* bitmaps/README:
[bpt/emacs.git] / src / keyboard.c
index 178fa06..51e228b 100644 (file)
@@ -5,10 +5,10 @@
 
 This file is part of GNU Emacs.
 
-GNU Emacs is free software; you can redistribute it and/or modify
+GNU Emacs is free software: you can redistribute it and/or modify
 it under the terms of the GNU General Public License as published by
-the Free Software Foundation; either version 3, or (at your option)
-any later version.
+the Free Software Foundation, either version 3 of the License, or
+(at your option) any later version.
 
 GNU Emacs is distributed in the hope that it will be useful,
 but WITHOUT ANY WARRANTY; without even the implied warranty of
@@ -16,24 +16,22 @@ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 GNU General Public License for more details.
 
 You should have received a copy of the GNU General Public License
-along with GNU Emacs; see the file COPYING.  If not, write to
-the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
-Boston, MA 02110-1301, USA.  */
+along with GNU Emacs.  If not, see <http://www.gnu.org/licenses/>.  */
 
 #include <config.h>
 #include <signal.h>
 #include <stdio.h>
+#include "lisp.h"
 #include "termchar.h"
 #include "termopts.h"
-#include "lisp.h"
+#include "frame.h"
 #include "termhooks.h"
 #include "macros.h"
 #include "keyboard.h"
-#include "frame.h"
 #include "window.h"
 #include "commands.h"
 #include "buffer.h"
-#include "charset.h"
+#include "character.h"
 #include "disptab.h"
 #include "dispextern.h"
 #include "syntax.h"
@@ -53,13 +51,10 @@ Boston, MA 02110-1301, USA.  */
 #include "msdos.h"
 #include <time.h>
 #else /* not MSDOS */
-#ifndef VMS
 #include <sys/ioctl.h>
-#endif
 #endif /* not MSDOS */
 
 #include "syssignal.h"
-#include "systty.h"
 
 #include <sys/types.h>
 #ifdef HAVE_UNISTD_H
@@ -79,8 +74,8 @@ Boston, MA 02110-1301, USA.  */
 #include "w32term.h"
 #endif /* HAVE_NTGUI */
 
-#ifdef MAC_OS
-#include "macterm.h"
+#ifdef HAVE_NS
+#include "nsterm.h"
 #endif
 
 #ifndef USE_CRT_DLL
@@ -96,48 +91,12 @@ volatile int interrupt_input_blocked;
    during the current critical section.  */
 int interrupt_input_pending;
 
-
-/* File descriptor to use for input.  */
-extern int input_fd;
-
-#ifdef HAVE_WINDOW_SYSTEM
-/* Make all keyboard buffers much bigger when using X windows.  */
-#ifdef MAC_OS8
-/* But not too big (local data > 32K error) if on Mac OS Classic.  */
-#define KBD_BUFFER_SIZE 512
-#else
-#define KBD_BUFFER_SIZE 4096
-#endif
-#else  /* No X-windows, character input */
 #define KBD_BUFFER_SIZE 4096
-#endif /* No X-windows */
-
-#undef abs
-#define abs(x)         ((x) >= 0 ? (x) : -(x))
-
-/* Following definition copied from eval.c */
-
-struct backtrace
-  {
-    struct backtrace *next;
-    Lisp_Object *function;
-    Lisp_Object *args; /* Points to vector of args. */
-    int nargs;         /* length of vector.  If nargs is UNEVALLED,
-                          args points to slot holding list of
-                          unevalled args */
-    char evalargs;
-    /* Nonzero means call value of debugger when done with this operation. */
-    char debug_on_exit;
-  };
 
-#ifdef MULTI_KBOARD
 KBOARD *initial_kboard;
 KBOARD *current_kboard;
 KBOARD *all_kboards;
 int single_kboard;
-#else
-KBOARD the_only_kboard;
-#endif
 
 /* Non-nil disable property on a command means
    do not execute it; call disabled-command-function's value instead.  */
@@ -165,16 +124,12 @@ int this_command_key_count_reset;
 Lisp_Object raw_keybuf;
 int raw_keybuf_count;
 
+/* Non-nil if the present key sequence was obtained by shift translation.  */
+Lisp_Object Vthis_command_keys_shift_translated;
+
 #define GROW_RAW_KEYBUF                                                        \
  if (raw_keybuf_count == XVECTOR (raw_keybuf)->size)                   \
-  {                                                                    \
-    int newsize = 2 * XVECTOR (raw_keybuf)->size;                      \
-    Lisp_Object new;                                                   \
-    new = Fmake_vector (make_number (newsize), Qnil);                  \
-    bcopy (XVECTOR (raw_keybuf)->contents, XVECTOR (new)->contents,    \
-          raw_keybuf_count * sizeof (Lisp_Object));                    \
-    raw_keybuf = new;                                                  \
-  }
+   raw_keybuf = larger_vector (raw_keybuf, raw_keybuf_count * 2, Qnil)  \
 
 /* Number of elements of this_command_keys
    that precede this key sequence.  */
@@ -189,18 +144,11 @@ extern int minbuf_level;
 
 extern int message_enable_multibyte;
 
-extern struct backtrace *backtrace_list;
-
 /* If non-nil, the function that implements the display of help.
    It's called with one argument, the help string to display.  */
 
 Lisp_Object Vshow_help_function;
 
-/* If a string, the message displayed before displaying a help-echo
-   in the echo area.  */
-
-Lisp_Object Vpre_help_message;
-
 /* Nonzero means do menu prompting.  */
 
 static int menu_prompting;
@@ -426,16 +374,6 @@ Lisp_Object Vecho_keystrokes;
 /* Form to evaluate (if non-nil) when Emacs is started.  */
 Lisp_Object Vtop_level;
 
-/* User-supplied table to translate input characters.  */
-Lisp_Object Vkeyboard_translate_table;
-
-/* Keymap mapping ASCII function key sequences onto their preferred forms.  */
-extern Lisp_Object Vfunction_key_map;
-
-/* Another keymap that maps key sequences into key sequences.
-   This one takes precedence over ordinary definitions.  */
-extern Lisp_Object Vkey_translation_map;
-
 /* If non-nil, this implements the current input method.  */
 Lisp_Object Vinput_method_function;
 Lisp_Object Qinput_method_function;
@@ -446,6 +384,7 @@ Lisp_Object Vinput_method_previous_message;
 
 /* Non-nil means deactivate the mark at end of this command.  */
 Lisp_Object Vdeactivate_mark;
+Lisp_Object Qdeactivate_mark;
 
 /* Menu bar specified in Lucid Emacs fashion.  */
 
@@ -459,6 +398,12 @@ Lisp_Object Qpre_command_hook, Vpre_command_hook;
 Lisp_Object Qpost_command_hook, Vpost_command_hook;
 Lisp_Object Qcommand_hook_internal, Vcommand_hook_internal;
 
+/* Parent keymap of terminal-local function-key-map instances.  */
+Lisp_Object Vfunction_key_map;
+
+/* Keymap of key translations that can override keymaps.  */
+Lisp_Object Vkey_translation_map;
+
 /* List of deferred actions to be performed at a later time.
    The precise format isn't relevant here; we just check whether it is nil.  */
 Lisp_Object Vdeferred_action_list;
@@ -476,11 +421,6 @@ FILE *dribble;
 /* Nonzero if input is available.  */
 int input_pending;
 
-/* 1 if should obey 0200 bit in input chars as "Meta", 2 if should
-   keep 0200 bit in input chars.  0 to ignore the 0200 bit.  */
-
-int meta_key;
-
 extern char *pending_malloc_warning;
 
 /* Circular buffer for pre-read keyboard input.  */
@@ -522,22 +462,21 @@ Lisp_Object Qmake_frame_visible;
 Lisp_Object Qselect_window;
 Lisp_Object Qhelp_echo;
 
-#ifdef HAVE_MOUSE
+#if defined (HAVE_MOUSE) || defined (HAVE_GPM)
 Lisp_Object Qmouse_fixup_help_message;
 #endif
 
 /* Symbols to denote kinds of events.  */
 Lisp_Object Qfunction_key;
 Lisp_Object Qmouse_click;
-#if defined (WINDOWSNT) || defined (MAC_OS)
+#if defined (WINDOWSNT)
 Lisp_Object Qlanguage_change;
 #endif
 Lisp_Object Qdrag_n_drop;
 Lisp_Object Qsave_session;
-#ifdef MAC_OS
-Lisp_Object Qmac_apple_event;
+#ifdef HAVE_DBUS
+Lisp_Object Qdbus_event;
 #endif
-
 /* Lisp_Object Qmouse_movement; - also an event header */
 
 /* Properties of event headers.  */
@@ -610,9 +549,6 @@ int interrupt_input;
 /* Nonzero while interrupts are temporarily deferred during redisplay.  */
 int interrupts_deferred;
 
-/* Nonzero means use ^S/^Q for flow control.  */
-int flow_control;
-
 /* Allow m- file to inhibit use of FIONREAD.  */
 #ifdef BROKEN_FIONREAD
 #undef FIONREAD
@@ -678,7 +614,7 @@ static Lisp_Object read_char_x_menu_prompt ();
 static Lisp_Object read_char_minibuf_menu_prompt P_ ((int, int,
                                                      Lisp_Object *));
 static Lisp_Object make_lispy_event P_ ((struct input_event *));
-#ifdef HAVE_MOUSE
+#if defined (HAVE_MOUSE) || defined (HAVE_GPM)
 static Lisp_Object make_lispy_movement P_ ((struct frame *, Lisp_Object,
                                            enum scroll_bar_part,
                                            Lisp_Object, Lisp_Object,
@@ -688,15 +624,14 @@ static Lisp_Object modify_event_symbol P_ ((int, unsigned, Lisp_Object,
                                            Lisp_Object, char **,
                                            Lisp_Object *, unsigned));
 static Lisp_Object make_lispy_switch_frame P_ ((Lisp_Object));
-static int parse_solitary_modifier P_ ((Lisp_Object));
-static int parse_solitary_modifier ();
 static void save_getcjmp P_ ((jmp_buf));
 static void save_getcjmp ();
 static void restore_getcjmp P_ ((jmp_buf));
 static Lisp_Object apply_modifiers P_ ((int, Lisp_Object));
 static void clear_event P_ ((struct input_event *));
-static void any_kboard_state P_ ((void));
+static Lisp_Object restore_kboard_configuration P_ ((Lisp_Object));
 static SIGTYPE interrupt_signal P_ ((int signalnum));
+static void handle_interrupt P_ ((void));
 static void timer_start_idle P_ ((void));
 static void timer_stop_idle P_ ((void));
 static void timer_resume_idle P_ ((void));
@@ -967,7 +902,7 @@ add_command_key (key)
                                       2 * ASIZE (this_command_keys),
                                       Qnil);
 
-  AREF (this_command_keys, this_command_key_count) = key;
+  ASET (this_command_keys, this_command_key_count, key);
   ++this_command_key_count;
 }
 
@@ -984,7 +919,7 @@ recursive_edit_1 ()
       specbind (Qstandard_input, Qt);
     }
 
-#ifdef HAVE_X_WINDOWS
+#ifdef HAVE_WINDOW_SYSTEM
   /* The command loop has started an hourglass timer, so we have to
      cancel it here, otherwise it will fire because the recursive edit
      can take some time.  Do not check for display_hourglass_p here,
@@ -1062,24 +997,20 @@ This function is called by the editor initialization to begin editing.  */)
      like it is done in the splash screen display, we have to
      make sure that we restore single_kboard as command_loop_1
      would have done if it were left normally.  */
-  record_unwind_protect (recursive_edit_unwind,
-                        Fcons (buffer, single_kboard ? Qt : Qnil));
+  if (command_loop_level > 0)
+    temporarily_switch_to_single_kboard (SELECTED_FRAME ());
+  record_unwind_protect (recursive_edit_unwind, buffer);
 
   recursive_edit_1 ();
   return unbind_to (count, Qnil);
 }
 
 Lisp_Object
-recursive_edit_unwind (info)
-     Lisp_Object info;
+recursive_edit_unwind (buffer)
+     Lisp_Object buffer;
 {
-  if (BUFFERP (XCAR (info)))
-    Fset_buffer (XCAR (info));
-
-  if (NILP (XCDR (info)))
-    any_kboard_state ();
-  else
-    single_kboard_state ();
+  if (BUFFERP (buffer))
+    Fset_buffer (buffer);
 
   command_loop_level--;
   update_mode_lines = 1;
@@ -1087,10 +1018,11 @@ recursive_edit_unwind (info)
 }
 
 \f
+#if 0  /* These two functions are now replaced with
+          temporarily_switch_to_single_kboard. */
 static void
 any_kboard_state ()
 {
-#ifdef MULTI_KBOARD
 #if 0 /* Theory: if there's anything in Vunread_command_events,
         it will right away be read by read_key_sequence,
         and then if we do switch KBOARDS, it will go into the side
@@ -1104,7 +1036,6 @@ any_kboard_state ()
   Vunread_command_events = Qnil;
 #endif
   single_kboard = 0;
-#endif
 }
 
 /* Switch to the single-kboard state, making current_kboard
@@ -1113,10 +1044,9 @@ any_kboard_state ()
 void
 single_kboard_state ()
 {
-#ifdef MULTI_KBOARD
   single_kboard = 1;
-#endif
 }
+#endif
 
 /* If we're in single_kboard state for kboard KBOARD,
    get out of it.  */
@@ -1125,10 +1055,8 @@ void
 not_single_kboard_state (kboard)
      KBOARD *kboard;
 {
-#ifdef MULTI_KBOARD
   if (kboard == current_kboard)
     single_kboard = 0;
-#endif
 }
 
 /* Maintain a stack of kboards, so other parts of Emacs
@@ -1144,10 +1072,9 @@ struct kboard_stack
 static struct kboard_stack *kboard_stack;
 
 void
-push_frame_kboard (f)
-     FRAME_PTR f;
+push_kboard (k)
+     struct kboard *k;
 {
-#ifdef MULTI_KBOARD
   struct kboard_stack *p
     = (struct kboard_stack *) xmalloc (sizeof (struct kboard_stack));
 
@@ -1155,20 +1082,103 @@ push_frame_kboard (f)
   p->kboard = current_kboard;
   kboard_stack = p;
 
-  current_kboard = FRAME_KBOARD (f);
-#endif
+  current_kboard = k;
 }
 
 void
-pop_frame_kboard ()
+pop_kboard ()
 {
-#ifdef MULTI_KBOARD
+  struct terminal *t;
   struct kboard_stack *p = kboard_stack;
-  current_kboard = p->kboard;
+  int found = 0;
+  for (t = terminal_list; t; t = t->next_terminal)
+    {
+      if (t->kboard == p->kboard)
+        {
+          current_kboard = p->kboard;
+          found = 1;
+          break;
+        }
+    }
+  if (!found)
+    {
+      /* The terminal we remembered has been deleted.  */
+      current_kboard = FRAME_KBOARD (SELECTED_FRAME ());
+      single_kboard = 0;
+    }
   kboard_stack = p->next;
   xfree (p);
+}
+
+/* Switch to single_kboard mode, making current_kboard the only KBOARD
+  from which further input is accepted.  If F is non-nil, set its
+  KBOARD as the current keyboard.
+
+  This function uses record_unwind_protect to return to the previous
+  state later.
+
+  If Emacs is already in single_kboard mode, and F's keyboard is
+  locked, then this function will throw an errow.  */
+
+void
+temporarily_switch_to_single_kboard (f)
+     struct frame *f;
+{
+  int was_locked = single_kboard;
+  if (was_locked)
+    {
+      if (f != NULL && FRAME_KBOARD (f) != current_kboard)
+        /* We can not switch keyboards while in single_kboard mode.
+           In rare cases, Lisp code may call `recursive-edit' (or
+           `read-minibuffer' or `y-or-n-p') after it switched to a
+           locked frame.  For example, this is likely to happen
+           when server.el connects to a new terminal while Emacs is in
+           single_kboard mode.  It is best to throw an error instead
+           of presenting the user with a frozen screen.  */
+        error ("Terminal %d is locked, cannot read from it",
+               FRAME_TERMINAL (f)->id);
+      else
+        /* This call is unnecessary, but helps
+           `restore_kboard_configuration' discover if somebody changed
+           `current_kboard' behind our back.  */
+        push_kboard (current_kboard);
+    }
+  else if (f != NULL)
+    current_kboard = FRAME_KBOARD (f);
+  single_kboard = 1;
+  record_unwind_protect (restore_kboard_configuration,
+                         (was_locked ? Qt : Qnil));
+}
+
+#if 0 /* This function is not needed anymore.  */
+void
+record_single_kboard_state ()
+{
+  if (single_kboard)
+    push_kboard (current_kboard);
+  record_unwind_protect (restore_kboard_configuration,
+                         (single_kboard ? Qt : Qnil));
+}
 #endif
+
+static Lisp_Object
+restore_kboard_configuration (was_locked)
+     Lisp_Object was_locked;
+{
+  if (NILP (was_locked))
+    single_kboard = 0;
+  else
+    {
+      struct kboard *prev = current_kboard;
+      single_kboard = 1;
+      pop_kboard ();
+      /* The pop should not change the kboard.  */
+      if (single_kboard && current_kboard != prev)
+        abort ();
+    }
+  return Qnil;
 }
+
 \f
 /* Handle errors that are not handled at inner levels
    by printing an error message and returning to the editor command loop.  */
@@ -1180,7 +1190,7 @@ cmd_error (data)
   Lisp_Object old_level, old_length;
   char macroerror[50];
 
-#ifdef HAVE_X_WINDOWS
+#ifdef HAVE_WINDOW_SYSTEM
   if (display_hourglass_p)
     cancel_hourglass ();
 #endif
@@ -1216,7 +1226,7 @@ cmd_error (data)
   Vquit_flag = Qnil;
 
   Vinhibit_quit = Qnil;
-#ifdef MULTI_KBOARD
+#if 0 /* This shouldn't be necessary anymore. --lorentey */
   if (command_loop_level == 0 && minibuf_level == 0)
     any_kboard_state ();
 #endif
@@ -1250,16 +1260,12 @@ cmd_error_internal (data, context)
   /* Use user's specified output function if any.  */
   if (!NILP (Vcommand_error_function))
     call3 (Vcommand_error_function, data,
-          build_string (context ? context : ""),
+          context ? build_string (context) : empty_unibyte_string,
           Vsignaling_function);
   /* If the window system or terminal frame hasn't been initialized
      yet, or we're not interactive, write the message to stderr and exit.  */
   else if (!sf->glyphs_initialized_p
-          /* This is the case of the frame dumped with Emacs, when we're
-             running under a window system.  */
-          || (!NILP (Vwindow_system)
-              && !inhibit_window_system
-              && FRAME_TERMCAP_P (sf))
+          || FRAME_INITIAL_P (sf)
           || noninteractive)
     {
       print_error_message (data, Qexternal_debugging_output,
@@ -1302,10 +1308,12 @@ command_loop ()
     while (1)
       {
        internal_catch (Qtop_level, top_level_1, Qnil);
-       /* Reset single_kboard in case top-level set it while
-          evaluating an -f option, or we are stuck there for some
-          other reason.  */
-       any_kboard_state ();
+#if 0 /* This shouldn't be necessary anymore.  --lorentey  */
+        /* Reset single_kboard in case top-level set it while
+           evaluating an -f option, or we are stuck there for some
+           other reason. */
+        any_kboard_state ();
+#endif
        internal_catch (Qtop_level, command_loop_2, Qnil);
        executing_kbd_macro = Qnil;
 
@@ -1356,7 +1364,7 @@ DEFUN ("top-level", Ftop_level, Stop_level, 0, 0, "",
        doc: /* Exit all recursive editing levels.  */)
      ()
 {
-#ifdef HAVE_X_WINDOWS
+#ifdef HAVE_WINDOW_SYSTEM
   if (display_hourglass_p)
     cancel_hourglass ();
 #endif
@@ -1391,7 +1399,7 @@ DEFUN ("abort-recursive-edit", Fabort_recursive_edit, Sabort_recursive_edit, 0,
   return Qnil;
 }
 \f
-#ifdef HAVE_MOUSE
+#if defined (HAVE_MOUSE) || defined (HAVE_GPM)
 
 /* Restore mouse tracking enablement.  See Ftrack_mouse for the only use
    of this function.  */
@@ -1467,7 +1475,7 @@ some_mouse_moved ()
   return 0;
 }
 
-#endif /* HAVE_MOUSE */
+#endif /* HAVE_MOUSE || HAVE_GPM */
 \f
 /* This is the actual command reading loop,
    sans error-handling encapsulation.  */
@@ -1479,7 +1487,7 @@ static void adjust_point_for_property P_ ((int, int));
 
 /* Cancel hourglass from protect_unwind.
    ARG is not used.  */
-#ifdef HAVE_X_WINDOWS
+#ifdef HAVE_WINDOW_SYSTEM
 static Lisp_Object
 cancel_hourglass_unwind (arg)
      Lisp_Object arg;
@@ -1497,13 +1505,12 @@ command_loop_1 ()
   int nonundocount;
   Lisp_Object keybuf[30];
   int i;
-  int no_direct;
   int prev_modiff = 0;
   struct buffer *prev_buffer = NULL;
-#ifdef MULTI_KBOARD
+#if 0 /* This shouldn't be necessary anymore.  --lorentey  */
   int was_locked = single_kboard;
 #endif
-  int already_adjusted;
+  int already_adjusted = 0;
 
   current_kboard->Vprefix_arg = Qnil;
   current_kboard->Vlast_prefix_arg = Qnil;
@@ -1555,8 +1562,6 @@ command_loop_1 ()
       while (pending_malloc_warning)
        display_malloc_warning ();
 
-      no_direct = 0;
-
       Vdeactivate_mark = Qnil;
 
       /* If minibuffer on and echo area in use,
@@ -1588,11 +1593,6 @@ command_loop_1 ()
            }
        }
 
-#ifdef C_ALLOCA
-      alloca (0);              /* Cause a garbage collection now */
-                               /* Since we can free the most stuff here.  */
-#endif /* C_ALLOCA */
-
 #if 0
       /* Select the frame that the last event came from.  Usually,
         switch-frame events will take care of this, but if some lisp
@@ -1614,6 +1614,7 @@ command_loop_1 ()
       Vthis_command = Qnil;
       real_this_command = Qnil;
       Vthis_original_command = Qnil;
+      Vthis_command_keys_shift_translated = Qnil;
 
       /* Read next key sequence; i gets its length.  */
       i = read_key_sequence (keybuf, sizeof keybuf / sizeof keybuf[0],
@@ -1720,14 +1721,16 @@ command_loop_1 ()
        }
       else
        {
-         if (NILP (current_kboard->Vprefix_arg) && ! no_direct)
+         if (NILP (current_kboard->Vprefix_arg))
            {
              /* In case we jump to directly_done.  */
              Vcurrent_prefix_arg = current_kboard->Vprefix_arg;
 
              /* Recognize some common commands in common situations and
                 do them directly.  */
-             if (EQ (Vthis_command, Qforward_char) && PT < ZV)
+             if (EQ (Vthis_command, Qforward_char) && PT < ZV
+                 && NILP (Vthis_command_keys_shift_translated)
+                 && !CONSP (Vtransient_mark_mode))
                {
                   struct Lisp_Char_Table *dp
                    = window_display_table (XWINDOW (selected_window));
@@ -1752,7 +1755,7 @@ command_loop_1 ()
                          : (lose >= 0x20 && lose < 0x7f))
                      /* To extract the case of continuation on
                          wide-column characters.  */
-                     && (WIDTH_BY_CHAR_HEAD (FETCH_BYTE (PT_BYTE)) == 1)
+                     && ASCII_BYTE_P (lose)
                      && (XFASTINT (XWINDOW (selected_window)->last_modified)
                          >= MODIFF)
                      && (XFASTINT (XWINDOW (selected_window)->last_overlay_modified)
@@ -1767,7 +1770,9 @@ command_loop_1 ()
                    direct_output_forward_char (1);
                  goto directly_done;
                }
-             else if (EQ (Vthis_command, Qbackward_char) && PT > BEGV)
+             else if (EQ (Vthis_command, Qbackward_char) && PT > BEGV
+                      && NILP (Vthis_command_keys_shift_translated)
+                      && !CONSP (Vtransient_mark_mode))
                {
                   struct Lisp_Char_Table *dp
                    = window_display_table (XWINDOW (selected_window));
@@ -1809,7 +1814,7 @@ command_loop_1 ()
                {
                  unsigned int c
                    = translate_char (Vtranslation_table_for_input,
-                                     XFASTINT (last_command_char), 0, 0, 0);
+                                     XFASTINT (last_command_char));
                  int value;
                  if (NILP (Vexecuting_kbd_macro)
                      && !EQ (minibuf_window, selected_window))
@@ -1857,7 +1862,7 @@ command_loop_1 ()
          /* Here for a command that isn't executed directly */
 
           {
-#ifdef HAVE_X_WINDOWS
+#ifdef HAVE_WINDOW_SYSTEM
             int scount = SPECPDL_INDEX ();
 
             if (display_hourglass_p
@@ -1873,7 +1878,7 @@ command_loop_1 ()
               Fundo_boundary ();
             Fcommand_execute (Vthis_command, Qnil, Qnil, Qnil);
 
-#ifdef HAVE_X_WINDOWS
+#ifdef HAVE_WINDOW_SYSTEM
          /* Do not check display_hourglass_p here, because
             Fcommand_execute could change it, but we should cancel
             hourglass cursor anyway.
@@ -1927,25 +1932,16 @@ command_loop_1 ()
 
       if (!NILP (current_buffer->mark_active) && !NILP (Vrun_hooks))
        {
-         /* Setting transient-mark-mode to `only' is a way of
-            turning it on for just one command.  */
-
+         /* In Emacs 22, setting transient-mark-mode to `only' was a
+            way of turning it on for just one command.  This usage is
+            obsolete, but support it anyway.  */
          if (EQ (Vtransient_mark_mode, Qidentity))
            Vtransient_mark_mode = Qnil;
-         if (EQ (Vtransient_mark_mode, Qonly))
+         else if (EQ (Vtransient_mark_mode, Qonly))
            Vtransient_mark_mode = Qidentity;
 
-         if (!NILP (Vdeactivate_mark) && !NILP (Vtransient_mark_mode))
-           {
-             /* We could also call `deactivate'mark'.  */
-             if (EQ (Vtransient_mark_mode, Qlambda))
-               Vtransient_mark_mode = Qnil;
-             else
-               {
-                 current_buffer->mark_active = Qnil;
-                 call1 (Vrun_hooks, intern ("deactivate-mark-hook"));
-               }
-           }
+         if (!NILP (Vdeactivate_mark))
+           call0 (Qdeactivate_mark);
          else if (current_buffer != prev_buffer || MODIFF != prev_modiff)
            call1 (Vrun_hooks, intern ("activate-mark-hook"));
        }
@@ -1964,10 +1960,9 @@ command_loop_1 ()
       if (!NILP (current_kboard->defining_kbd_macro)
          && NILP (current_kboard->Vprefix_arg))
        finalize_kbd_macro_chars ();
-
-#ifdef MULTI_KBOARD
+#if 0 /* This shouldn't be necessary anymore.  --lorentey  */
       if (!was_locked)
-       any_kboard_state ();
+        any_kboard_state ();
 #endif
     }
 }
@@ -1987,7 +1982,7 @@ adjust_point_for_property (last_pt, modified)
      int last_pt;
      int modified;
 {
-  int beg, end;
+  EMACS_INT beg, end;
   Lisp_Object val, overlay, tmp;
   int check_composition = 1, check_display = 1, check_invisible = 1;
   int orig_pt = PT;
@@ -1996,6 +1991,7 @@ adjust_point_for_property (last_pt, modified)
      can't be usefully combined anyway.  */
   while (check_composition || check_display || check_invisible)
     {
+      /* FIXME: check `intangible'.  */
       if (check_composition
          && PT > BEGV && PT < ZV
          && get_property_and_range (PT, Qcomposition, &val, &beg, &end, Qnil)
@@ -2206,7 +2202,10 @@ void
 start_polling ()
 {
 #ifdef POLL_FOR_INPUT
-  if (read_socket_hook && !interrupt_input)
+  /* XXX This condition was (read_socket_hook && !interrupt_input),
+     but read_socket_hook is not global anymore.  Let's pretend that
+     it's always set. */
+  if (!interrupt_input)
     {
       /* Turn alarm handling on unconditionally.  It might have
         been turned off in process.c.  */
@@ -2240,7 +2239,10 @@ int
 input_polling_used ()
 {
 #ifdef POLL_FOR_INPUT
-  return read_socket_hook && !interrupt_input;
+  /* XXX This condition was (read_socket_hook && !interrupt_input),
+     but read_socket_hook is not global anymore.  Let's pretend that
+     it's always set. */
+  return !interrupt_input;
 #else
   return 0;
 #endif
@@ -2252,7 +2254,10 @@ void
 stop_polling ()
 {
 #ifdef POLL_FOR_INPUT
-  if (read_socket_hook && !interrupt_input)
+  /* XXX This condition was (read_socket_hook && !interrupt_input),
+     but read_socket_hook is not global anymore.  Let's pretend that
+     it's always set. */
+  if (!interrupt_input)
     ++poll_suppress_count;
 #endif
 }
@@ -2394,7 +2399,7 @@ show_help_echo (help, window, object, pos, ok_to_overwrite_keystroke_echo)
        return;
     }
 
-#ifdef HAVE_MOUSE
+#if defined (HAVE_MOUSE) || defined (HAVE_GPM)
   if (!noninteractive && STRINGP (help))
     {
       /* The mouse-fixup-help-message Lisp function can call
@@ -2413,37 +2418,6 @@ show_help_echo (help, window, object, pos, ok_to_overwrite_keystroke_echo)
     {
       if (!NILP (Vshow_help_function))
        call1 (Vshow_help_function, help);
-      else if (/* Don't overwrite minibuffer contents.  */
-              !MINI_WINDOW_P (XWINDOW (selected_window))
-              /* Don't overwrite a keystroke echo.  */
-              && (NILP (echo_message_buffer)
-                  || ok_to_overwrite_keystroke_echo)
-              /* Don't overwrite a prompt.  */
-              && !cursor_in_echo_area)
-       {
-         if (STRINGP (help))
-           {
-             int count = SPECPDL_INDEX ();
-
-             if (!help_echo_showing_p)
-               Vpre_help_message = current_message ();
-
-             specbind (Qmessage_truncate_lines, Qt);
-             message3_nolog (help, SBYTES (help),
-                             STRING_MULTIBYTE (help));
-             unbind_to (count, Qnil);
-           }
-         else if (STRINGP (Vpre_help_message))
-           {
-             message3_nolog (Vpre_help_message,
-                             SBYTES (Vpre_help_message),
-                             STRING_MULTIBYTE (Vpre_help_message));
-             Vpre_help_message = Qnil;
-           }
-         else
-           message (0);
-       }
-
       help_echo_showing_p = STRINGP (help);
     }
 }
@@ -2467,10 +2441,6 @@ read_char_help_form_unwind (arg)
   return Qnil;
 }
 
-#ifdef MULTI_KBOARD
-static jmp_buf wrong_kboard_jmpbuf;
-#endif
-
 #define STOP_POLLING                                   \
 do { if (! polling_stopped_here) stop_polling ();      \
        polling_stopped_here = 1; } while (0)
@@ -2497,6 +2467,9 @@ do { if (polling_stopped_here) start_polling ();  \
    if we used a mouse menu to read the input, or zero otherwise.  If
    USED_MOUSE_MENU is null, we don't dereference it.
 
+   Value is -2 when we find input on another keyboard.  A second call
+   to read_char will read it.
+
    If END_TIME is non-null, it is a pointer to an EMACS_TIME
    specifying the maximum time to wait until.  If no input arrives by
    that time, stop waiting and return nil.
@@ -2523,6 +2496,7 @@ read_char (commandflag, nmaps, maps, prev_event, used_mouse_menu, end_time)
   volatile int reread;
   struct gcpro gcpro1, gcpro2;
   int polling_stopped_here = 0;
+  struct kboard *orig_kboard = current_kboard;
 
   also_record = Qnil;
 
@@ -2661,6 +2635,8 @@ read_char (commandflag, nmaps, maps, prev_event, used_mouse_menu, end_time)
   /* if redisplay was requested */
   if (commandflag >= 0)
     {
+      int echo_current = EQ (echo_message_buffer, echo_area_buffer[0]);
+
        /* If there is pending input, process any events which are not
           user-visible, such as X selection_request events.  */
       if (input_pending
@@ -2684,6 +2660,12 @@ read_char (commandflag, nmaps, maps, prev_event, used_mouse_menu, end_time)
          swallow_events (0);
          /* If that cleared input_pending, try again to redisplay.  */
        }
+
+      /* Prevent the redisplay we just did
+        from messing up echoing of the input after the prompt.  */
+      if (commandflag == 0 && echo_current)
+       echo_message_buffer = echo_area_buffer[0];
+
     }
 
   /* Message turns off echoing unless more keystrokes turn it on again.
@@ -2737,6 +2719,10 @@ read_char (commandflag, nmaps, maps, prev_event, used_mouse_menu, end_time)
       && !detect_input_pending_run_timers (0))
     {
       c = read_char_minibuf_menu_prompt (commandflag, nmaps, maps);
+
+      if (INTEGERP (c) && XINT (c) == -2)
+        return c;               /* wrong_kboard_jmpbuf */
+
       if (! NILP (c))
        {
          key_already_recorded = 1;
@@ -2753,6 +2739,7 @@ read_char (commandflag, nmaps, maps, prev_event, used_mouse_menu, end_time)
   jmpcount = SPECPDL_INDEX ();
   if (_setjmp (local_getcjmp))
     {
+      /* Handle quits while reading the keyboard.  */
       /* We must have saved the outer value of getcjmp here,
         so restore it now.  */
       restore_getcjmp (save_jump);
@@ -2765,7 +2752,6 @@ read_char (commandflag, nmaps, maps, prev_event, used_mouse_menu, end_time)
       if (!NILP (Vinhibit_quit))
        Vquit_flag = Qnil;
 
-#ifdef MULTI_KBOARD
       {
        KBOARD *kb = FRAME_KBOARD (XFRAME (selected_frame));
        if (kb != current_kboard)
@@ -2790,10 +2776,9 @@ read_char (commandflag, nmaps, maps, prev_event, used_mouse_menu, end_time)
            /* This is going to exit from read_char
               so we had better get rid of this frame's stuff.  */
            UNGCPRO;
-           longjmp (wrong_kboard_jmpbuf, 1);
+            return make_number (-2); /* wrong_kboard_jmpbuf */
          }
       }
-#endif
       goto non_reread;
     }
 
@@ -2927,6 +2912,19 @@ read_char (commandflag, nmaps, maps, prev_event, used_mouse_menu, end_time)
        }
     }
 
+  /* Notify the caller if an autosave hook, or a timer, sentinel or
+     filter in the sit_for calls above have changed the current
+     kboard.  This could happen if they use the minibuffer or start a
+     recursive edit, like the fancy splash screen in server.el's
+     filter.  If this longjmp wasn't here, read_key_sequence would
+     interpret the next key sequence using the wrong translation
+     tables and function keymaps.  */
+  if (NILP (c) && current_kboard != orig_kboard)
+    {
+      UNGCPRO;
+      return make_number (-2);  /* wrong_kboard_jmpbuf */
+    }
+
   /* If this has become non-nil here, it has been set by a timer
      or sentinel or filter.  */
   if (CONSP (Vunread_command_events))
@@ -2956,7 +2954,6 @@ read_char (commandflag, nmaps, maps, prev_event, used_mouse_menu, end_time)
        }
     }
 
-#ifdef MULTI_KBOARD
   /* If current_kboard's side queue is empty check the other kboards.
      If one of them has data that we have not yet seen here,
      switch to it and process the data waiting for it.
@@ -2975,10 +2972,9 @@ read_char (commandflag, nmaps, maps, prev_event, used_mouse_menu, end_time)
            /* This is going to exit from read_char
               so we had better get rid of this frame's stuff.  */
            UNGCPRO;
-           longjmp (wrong_kboard_jmpbuf, 1);
+            return make_number (-2); /* wrong_kboard_jmpbuf */
          }
     }
-#endif
 
  wrong_kboard:
 
@@ -3008,7 +3004,6 @@ read_char (commandflag, nmaps, maps, prev_event, used_mouse_menu, end_time)
       c = kbd_buffer_get_event (&kb, used_mouse_menu, end_time);
       restore_getcjmp (save_jump);
 
-#ifdef MULTI_KBOARD
       if (! NILP (c) && (kb != current_kboard))
        {
          Lisp_Object link = kb->kbd_queue;
@@ -3031,9 +3026,8 @@ read_char (commandflag, nmaps, maps, prev_event, used_mouse_menu, end_time)
          /* This is going to exit from read_char
             so we had better get rid of this frame's stuff.  */
          UNGCPRO;
-         longjmp (wrong_kboard_jmpbuf, 1);
+          return make_number (-2);
        }
-#endif
     }
 
   /* Terminate Emacs in batch mode if at eof.  */
@@ -3086,7 +3080,11 @@ read_char (commandflag, nmaps, maps, prev_event, used_mouse_menu, end_time)
 
   if (!NILP (tem))
     {
+#if 0 /* This shouldn't be necessary anymore. --lorentey  */
       int was_locked = single_kboard;
+      int count = SPECPDL_INDEX ();
+      record_single_kboard_state ();
+#endif
 
       last_input_char = c;
       Fcommand_execute (tem, Qnil, Fvector (1, &last_input_char), Qt);
@@ -3098,9 +3096,12 @@ read_char (commandflag, nmaps, maps, prev_event, used_mouse_menu, end_time)
           example banishing the mouse under mouse-avoidance-mode.  */
        timer_resume_idle ();
 
+#if 0 /* This shouldn't be necessary anymore. --lorentey  */
       /* Resume allowing input from any kboard, if that was true before.  */
       if (!was_locked)
        any_kboard_state ();
+      unbind_to (count, Qnil);
+#endif
 
       goto retry;
     }
@@ -3112,15 +3113,15 @@ read_char (commandflag, nmaps, maps, prev_event, used_mouse_menu, end_time)
       if (XINT (c) == -1)
        goto exit;
 
-      if ((STRINGP (Vkeyboard_translate_table)
-          && SCHARS (Vkeyboard_translate_table) > (unsigned) XFASTINT (c))
-         || (VECTORP (Vkeyboard_translate_table)
-             && XVECTOR (Vkeyboard_translate_table)->size > (unsigned) XFASTINT (c))
-         || (CHAR_TABLE_P (Vkeyboard_translate_table)
-             && CHAR_VALID_P (XINT (c), 0)))
+      if ((STRINGP (current_kboard->Vkeyboard_translate_table)
+          && SCHARS (current_kboard->Vkeyboard_translate_table) > (unsigned) XFASTINT (c))
+         || (VECTORP (current_kboard->Vkeyboard_translate_table)
+             && XVECTOR (current_kboard->Vkeyboard_translate_table)->size > (unsigned) XFASTINT (c))
+         || (CHAR_TABLE_P (current_kboard->Vkeyboard_translate_table)
+             && CHARACTERP (c)))
        {
          Lisp_Object d;
-         d = Faref (Vkeyboard_translate_table, c);
+         d = Faref (current_kboard->Vkeyboard_translate_table, c);
          /* nil in keyboard-translate-table means no translation.  */
          if (!NILP (d))
            c = d;
@@ -3646,7 +3647,7 @@ readable_events (flags)
        return 1;
     }
 
-#ifdef HAVE_MOUSE
+#if defined (HAVE_MOUSE) || defined (HAVE_GPM)
   if (!(flags & READABLE_EVENTS_IGNORE_SQUEEZABLES)
       && !NILP (do_mouse_tracking) && some_mouse_moved ())
     return 1;
@@ -3669,7 +3670,6 @@ readable_events (flags)
 /* Set this for debugging, to have a way to get out */
 int stop_character;
 
-#ifdef MULTI_KBOARD
 static KBOARD *
 event_to_kboard (event)
      struct input_event *event;
@@ -3689,7 +3689,6 @@ event_to_kboard (event)
   else
     return FRAME_KBOARD (XFRAME (frame));
 }
-#endif
 
 
 Lisp_Object Vthrow_on_input;
@@ -3739,13 +3738,10 @@ kbd_buffer_store_event_hold (event, hold_quit)
 
       if (c == quit_char)
        {
-#ifdef MULTI_KBOARD
-         KBOARD *kb;
+         KBOARD *kb = FRAME_KBOARD (XFRAME (event->frame_or_window));
          struct input_event *sp;
 
-         if (single_kboard
-             && (kb = FRAME_KBOARD (XFRAME (event->frame_or_window)),
-                 kb != current_kboard))
+         if (single_kboard && kb != current_kboard)
            {
              kb->kbd_queue
                = Fcons (make_lispy_switch_frame (event->frame_or_window),
@@ -3765,7 +3761,6 @@ kbd_buffer_store_event_hold (event, hold_quit)
                }
              return;
            }
-#endif
 
          if (hold_quit)
            {
@@ -3788,7 +3783,7 @@ kbd_buffer_store_event_hold (event, hold_quit)
          }
 
          last_event_timestamp = event->timestamp;
-         interrupt_signal (0 /* dummy */);
+         handle_interrupt ();
          return;
        }
 
@@ -3921,8 +3916,9 @@ discard_mouse_events ()
 
       if (sp->kind == MOUSE_CLICK_EVENT
          || sp->kind == WHEEL_EVENT
-#ifdef WINDOWSNT
-         || sp->kind == W32_SCROLL_BAR_CLICK_EVENT
+          || sp->kind == HORIZ_WHEEL_EVENT
+#ifdef HAVE_GPM
+         || sp->kind == GPM_CLICK_EVENT
 #endif
          || sp->kind == SCROLL_BAR_CLICK_EVENT)
        {
@@ -4001,10 +3997,10 @@ kbd_buffer_get_event (kbp, used_mouse_menu, end_time)
         events.  */
       if (CONSP (Vunread_command_events))
        break;
-      
+
       if (kbd_fetch_ptr != kbd_store_ptr)
        break;
-#ifdef HAVE_MOUSE
+#if defined (HAVE_MOUSE) || defined (HAVE_GPM)
       if (!NILP (do_mouse_tracking) && some_mouse_moved ())
        break;
 #endif
@@ -4017,16 +4013,13 @@ kbd_buffer_get_event (kbp, used_mouse_menu, end_time)
       /* One way or another, wait until input is available; then, if
         interrupt handlers have not read it, read it now.  */
 
-#ifdef OLDVMS
-      wait_for_kbd_input ();
-#else
 /* Note SIGIO has been undef'd if FIONREAD is missing.  */
 #ifdef SIGIO
       gobble_input (0);
 #endif /* SIGIO */
       if (kbd_fetch_ptr != kbd_store_ptr)
        break;
-#ifdef HAVE_MOUSE
+#if defined (HAVE_MOUSE) || defined (HAVE_GPM)
       if (!NILP (do_mouse_tracking) && some_mouse_moved ())
        break;
 #endif
@@ -4050,7 +4043,6 @@ kbd_buffer_get_event (kbp, used_mouse_menu, end_time)
       if (!interrupt_input && kbd_fetch_ptr == kbd_store_ptr)
        /* Pass 1 for EXPECT since we just waited to have input.  */
        read_avail_input (1);
-#endif /* not VMS */
     }
 
   if (CONSP (Vunread_command_events))
@@ -4075,13 +4067,9 @@ kbd_buffer_get_event (kbp, used_mouse_menu, end_time)
 
       last_event_timestamp = event->timestamp;
 
-#ifdef MULTI_KBOARD
       *kbp = event_to_kboard (event);
       if (*kbp == 0)
        *kbp = current_kboard;  /* Better than returning null ptr?  */
-#else
-      *kbp = &the_only_kboard;
-#endif
 
       obj = Qnil;
 
@@ -4108,7 +4096,8 @@ kbd_buffer_get_event (kbp, used_mouse_menu, end_time)
 #endif
        }
 
-#if defined (HAVE_X11) || defined (HAVE_NTGUI) || defined (MAC_OS)
+#if defined (HAVE_X11) || defined (HAVE_NTGUI) \
+    || defined (HAVE_NS)
       else if (event->kind == DELETE_WINDOW_EVENT)
        {
          /* Make an event (delete-frame (FRAME)).  */
@@ -4117,7 +4106,8 @@ kbd_buffer_get_event (kbp, used_mouse_menu, end_time)
          kbd_fetch_ptr = event + 1;
        }
 #endif
-#if defined (HAVE_X11) || defined (HAVE_NTGUI) || defined (MAC_OS)
+#if defined (HAVE_X11) || defined (HAVE_NTGUI) \
+    || defined (HAVE_NS)
       else if (event->kind == ICONIFY_EVENT)
        {
          /* Make an event (iconify-frame (FRAME)).  */
@@ -4139,8 +4129,8 @@ kbd_buffer_get_event (kbp, used_mouse_menu, end_time)
          XSETBUFFER (obj, current_buffer);
          kbd_fetch_ptr = event + 1;
        }
-#if defined (USE_X_TOOLKIT) || defined (HAVE_NTGUI) || defined (MAC_OS) \
-    || defined (USE_GTK)
+#if defined (USE_X_TOOLKIT) || defined (HAVE_NTGUI) \
+    || defined(HAVE_NS) || defined (USE_GTK)
       else if (event->kind == MENU_BAR_ACTIVATE_EVENT)
        {
          kbd_fetch_ptr = event + 1;
@@ -4149,16 +4139,11 @@ kbd_buffer_get_event (kbp, used_mouse_menu, end_time)
            x_activate_menubar (XFRAME (event->frame_or_window));
        }
 #endif
-#if defined (WINDOWSNT) || defined (MAC_OS)
+#if defined (WINDOWSNT)
       else if (event->kind == LANGUAGE_CHANGE_EVENT)
        {
-#ifdef MAC_OS
-         /* Make an event (language-change (KEY_SCRIPT)).  */
-         obj = Fcons (make_number (event->code), Qnil);
-#else
          /* Make an event (language-change (FRAME CHARSET LCID)).  */
          obj = Fcons (event->frame_or_window, Qnil);
-#endif
          obj = Fcons (Qlanguage_change, Fcons (obj, Qnil));
          kbd_fetch_ptr = event + 1;
        }
@@ -4213,6 +4198,13 @@ kbd_buffer_get_event (kbp, used_mouse_menu, end_time)
          internal_last_event_frame = frame;
          kbd_fetch_ptr = event + 1;
        }
+#ifdef HAVE_DBUS
+      else if (event->kind == DBUS_EVENT)
+       {
+         obj = make_lispy_event (event);
+         kbd_fetch_ptr = event + 1;
+       }
+#endif
       else
        {
          /* If this event is on a different frame, return a switch-frame this
@@ -4242,8 +4234,8 @@ kbd_buffer_get_event (kbp, used_mouse_menu, end_time)
            {
              obj = make_lispy_event (event);
 
-#if defined (USE_X_TOOLKIT) || defined (HAVE_NTGUI) || defined(MAC_OS) \
-    || defined (USE_GTK)
+#if defined (USE_X_TOOLKIT) || defined (HAVE_NTGUI) \
+    || defined(HAVE_NS) || defined (USE_GTK)
              /* If this was a menu selection, then set the flag to inhibit
                 writing to last_nonmenu_event.  Don't do this if the event
                 we're returning is (menu-bar), though; that indicates the
@@ -4262,7 +4254,7 @@ kbd_buffer_get_event (kbp, used_mouse_menu, end_time)
            }
        }
     }
-#ifdef HAVE_MOUSE
+#if defined (HAVE_MOUSE) || defined (HAVE_GPM)
   /* Try generating a mouse motion event.  */
   else if (!NILP (do_mouse_tracking) && some_mouse_moved ())
     {
@@ -4273,11 +4265,15 @@ kbd_buffer_get_event (kbp, used_mouse_menu, end_time)
       unsigned long time;
 
       *kbp = current_kboard;
-      /* Note that this uses F to determine which display to look at.
+      /* Note that this uses F to determine which terminal to look at.
         If there is no valid info, it does not store anything
         so x remains nil.  */
       x = Qnil;
-      (*mouse_position_hook) (&f, 0, &bar_window, &part, &x, &y, &time);
+
+      /* XXX Can f or mouse_position_hook be NULL here? */
+      if (f && FRAME_TERMINAL (f)->mouse_position_hook)
+        (*FRAME_TERMINAL (f)->mouse_position_hook) (&f, 0, &bar_window,
+                                                    &part, &x, &y, &time);
 
       obj = Qnil;
 
@@ -4303,7 +4299,7 @@ kbd_buffer_get_event (kbp, used_mouse_menu, end_time)
       if (!NILP (x) && NILP (obj))
        obj = make_lispy_movement (f, bar_window, part, x, y, time);
     }
-#endif /* HAVE_MOUSE */
+#endif /* HAVE_MOUSE || HAVE GPM */
   else
     /* We were promised by the above while loop that there was
        something for us to read!  */
@@ -4418,6 +4414,13 @@ timer_resume_idle ()
 /* This is only for debugging.  */
 struct input_event last_timer_event;
 
+/* List of elisp functions to call, delayed because they were generated in
+   a context where Elisp could not be safely run (e.g. redisplay, signal,
+   ...).  Each lement has the form (FUN . ARGS).  */
+Lisp_Object pending_funcalls;
+
+extern Lisp_Object Qapply;
+
 /* Check whether a timer has fired.  To prevent larger problems we simply
    disregard elements that are not proper timers.  Do not make a circular
    timer list for the time being.
@@ -4454,6 +4457,14 @@ timer_check (do_it_now)
   chosen_timer = Qnil;
   GCPRO3 (timers, idle_timers, chosen_timer);
 
+  /* First run the code that was delayed.  */
+  while (CONSP (pending_funcalls))
+    {
+      Lisp_Object funcall = XCAR (pending_funcalls);
+      pending_funcalls = XCDR (pending_funcalls);
+      safe_call2 (Qapply, XCAR (funcall), XCDR (funcall));
+    }
+
   if (CONSP (timers) || CONSP (idle_timers))
     {
       EMACS_GET_TIME (now);
@@ -4574,10 +4585,14 @@ timer_check (do_it_now)
        {
          if (NILP (vector[0]))
            {
-             int was_locked = single_kboard;
              int count = SPECPDL_INDEX ();
              Lisp_Object old_deactivate_mark = Vdeactivate_mark;
 
+#if 0 /* This shouldn't be necessary anymore.  --lorentey  */
+             /* On unbind_to, resume allowing input from any kboard, if that
+                 was true before.  */
+              record_single_kboard_state ();
+#endif
              /* Mark the timer as triggered to prevent problems if the lisp
                 code fails to reschedule it right.  */
              vector[0] = Qt;
@@ -4589,10 +4604,6 @@ timer_check (do_it_now)
              timers_run++;
              unbind_to (count, Qnil);
 
-             /* Resume allowing input from any kboard, if that was true before.  */
-             if (!was_locked)
-               any_kboard_state ();
-
              /* Since we have handled the event,
                 we don't need to tell the caller to wake up and do it.  */
            }
@@ -4810,13 +4821,17 @@ char *lispy_function_keys[] =
     0,                /* VK_MENU           0x12 */
     "pause",          /* VK_PAUSE          0x13 */
     "capslock",       /* VK_CAPITAL        0x14 */
-
-    0, 0, 0, 0, 0, 0, /*    0x15 .. 0x1A        */
-
+    "kana",           /* VK_KANA/VK_HANGUL 0x15 */
+    0,                /*    0x16                */
+    "junja",          /* VK_JUNJA          0x17 */
+    "final",          /* VK_FINAL          0x18 */
+    "kanji",          /* VK_KANJI/VK_HANJA 0x19 */
+    0,                /*    0x1A                */
     "escape",         /* VK_ESCAPE         0x1B */
-
-    0, 0, 0, 0,       /*    0x1C .. 0x1F        */
-
+    "convert",        /* VK_CONVERT        0x1C */
+    "non-convert",    /* VK_NONCONVERT     0x1D */
+    "accept",         /* VK_ACCEPT         0x1E */
+    "mode-change",    /* VK_MODECHANGE     0x1F */
     0,                /* VK_SPACE          0x20 */
     "prior",          /* VK_PRIOR          0x21 */
     "next",           /* VK_NEXT           0x22 */
@@ -4849,9 +4864,8 @@ char *lispy_function_keys[] =
     "lwindow",       /* VK_LWIN           0x5B */
     "rwindow",       /* VK_RWIN           0x5C */
     "apps",          /* VK_APPS           0x5D */
-
-    0, 0,            /*    0x5E .. 0x5F        */
-
+    0,               /*    0x5E                */
+    "sleep",
     "kp-0",          /* VK_NUMPAD0        0x60 */
     "kp-1",          /* VK_NUMPAD1        0x61 */
     "kp-2",          /* VK_NUMPAD2        0x62 */
@@ -4898,7 +4912,9 @@ char *lispy_function_keys[] =
 
     "kp-numlock",    /* VK_NUMLOCK        0x90 */
     "scroll",        /* VK_SCROLL         0x91 */
-
+    /* Not sure where the following block comes from.
+       Windows headers have NEC and Fujitsu specific keys in
+       this block, but nothing generic.  */
     "kp-space",             /* VK_NUMPAD_CLEAR   0x92 */
     "kp-enter",             /* VK_NUMPAD_ENTER   0x93 */
     "kp-prior",             /* VK_NUMPAD_PRIOR   0x94 */
@@ -4918,19 +4934,47 @@ char *lispy_function_keys[] =
      * VK_L* & VK_R* - left and right Alt, Ctrl and Shift virtual keys.
      * Used only as parameters to GetAsyncKeyState and GetKeyState.
      * No other API or message will distinguish left and right keys this way.
+     * 0xA0 .. 0xA5
      */
-    /* 0xA0 .. 0xEF */
+    0, 0, 0, 0, 0, 0,
 
-    0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
-    0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
-    0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
-    0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
-    0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
+    /* Multimedia keys. These are handled as WM_APPCOMMAND, which allows us
+       to enable them selectively, and gives access to a few more functions.
+       See lispy_multimedia_keys below.  */
+    0, 0, 0, 0, 0, 0, 0, /* 0xA6 .. 0xAC        Browser */
+    0, 0, 0,             /* 0xAD .. 0xAF         Volume */
+    0, 0, 0, 0,          /* 0xB0 .. 0xB3          Media */
+    0, 0, 0, 0,          /* 0xB4 .. 0xB7           Apps */
 
-    /* 0xF0 .. 0xF5 */
+    /* 0xB8 .. 0xC0 "OEM" keys - all seem to be punctuation.  */
+    0, 0, 0, 0, 0, 0, 0, 0, 0,
 
-    0, 0, 0, 0, 0, 0,
+    /* 0xC1 - 0xDA unallocated, 0xDB-0xDF more OEM keys */
+    0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
+    0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
 
+    0,               /* 0xE0                   */
+    "ax",            /* VK_OEM_AX         0xE1 */
+    0,               /* VK_OEM_102        0xE2 */
+    "ico-help",      /* VK_ICO_HELP       0xE3 */
+    "ico-00",        /* VK_ICO_00         0xE4 */
+    0,               /* VK_PROCESSKEY     0xE5 */
+    "ico-clear",     /* VK_ICO_CLEAR      0xE6 */
+    "packet",        /* VK_PACKET         0xE7 */
+    0,               /*                   0xE8 */
+    "reset",         /* VK_OEM_RESET      0xE9 */
+    "jump",          /* VK_OEM_JUMP       0xEA */
+    "oem-pa1",       /* VK_OEM_PA1        0xEB */
+    "oem-pa2",       /* VK_OEM_PA2        0xEC */
+    "oem-pa3",       /* VK_OEM_PA3        0xED */
+    "wsctrl",        /* VK_OEM_WSCTRL     0xEE */
+    "cusel",         /* VK_OEM_CUSEL      0xEF */
+    "oem-attn",      /* VK_OEM_ATTN       0xF0 */
+    "finish",        /* VK_OEM_FINISH     0xF1 */
+    "copy",          /* VK_OEM_COPY       0xF2 */
+    "auto",          /* VK_OEM_AUTO       0xF3 */
+    "enlw",          /* VK_OEM_ENLW       0xF4 */
+    "backtab",       /* VK_OEM_BACKTAB    0xF5 */
     "attn",          /* VK_ATTN           0xF6 */
     "crsel",         /* VK_CRSEL          0xF7 */
     "exsel",         /* VK_EXSEL          0xF8 */
@@ -4943,6 +4987,65 @@ char *lispy_function_keys[] =
     0 /* 0xFF */
   };
 
+/* Some of these duplicate the "Media keys" on newer keyboards,
+   but they are delivered to the application in a different way.  */
+static char *lispy_multimedia_keys[] =
+  {
+    0,
+    "browser-back",
+    "browser-forward",
+    "browser-refresh",
+    "browser-stop",
+    "browser-search",
+    "browser-favorites",
+    "browser-home",
+    "volume-mute",
+    "volume-down",
+    "volume-up",
+    "media-next",
+    "media-previous",
+    "media-stop",
+    "media-play-pause",
+    "mail",
+    "media-select",
+    "app-1",
+    "app-2",
+    "bass-down",
+    "bass-boost",
+    "bass-up",
+    "treble-down",
+    "treble-up",
+    "mic-volume-mute",
+    "mic-volume-down",
+    "mic-volume-up",
+    "help",
+    "find",
+    "new",
+    "open",
+    "close",
+    "save",
+    "print",
+    "undo",
+    "redo",
+    "copy",
+    "cut",
+    "paste",
+    "mail-reply",
+    "mail-forward",
+    "mail-send",
+    "spell-check",
+    "toggle-dictate-command",
+    "mic-toggle",
+    "correction-list",
+    "media-play",
+    "media-pause",
+    "media-record",
+    "media-fast-forward",
+    "media-rewind",
+    "media-channel-up",
+    "media-channel-down"
+  };
+
 #else /* not HAVE_NTGUI */
 
 /* This should be dealt with in XTread_socket now, and that doesn't
@@ -5100,7 +5203,7 @@ Lisp_Object Vlispy_mouse_stem;
 
 static char *lispy_wheel_names[] =
 {
-  "wheel-up", "wheel-down"
+  "wheel-up", "wheel-down", "wheel-left", "wheel-right"
 };
 
 /* drag-n-drop events are generated when a set of selected files are
@@ -5357,41 +5460,32 @@ make_lispy_event (event)
     {
       /* A simple keystroke.  */
     case ASCII_KEYSTROKE_EVENT:
-      {
-       Lisp_Object lispy_c;
-       int c = event->code & 0377;
-       /* Turn ASCII characters into control characters
-          when proper.  */
-       if (event->modifiers & ctrl_modifier)
-         c = make_ctrl_char (c);
-
-       /* Add in the other modifier bits.  We took care of ctrl_modifier
-          just above, and the shift key was taken care of by the X code,
-          and applied to control characters by make_ctrl_char.  */
-       c |= (event->modifiers
-             & (meta_modifier | alt_modifier
-                | hyper_modifier | super_modifier));
-       /* Distinguish Shift-SPC from SPC.  */
-       if ((event->code & 0377) == 040
-           && event->modifiers & shift_modifier)
-         c |= shift_modifier;
-       button_down_time = 0;
-       XSETFASTINT (lispy_c, c);
-       return lispy_c;
-      }
-
     case MULTIBYTE_CHAR_KEYSTROKE_EVENT:
       {
        Lisp_Object lispy_c;
        int c = event->code;
+       if (event->kind == ASCII_KEYSTROKE_EVENT)
+         {
+           c &= 0377;
+           eassert (c == event->code);
+           /* Turn ASCII characters into control characters
+              when proper.  */
+           if (event->modifiers & ctrl_modifier)
+             {
+               c = make_ctrl_char (c);
+               event->modifiers &= ~ctrl_modifier;
+             }
+         }
 
-       /* Add in the other modifier bits.  We took care of ctrl_modifier
-          just above, and the shift key was taken care of by the X code,
-          and applied to control characters by make_ctrl_char.  */
+       /* Add in the other modifier bits.  The shift key was taken care
+          of by the X code.  */
        c |= (event->modifiers
              & (meta_modifier | alt_modifier
                 | hyper_modifier | super_modifier | ctrl_modifier));
-       /* What about the `shift' modifier ?  */
+       /* Distinguish Shift-SPC from SPC.  */
+       if ((event->code) == 040
+           && event->modifiers & shift_modifier)
+         c |= shift_modifier;
        button_down_time = 0;
        XSETFASTINT (lispy_c, c);
        return lispy_c;
@@ -5460,6 +5554,21 @@ make_lispy_event (event)
                                  (sizeof (lispy_function_keys)
                                   / sizeof (lispy_function_keys[0])));
 
+#ifdef WINDOWSNT
+    case MULTIMEDIA_KEY_EVENT:
+      if (event->code < (sizeof (lispy_multimedia_keys)
+                         / sizeof (lispy_multimedia_keys[0]))
+          && event->code > 0 && lispy_multimedia_keys[event->code])
+        {
+          return modify_event_symbol (event->code, event->modifiers,
+                                      Qfunction_key, Qnil,
+                                      lispy_multimedia_keys, &func_key_syms,
+                                      (sizeof (lispy_multimedia_keys)
+                                       / sizeof (lispy_multimedia_keys[0])));
+        }
+      return Qnil;
+#endif
+
 #ifdef HAVE_MOUSE
       /* A mouse click.  Figure out where it is, decide whether it's
          a press, click or drag, and build the appropriate structure.  */
@@ -5480,7 +5589,7 @@ make_lispy_event (event)
        if (event->kind == MOUSE_CLICK_EVENT)
          {
            struct frame *f = XFRAME (event->frame_or_window);
-#if ! defined (USE_X_TOOLKIT) && ! defined (USE_GTK)
+#if ! defined (USE_X_TOOLKIT) && ! defined (USE_GTK) && ! defined (HAVE_NS)
            int row, column;
 #endif
 
@@ -5489,7 +5598,7 @@ make_lispy_event (event)
            if (! FRAME_LIVE_P (f))
              return Qnil;
 
-#if ! defined (USE_X_TOOLKIT) && ! defined (USE_GTK)
+#if ! defined (USE_X_TOOLKIT) && ! defined (USE_GTK) && ! defined (HAVE_NS)
            /* EVENT->x and EVENT->y are frame-relative pixel
               coordinates at this place.  Under old redisplay, COLUMN
               and ROW are set to frame relative glyph coordinates
@@ -5549,7 +5658,7 @@ make_lispy_event (event)
 
                return Fcons (item, Fcons (position, Qnil));
              }
-#endif /* not USE_X_TOOLKIT && not USE_GTK */
+#endif /* not USE_X_TOOLKIT && not USE_GTK && not HAVE_NS */
 
            position = make_lispy_position (f, &event->x, &event->y,
                                            event->timestamp);
@@ -5606,8 +5715,8 @@ make_lispy_event (event)
            fuzz = double_click_fuzz / 8;
 
          is_double = (button == last_mouse_button
-                      && (abs (XINT (event->x) - last_mouse_x) <= fuzz)
-                      && (abs (XINT (event->y) - last_mouse_y) <= fuzz)
+                      && (eabs (XINT (event->x) - last_mouse_x) <= fuzz)
+                      && (eabs (XINT (event->y) - last_mouse_y) <= fuzz)
                       && button_down_time != 0
                       && (EQ (Vdouble_click_time, Qt)
                           || (INTEGERP (Vdouble_click_time)
@@ -5737,6 +5846,7 @@ make_lispy_event (event)
       }
 
     case WHEEL_EVENT:
+    case HORIZ_WHEEL_EVENT:
       {
        Lisp_Object position;
        Lisp_Object head;
@@ -5774,8 +5884,8 @@ make_lispy_event (event)
            fuzz = double_click_fuzz / 8;
 
          is_double = (last_mouse_button < 0
-                      && (abs (XINT (event->x) - last_mouse_x) <= fuzz)
-                      && (abs (XINT (event->y) - last_mouse_y) <= fuzz)
+                      && (eabs (XINT (event->x) - last_mouse_x) <= fuzz)
+                      && (eabs (XINT (event->y) - last_mouse_y) <= fuzz)
                       && button_down_time != 0
                       && (EQ (Vdouble_click_time, Qt)
                           || (INTEGERP (Vdouble_click_time)
@@ -5821,6 +5931,9 @@ make_lispy_event (event)
               the up_modifier set.  */
            abort ();
 
+          if (event->kind == HORIZ_WHEEL_EVENT)
+            symbol_num += 2;
+
          /* Get the symbol we should use for the wheel event.  */
          head = modify_event_symbol (symbol_num,
                                      event->modifiers,
@@ -5896,52 +6009,6 @@ make_lispy_event (event)
 
 #endif /* USE_TOOLKIT_SCROLL_BARS */
 
-#ifdef WINDOWSNT
-    case W32_SCROLL_BAR_CLICK_EVENT:
-      {
-       int button = event->code;
-       int is_double;
-       Lisp_Object position;
-       Lisp_Object *start_pos_ptr;
-       Lisp_Object start_pos;
-
-       {
-         Lisp_Object window;
-         Lisp_Object portion_whole;
-         Lisp_Object part;
-
-         window = event->frame_or_window;
-         portion_whole = Fcons (event->x, event->y);
-         part = *scroll_bar_parts[(int) event->part];
-
-         position
-           = Fcons (window,
-                    Fcons (Qvertical_scroll_bar,
-                           Fcons (portion_whole,
-                                  Fcons (make_number (event->timestamp),
-                                         Fcons (part, Qnil)))));
-       }
-
-       /* Always treat W32 scroll bar events as clicks. */
-       event->modifiers |= click_modifier;
-
-       {
-         /* Get the symbol we should use for the mouse click.  */
-         Lisp_Object head;
-
-         head = modify_event_symbol (button,
-                                     event->modifiers,
-                                     Qmouse_click,
-                                     Vlispy_mouse_stem,
-                                     NULL, &mouse_syms,
-                                     XVECTOR (mouse_syms)->size);
-         return Fcons (head,
-                       Fcons (position,
-                              Qnil));
-       }
-      }
-#endif /* WINDOWSNT */
-
     case DRAG_N_DROP_EVENT:
       {
        FRAME_PTR f;
@@ -5970,8 +6037,8 @@ make_lispy_event (event)
       }
 #endif /* HAVE_MOUSE */
 
-#if defined (USE_X_TOOLKIT) || defined (HAVE_NTGUI) || defined (MAC_OS) \
-    || defined (USE_GTK)
+#if defined (USE_X_TOOLKIT) || defined (HAVE_NTGUI) \
+    || defined(HAVE_NS) || defined (USE_GTK)
     case MENU_BAR_EVENT:
       if (EQ (event->arg, event->frame_or_window))
        /* This is the prefix key.  We translate this to
@@ -6009,26 +6076,80 @@ make_lispy_event (event)
     case SAVE_SESSION_EVENT:
       return Qsave_session;
 
-#ifdef MAC_OS
-    case MAC_APPLE_EVENT:
+#ifdef HAVE_DBUS
+    case DBUS_EVENT:
       {
-       Lisp_Object spec[2];
-
-       spec[0] = event->x;
-       spec[1] = event->y;
-       return Fcons (Qmac_apple_event,
-                     Fcons (Fvector (2, spec),
-                            Fcons (event->arg, Qnil)));
+       return Fcons (Qdbus_event, event->arg);
       }
-#endif
+#endif /* HAVE_DBUS */
 
-      /* The 'kind' field of the event is something we don't recognize.  */
-    default:
-      abort ();
-    }
-}
+#ifdef HAVE_GPM
+    case GPM_CLICK_EVENT:
+      {
+       FRAME_PTR f = XFRAME (event->frame_or_window);
+       Lisp_Object head, position;
+       Lisp_Object *start_pos_ptr;
+       Lisp_Object start_pos;
+       int button = event->code;
 
-#ifdef HAVE_MOUSE
+       if (button >= ASIZE (button_down_location))
+         {
+           button_down_location = larger_vector (button_down_location,
+                                                 button + 1, Qnil);
+           mouse_syms = larger_vector (mouse_syms, button + 1, Qnil);
+         }
+
+       start_pos_ptr = &AREF (button_down_location, button);
+       start_pos = *start_pos_ptr;
+
+       position = make_lispy_position (f, &event->x, &event->y,
+                                           event->timestamp);
+
+       if (event->modifiers & down_modifier)
+         *start_pos_ptr = Fcopy_alist (position);
+       else if (event->modifiers & (up_modifier | drag_modifier))
+         {
+           if (!CONSP (start_pos))
+             return Qnil;
+           event->modifiers &= ~up_modifier;
+         }
+
+       head = modify_event_symbol (button,
+                                   event->modifiers,
+                                   Qmouse_click, Vlispy_mouse_stem,
+                                   NULL,
+                                   &mouse_syms,
+                                   XVECTOR (mouse_syms)->size);
+
+       if (event->modifiers & drag_modifier)
+         return Fcons (head,
+                       Fcons (start_pos,
+                              Fcons (position,
+                                     Qnil)));
+       else if (event->modifiers & double_modifier)
+         return Fcons (head,
+                       Fcons (position,
+                              Fcons (make_number (2),
+                                     Qnil)));
+       else if (event->modifiers & triple_modifier)
+         return Fcons (head,
+                       Fcons (position,
+                              Fcons (make_number (3),
+                                     Qnil)));
+       else
+         return Fcons (head,
+                       Fcons (position,
+                              Qnil));
+       }
+#endif /* HAVE_GPM */
+
+      /* The 'kind' field of the event is something we don't recognize.  */
+    default:
+      abort ();
+    }
+}
+
+#if defined(HAVE_MOUSE) || defined(HAVE_GPM)
 
 static Lisp_Object
 make_lispy_movement (frame, bar_window, part, x, y, time)
@@ -6067,7 +6188,7 @@ make_lispy_movement (frame, bar_window, part, x, y, time)
     }
 }
 
-#endif /* HAVE_MOUSE */
+#endif /* HAVE_MOUSE || HAVE GPM */
 
 /* Construct a switch frame event.  */
 static Lisp_Object
@@ -6280,12 +6401,21 @@ lispy_modifier_list (modifiers)
    SYMBOL's Qevent_symbol_element_mask property, and maintains the
    Qevent_symbol_elements property.  */
 
+#define KEY_TO_CHAR(k) (XINT (k) & ((1 << CHARACTERBITS) - 1))
+
 Lisp_Object
 parse_modifiers (symbol)
      Lisp_Object symbol;
 {
   Lisp_Object elements;
 
+  if (INTEGERP (symbol))
+    return (Fcons (make_number (KEY_TO_CHAR (symbol)),
+                  Fcons (make_number (XINT (symbol) & CHAR_MODIFIER_MASK),
+                         Qnil)));
+  else if (!SYMBOLP (symbol))
+    return Qnil;
+
   elements = Fget (symbol, Qevent_symbol_element_mask);
   if (CONSP (elements))
     return elements;
@@ -6320,6 +6450,20 @@ parse_modifiers (symbol)
     }
 }
 
+DEFUN ("internal-event-symbol-parse-modifiers", Fevent_symbol_parse_modifiers,
+       Sevent_symbol_parse_modifiers, 1, 1, 0,
+       doc: /* Parse the event symbol.  For internal use.  */)
+     (symbol)
+     Lisp_Object symbol;
+{
+  /* Fill the cache if needed.  */
+  parse_modifiers (symbol);
+  /* Ignore the result (which is stored on Qevent_symbol_element_mask)
+     and use the Lispier representation stored on Qevent_symbol_elements
+     instead.  */
+  return Fget (symbol, Qevent_symbol_elements);
+}
+
 /* Apply the modifiers MODIFIERS to the symbol BASE.
    BASE must be unmodified.
 
@@ -6339,6 +6483,9 @@ apply_modifiers (modifiers, base)
   /* Mask out upper bits.  We don't know where this value's been.  */
   modifiers &= INTMASK;
 
+  if (INTEGERP (base))
+    return make_number (XINT (base) | modifiers);
+
   /* The click modifier never figures into cache indices.  */
   cache = Fget (base, Qmodifier_cache);
   XSETFASTINT (index, (modifiers & ~click_modifier));
@@ -6495,8 +6642,8 @@ modify_event_symbol (symbol_num, modifiers, symbol_kind, name_alist_or_stem,
        {
          int len = SBYTES (name_alist_or_stem);
          char *buf = (char *) alloca (len + 50);
-         sprintf (buf, "%s-%ld", SDATA (name_alist_or_stem),
-                  (long) XINT (symbol_int) + 1);
+          sprintf (buf, "%s-%ld", SDATA (name_alist_or_stem),
+                   (long) XINT (symbol_int) + 1);
          value = intern (buf);
        }
       else if (name_table != 0 && name_table[symbol_num])
@@ -6608,9 +6755,8 @@ has the same base event type and all the specified modifiers.  */)
 /* Try to recognize SYMBOL as a modifier name.
    Return the modifier flag bit, or 0 if not recognized.  */
 
-static int
-parse_solitary_modifier (symbol)
-     Lisp_Object symbol;
+int
+parse_solitary_modifier (Lisp_Object symbol)
 {
   Lisp_Object name = SYMBOL_NAME (symbol);
 
@@ -6750,7 +6896,11 @@ void
 gobble_input (expected)
      int expected;
 {
-#ifndef VMS
+#ifdef HAVE_DBUS
+  /* Check whether a D-Bus message has arrived.  */
+  xd_read_queued_messages ();
+#endif /* HAVE_DBUS */
+
 #ifdef SIGIO
   if (interrupt_input)
     {
@@ -6761,7 +6911,10 @@ gobble_input (expected)
     }
   else
 #ifdef POLL_FOR_INPUT
-  if (read_socket_hook && !interrupt_input && poll_suppress_count == 0)
+  /* XXX This condition was (read_socket_hook && !interrupt_input),
+     but read_socket_hook is not global anymore.  Let's pretend that
+     it's always set. */
+  if (!interrupt_input && poll_suppress_count == 0)
     {
       SIGMASKTYPE mask;
       mask = sigblock (sigmask (SIGALRM));
@@ -6769,7 +6922,6 @@ gobble_input (expected)
       sigsetmask (mask);
     }
   else
-#endif
 #endif
     read_avail_input (expected);
 #endif
@@ -6820,17 +6972,11 @@ record_asynch_buffer_change ()
     }
 }
 \f
-#ifndef VMS
-
 /* Read any terminal input already buffered up by the system
    into the kbd_buffer, but do not wait.
 
    EXPECTED should be nonzero if the caller knows there is some input.
 
-   Except on VMS, all input is read by this function.
-   If interrupt_input is nonzero, this function MUST be called
-   only when SIGIO is blocked.
-
    Returns the number of keyboard chars read, or -1 meaning
    this is a bad time to try to read input.  */
 
@@ -6838,163 +6984,250 @@ static int
 read_avail_input (expected)
      int expected;
 {
-  register int i;
   int nread = 0;
+  int err = 0;
+  struct terminal *t;
 
   /* Store pending user signal events, if any.  */
   if (store_user_signal_events ())
     expected = 0;
 
-  if (read_socket_hook)
+  /* Loop through the available terminals, and call their input hooks. */
+  t = terminal_list;
+  while (t)
     {
-      int nr;
-      struct input_event hold_quit;
+      struct terminal *next = t->next_terminal;
 
-      EVENT_INIT (hold_quit);
-      hold_quit.kind = NO_EVENT;
+      if (t->read_socket_hook)
+        {
+          int nr;
+          struct input_event hold_quit;
+
+          EVENT_INIT (hold_quit);
+          hold_quit.kind = NO_EVENT;
+
+          /* No need for FIONREAD or fcntl; just say don't wait.  */
+          while (nr = (*t->read_socket_hook) (t, expected, &hold_quit), nr > 0)
+            {
+              nread += nr;
+              expected = 0;
+            }
+
+          if (nr == -1)          /* Not OK to read input now. */
+            {
+              err = 1;
+            }
+          else if (nr == -2)          /* Non-transient error. */
+            {
+              /* The terminal device terminated; it should be closed. */
+
+              /* Kill Emacs if this was our last terminal. */
+              if (!terminal_list->next_terminal)
+                /* Formerly simply reported no input, but that
+                   sometimes led to a failure of Emacs to terminate.
+                   SIGHUP seems appropriate if we can't reach the
+                   terminal.  */
+                /* ??? Is it really right to send the signal just to
+                   this process rather than to the whole process
+                   group?  Perhaps on systems with FIONREAD Emacs is
+                   alone in its group.  */
+                kill (getpid (), SIGHUP);
+
+              /* XXX Is calling delete_terminal safe here?  It calls Fdelete_frame. */
+             {
+               Lisp_Object tmp;
+               XSETTERMINAL (tmp, t);
+               Fdelete_terminal (tmp, Qnoelisp);
+             }
+            }
 
-      /* No need for FIONREAD or fcntl; just say don't wait.  */
-      while (nr = (*read_socket_hook) (input_fd, expected, &hold_quit), nr > 0)
-       {
-         nread += nr;
-         expected = 0;
-       }
-      if (hold_quit.kind != NO_EVENT)
-       kbd_buffer_store_event (&hold_quit);
+          if (hold_quit.kind != NO_EVENT)
+            kbd_buffer_store_event (&hold_quit);
+        }
+
+      t = next;
     }
-  else
-    {
-      /* Using KBD_BUFFER_SIZE - 1 here avoids reading more than
-        the kbd_buffer can really hold.  That may prevent loss
-        of characters on some systems when input is stuffed at us.  */
-      unsigned char cbuf[KBD_BUFFER_SIZE - 1];
-      int n_to_read;
 
-      /* Determine how many characters we should *try* to read.  */
+  if (err && !nread)
+    nread = -1;
+
+  return nread;
+}
+
+/* This is the tty way of reading available input.
+
+   Note that each terminal device has its own `struct terminal' object,
+   and so this function is called once for each individual termcap
+   terminal.  The first parameter indicates which terminal to read from.  */
+
+int
+tty_read_avail_input (struct terminal *terminal,
+                      int expected,
+                      struct input_event *hold_quit)
+{
+  /* Using KBD_BUFFER_SIZE - 1 here avoids reading more than
+     the kbd_buffer can really hold.  That may prevent loss
+     of characters on some systems when input is stuffed at us.  */
+  unsigned char cbuf[KBD_BUFFER_SIZE - 1];
+  int n_to_read, i;
+  struct tty_display_info *tty = terminal->display_info.tty;
+  int nread = 0;
+
+  if (!terminal->name)         /* Don't read from a dead terminal. */
+    return 0;
+
+  if (terminal->type != output_termcap)
+    abort ();
+
+  /* XXX I think the following code should be moved to separate hook
+     functions in system-dependent files. */
 #ifdef WINDOWSNT
-      return 0;
+  return 0;
 #else /* not WINDOWSNT */
 #ifdef MSDOS
-      n_to_read = dos_keysns ();
-      if (n_to_read == 0)
-       return 0;
+  n_to_read = dos_keysns ();
+  if (n_to_read == 0)
+    return 0;
+
+  cbuf[0] = dos_keyread ();
+  nread = 1;
+
 #else /* not MSDOS */
+
+  if (! tty->term_initted)      /* In case we get called during bootstrap. */
+    return 0;
+
+  if (! tty->input)
+    return 0;                   /* The terminal is suspended. */
+
+#ifdef HAVE_GPM
+  if (gpm_tty == tty)
+  {
+      Gpm_Event event;
+      struct input_event hold_quit;
+      int gpm;
+
+      EVENT_INIT (hold_quit);
+      hold_quit.kind = NO_EVENT;
+
+      while (gpm = Gpm_GetEvent (&event), gpm == 1) {
+         nread += handle_one_term_event (tty, &event, &hold_quit);
+      }
+      if (hold_quit.kind != NO_EVENT)
+         kbd_buffer_store_event (&hold_quit);
+      if (nread)
+         return nread;
+  }
+#endif /* HAVE_GPM */
+
+/* Determine how many characters we should *try* to read.  */
 #ifdef FIONREAD
-      /* Find out how much input is available.  */
-      if (ioctl (input_fd, FIONREAD, &n_to_read) < 0)
-       /* Formerly simply reported no input, but that sometimes led to
-          a failure of Emacs to terminate.
-          SIGHUP seems appropriate if we can't reach the terminal.  */
-       /* ??? Is it really right to send the signal just to this process
-          rather than to the whole process group?
-          Perhaps on systems with FIONREAD Emacs is alone in its group.  */
-       {
-         if (! noninteractive)
-           kill (getpid (), SIGHUP);
-         else
-           n_to_read = 0;
-       }
-      if (n_to_read == 0)
-       return 0;
-      if (n_to_read > sizeof cbuf)
-       n_to_read = sizeof cbuf;
+  /* Find out how much input is available.  */
+  if (ioctl (fileno (tty->input), FIONREAD, &n_to_read) < 0)
+    {
+      if (! noninteractive)
+        return -2;          /* Close this terminal. */
+      else
+        n_to_read = 0;
+    }
+  if (n_to_read == 0)
+    return 0;
+  if (n_to_read > sizeof cbuf)
+    n_to_read = sizeof cbuf;
 #else /* no FIONREAD */
-#if defined (USG) || defined (DGUX) || defined(CYGWIN)
-      /* Read some input if available, but don't wait.  */
-      n_to_read = sizeof cbuf;
-      fcntl (input_fd, F_SETFL, O_NDELAY);
+#if defined (USG) || defined(CYGWIN)
+  /* Read some input if available, but don't wait.  */
+  n_to_read = sizeof cbuf;
+  fcntl (fileno (tty->input), F_SETFL, O_NDELAY);
 #else
-      you lose;
+  you lose;
 #endif
 #endif
-#endif /* not MSDOS */
-#endif /* not WINDOWSNT */
 
-      /* Now read; for one reason or another, this will not block.
-        NREAD is set to the number of chars read.  */
-      do
-       {
-#ifdef MSDOS
-         cbuf[0] = dos_keyread ();
-         nread = 1;
-#else
-         nread = emacs_read (input_fd, cbuf, n_to_read);
-#endif
-         /* POSIX infers that processes which are not in the session leader's
-            process group won't get SIGHUP's at logout time.  BSDI adheres to
-            this part standard and returns -1 from read (0) with errno==EIO
-            when the control tty is taken away.
-            Jeffrey Honig <jch@bsdi.com> says this is generally safe.  */
-         if (nread == -1 && errno == EIO)
-           kill (0, SIGHUP);
-#if defined (AIX) && (! defined (aix386) && defined (_BSD))
-         /* The kernel sometimes fails to deliver SIGHUP for ptys.
-            This looks incorrect, but it isn't, because _BSD causes
-            O_NDELAY to be defined in fcntl.h as O_NONBLOCK,
-            and that causes a value other than 0 when there is no input.  */
-         if (nread == 0)
-           kill (0, SIGHUP);
-#endif
-       }
-      while (
-            /* We used to retry the read if it was interrupted.
-               But this does the wrong thing when O_NDELAY causes
-               an EAGAIN error.  Does anybody know of a situation
-               where a retry is actually needed?  */
+  /* Now read; for one reason or another, this will not block.
+     NREAD is set to the number of chars read.  */
+  do
+    {
+      nread = emacs_read (fileno (tty->input), cbuf, n_to_read);
+      /* POSIX infers that processes which are not in the session leader's
+         process group won't get SIGHUP's at logout time.  BSDI adheres to
+         this part standard and returns -1 from read (0) with errno==EIO
+         when the control tty is taken away.
+         Jeffrey Honig <jch@bsdi.com> says this is generally safe. */
+      if (nread == -1 && errno == EIO)
+        return -2;          /* Close this terminal. */
+#if defined (AIX) && defined (_BSD)
+      /* The kernel sometimes fails to deliver SIGHUP for ptys.
+         This looks incorrect, but it isn't, because _BSD causes
+         O_NDELAY to be defined in fcntl.h as O_NONBLOCK,
+         and that causes a value other than 0 when there is no input.  */
+      if (nread == 0)
+        return -2;          /* Close this terminal. */
+#endif
+    }
+  while (
+         /* We used to retry the read if it was interrupted.
+            But this does the wrong thing when O_NDELAY causes
+            an EAGAIN error.  Does anybody know of a situation
+            where a retry is actually needed?  */
 #if 0
-            nread < 0 && (errno == EAGAIN
+         nread < 0 && (errno == EAGAIN
 #ifdef EFAULT
-                          || errno == EFAULT
+                       || errno == EFAULT
 #endif
 #ifdef EBADSLT
-                          || errno == EBADSLT
+                       || errno == EBADSLT
 #endif
-                          )
+                       )
 #else
-            0
+         0
 #endif
-            );
+         );
 
 #ifndef FIONREAD
-#if defined (USG) || defined (DGUX) || defined (CYGWIN)
-      fcntl (input_fd, F_SETFL, 0);
-#endif /* USG or DGUX or CYGWIN */
+#if defined (USG) || defined (CYGWIN)
+  fcntl (fileno (tty->input), F_SETFL, 0);
+#endif /* USG or CYGWIN */
 #endif /* no FIONREAD */
-      for (i = 0; i < nread; i++)
-       {
-         struct input_event buf;
-         EVENT_INIT (buf);
-         buf.kind = ASCII_KEYSTROKE_EVENT;
-         buf.modifiers = 0;
-         if (meta_key == 1 && (cbuf[i] & 0x80))
-           buf.modifiers = meta_modifier;
-         if (meta_key != 2)
-           cbuf[i] &= ~0x80;
-
-         buf.code = cbuf[i];
-         buf.frame_or_window = selected_frame;
-         buf.arg = Qnil;
-
-         kbd_buffer_store_event (&buf);
-         /* Don't look at input that follows a C-g too closely.
-            This reduces lossage due to autorepeat on C-g.  */
-         if (buf.kind == ASCII_KEYSTROKE_EVENT
-             && buf.code == quit_char)
-           break;
-       }
+
+  if (nread <= 0)
+    return nread;
+
+#endif /* not MSDOS */
+#endif /* not WINDOWSNT */
+
+  for (i = 0; i < nread; i++)
+    {
+      struct input_event buf;
+      EVENT_INIT (buf);
+      buf.kind = ASCII_KEYSTROKE_EVENT;
+      buf.modifiers = 0;
+      if (tty->meta_key == 1 && (cbuf[i] & 0x80))
+        buf.modifiers = meta_modifier;
+      if (tty->meta_key != 2)
+        cbuf[i] &= ~0x80;
+
+      buf.code = cbuf[i];
+      /* Set the frame corresponding to the active tty.  Note that the
+         value of selected_frame is not reliable here, redisplay tends
+         to temporarily change it. */
+      buf.frame_or_window = tty->top_frame;
+      buf.arg = Qnil;
+
+      kbd_buffer_store_event (&buf);
+      /* Don't look at input that follows a C-g too closely.
+         This reduces lossage due to autorepeat on C-g.  */
+      if (buf.kind == ASCII_KEYSTROKE_EVENT
+          && buf.code == quit_char)
+        break;
     }
 
   return nread;
 }
-#endif /* not VMS */
 \f
 void
 handle_async_input ()
 {
-#ifdef BSD4_1
-  extern int select_alarmed;
-#endif
-
   interrupt_input_pending = 0;
 
   while (1)
@@ -7006,10 +7239,6 @@ handle_async_input ()
         0 means there was no keyboard input available.  */
       if (nread <= 0)
        break;
-
-#ifdef BSD4_1
-      select_alarmed = 1;  /* Force the select emulator back to life */
-#endif
     }
 }
 
@@ -7028,10 +7257,6 @@ input_available_signal (signo)
   signal (signo, input_available_signal);
 #endif /* USG */
 
-#ifdef BSD4_1
-  sigisheld (SIGIO);
-#endif
-
 #ifdef SYNC_INPUT
   interrupt_input_pending = 1;
 #else
@@ -7045,9 +7270,6 @@ input_available_signal (signo)
   handle_async_input ();
 #endif
 
-#ifdef BSD4_1
-  sigfree ();
-#endif
   errno = old_errno;
 }
 #endif /* SIGIO */
@@ -7332,13 +7554,7 @@ menu_bar_items (old)
   /* Add nil, nil, nil, nil at the end.  */
   i = menu_bar_items_index;
   if (i + 4 > XVECTOR (menu_bar_items_vector)->size)
-    {
-      Lisp_Object tem;
-      tem = Fmake_vector (make_number (2 * i), Qnil);
-      bcopy (XVECTOR (menu_bar_items_vector)->contents,
-            XVECTOR (tem)->contents, i * sizeof (Lisp_Object));
-      menu_bar_items_vector = tem;
-    }
+    menu_bar_items_vector = larger_vector (menu_bar_items_vector, 2 * i, Qnil);
   /* Add this item.  */
   XVECTOR (menu_bar_items_vector)->contents[i++] = Qnil;
   XVECTOR (menu_bar_items_vector)->contents[i++] = Qnil;
@@ -7410,14 +7626,7 @@ menu_bar_item (key, item, dummy1, dummy2)
     {
       /* If vector is too small, get a bigger one.  */
       if (i + 4 > XVECTOR (menu_bar_items_vector)->size)
-       {
-         Lisp_Object tem;
-         tem = Fmake_vector (make_number (2 * i), Qnil);
-         bcopy (XVECTOR (menu_bar_items_vector)->contents,
-                XVECTOR (tem)->contents, i * sizeof (Lisp_Object));
-         menu_bar_items_vector = tem;
-       }
-
+       menu_bar_items_vector = larger_vector (menu_bar_items_vector, 2 * i, Qnil);
       /* Add this item.  */
       XVECTOR (menu_bar_items_vector)->contents[i++] = key;
       XVECTOR (menu_bar_items_vector)->contents[i++]
@@ -7502,11 +7711,11 @@ parse_menu_item (item, notreal, inmenubar)
 
   /* Initialize optional entries.  */
   for (i = ITEM_PROPERTY_DEF; i < ITEM_PROPERTY_ENABLE; i++)
-    AREF (item_properties, i) = Qnil;
-  AREF (item_properties, ITEM_PROPERTY_ENABLE) = Qt;
+    ASET (item_properties, i, Qnil);
+  ASET (item_properties, ITEM_PROPERTY_ENABLE, Qt);
 
   /* Save the item here to protect it from GC.  */
-  AREF (item_properties, ITEM_PROPERTY_ITEM) = item;
+  ASET (item_properties, ITEM_PROPERTY_ITEM, item);
 
   item_string = XCAR (item);
 
@@ -7515,12 +7724,12 @@ parse_menu_item (item, notreal, inmenubar)
   if (STRINGP (item_string))
     {
       /* Old format menu item.  */
-      AREF (item_properties, ITEM_PROPERTY_NAME) = item_string;
+      ASET (item_properties, ITEM_PROPERTY_NAME, item_string);
 
       /* Maybe help string.  */
       if (CONSP (item) && STRINGP (XCAR (item)))
        {
-         AREF (item_properties, ITEM_PROPERTY_HELP) = XCAR (item);
+         ASET (item_properties, ITEM_PROPERTY_HELP, XCAR (item));
          start = item;
          item = XCDR (item);
        }
@@ -7535,27 +7744,27 @@ parse_menu_item (item, notreal, inmenubar)
        }
 
       /* This is the real definition--the function to run.  */
-      AREF (item_properties, ITEM_PROPERTY_DEF) = item;
+      ASET (item_properties, ITEM_PROPERTY_DEF, item);
 
       /* Get enable property, if any.  */
       if (SYMBOLP (item))
        {
          tem = Fget (item, Qmenu_enable);
          if (!NILP (Venable_disabled_menus_and_buttons))
-           AREF (item_properties, ITEM_PROPERTY_ENABLE) = Qt;
+           ASET (item_properties, ITEM_PROPERTY_ENABLE, Qt);
          else if (!NILP (tem))
-           AREF (item_properties, ITEM_PROPERTY_ENABLE) = tem;
+           ASET (item_properties, ITEM_PROPERTY_ENABLE, tem);
        }
     }
   else if (EQ (item_string, Qmenu_item) && CONSP (item))
     {
       /* New format menu item.  */
-      AREF (item_properties, ITEM_PROPERTY_NAME) = XCAR (item);
+      ASET (item_properties, ITEM_PROPERTY_NAME, XCAR (item));
       start = XCDR (item);
       if (CONSP (start))
        {
          /* We have a real binding.  */
-         AREF (item_properties, ITEM_PROPERTY_DEF) = XCAR (start);
+         ASET (item_properties, ITEM_PROPERTY_DEF, XCAR (start));
 
          item = XCDR (start);
          /* Is there a cache list with key equivalences. */
@@ -7574,9 +7783,9 @@ parse_menu_item (item, notreal, inmenubar)
              if (EQ (tem, QCenable))
                {
                  if (!NILP (Venable_disabled_menus_and_buttons))
-                   AREF (item_properties, ITEM_PROPERTY_ENABLE) = Qt;
+                   ASET (item_properties, ITEM_PROPERTY_ENABLE, Qt);
                  else
-                   AREF (item_properties, ITEM_PROPERTY_ENABLE) = XCAR (item);
+                   ASET (item_properties, ITEM_PROPERTY_ENABLE, XCAR (item));
                }
              else if (EQ (tem, QCvisible) && !notreal)
                {
@@ -7587,7 +7796,7 @@ parse_menu_item (item, notreal, inmenubar)
                    return 0;
                }
              else if (EQ (tem, QChelp))
-               AREF (item_properties, ITEM_PROPERTY_HELP) = XCAR (item);
+               ASET (item_properties, ITEM_PROPERTY_HELP, XCAR (item));
              else if (EQ (tem, QCfilter))
                filter = item;
              else if (EQ (tem, QCkey_sequence))
@@ -7602,7 +7811,7 @@ parse_menu_item (item, notreal, inmenubar)
                {
                  tem = XCAR (item);
                  if (CONSP (tem) || (STRINGP (tem) && NILP (cachelist)))
-                   AREF (item_properties, ITEM_PROPERTY_KEYEQ) = tem;
+                   ASET (item_properties, ITEM_PROPERTY_KEYEQ, tem);
                }
              else if (EQ (tem, QCbutton) && CONSP (XCAR (item)))
                {
@@ -7611,10 +7820,9 @@ parse_menu_item (item, notreal, inmenubar)
                  type = XCAR (tem);
                  if (EQ (type, QCtoggle) || EQ (type, QCradio))
                    {
-                     AREF (item_properties, ITEM_PROPERTY_SELECTED)
-                       = XCDR (tem);
-                     AREF (item_properties, ITEM_PROPERTY_TYPE)
-                       = type;
+                     ASET (item_properties, ITEM_PROPERTY_SELECTED,
+                           XCDR (tem));
+                     ASET (item_properties, ITEM_PROPERTY_TYPE, type);
                    }
                }
              item = XCDR (item);
@@ -7634,7 +7842,7 @@ parse_menu_item (item, notreal, inmenubar)
       item_string = menu_item_eval_property (item_string);
       if (!STRINGP (item_string))
        return 0;
-      AREF (item_properties, ITEM_PROPERTY_NAME) = item_string;
+      ASET (item_properties, ITEM_PROPERTY_NAME, item_string);
     }
 
   /* If got a filter apply it on definition.  */
@@ -7644,7 +7852,7 @@ parse_menu_item (item, notreal, inmenubar)
       def = menu_item_eval_property (list2 (XCAR (filter),
                                            list2 (Qquote, def)));
 
-      AREF (item_properties, ITEM_PROPERTY_DEF) = def;
+      ASET (item_properties, ITEM_PROPERTY_DEF, def);
     }
 
   /* Enable or disable selection of item.  */
@@ -7657,7 +7865,7 @@ parse_menu_item (item, notreal, inmenubar)
        tem = menu_item_eval_property (tem);
       if (inmenubar && NILP (tem))
        return 0;               /* Ignore disabled items in menu bar.  */
-      AREF (item_properties, ITEM_PROPERTY_ENABLE) = tem;
+      ASET (item_properties, ITEM_PROPERTY_ENABLE, tem);
     }
 
   /* If we got no definition, this item is just unselectable text which
@@ -7671,8 +7879,8 @@ parse_menu_item (item, notreal, inmenubar)
   /* For a subkeymap, just record its details and exit.  */
   if (CONSP (tem))
     {
-      AREF (item_properties, ITEM_PROPERTY_MAP) = tem;
-      AREF (item_properties, ITEM_PROPERTY_DEF) = tem;
+      ASET (item_properties, ITEM_PROPERTY_MAP, tem);
+      ASET (item_properties, ITEM_PROPERTY_DEF, tem);
       return 1;
     }
 
@@ -7686,9 +7894,13 @@ parse_menu_item (item, notreal, inmenubar)
   if (NILP (cachelist))
     {
       /* We have to create a cachelist.  */
-      CHECK_IMPURE (start);
-      XSETCDR (start, Fcons (Fcons (Qnil, Qnil), XCDR (start)));
-      cachelist = XCAR (XCDR (start));
+      /* With the introduction of where_is_cache, the computation
+         of equivalent key bindings is sufficiently fast that we
+         do not need to cache it here any more. */
+      /* CHECK_IMPURE (start);
+         XSETCDR (start, Fcons (Fcons (Qnil, Qnil), XCDR (start)));
+        cachelist = XCAR (XCDR (start));  */
+      cachelist = Fcons (Qnil, Qnil);
       newcache = 1;
       tem = AREF (item_properties, ITEM_PROPERTY_KEYEQ);
       if (!NILP (keyhint))
@@ -7786,7 +7998,8 @@ parse_menu_item (item, notreal, inmenubar)
   tem = XCDR (cachelist);
   if (newcache && !NILP (tem))
     {
-      tem = concat3 (build_string ("  ("), tem, build_string (")"));
+      tem = concat2 (build_string ("  "), tem);
+      /* tem = concat3 (build_string ("  ("), tem, build_string (")")); */
       XSETCDR (cachelist, tem);
     }
 
@@ -7795,7 +8008,7 @@ parse_menu_item (item, notreal, inmenubar)
     return 1;
 
   /* If we have an equivalent key binding, use that.  */
-  AREF (item_properties, ITEM_PROPERTY_KEYEQ) = tem;
+  ASET (item_properties, ITEM_PROPERTY_KEYEQ, tem);
 
   /* Include this when menu help is implemented.
   tem = XVECTOR (item_properties)->contents[ITEM_PROPERTY_HELP];
@@ -7811,8 +8024,8 @@ parse_menu_item (item, notreal, inmenubar)
   /* Handle radio buttons or toggle boxes.  */
   tem = AREF (item_properties, ITEM_PROPERTY_SELECTED);
   if (!NILP (tem))
-    AREF (item_properties, ITEM_PROPERTY_SELECTED)
-      = menu_item_eval_property (tem);
+    ASET (item_properties, ITEM_PROPERTY_SELECTED,
+         menu_item_eval_property (tem));
 
   return 1;
 }
@@ -8130,7 +8343,7 @@ parse_tool_bar_item (key, item)
        PROP (TOOL_BAR_ITEM_IMAGES) = value;
       else if (EQ (key, Qrtl))
         /* ':rtl STRING' */
-        PROP (TOOL_BAR_ITEM_RTL_IMAGE) = value;
+       PROP (TOOL_BAR_ITEM_RTL_IMAGE) = value;
     }
 
   /* If got a filter apply it on binding.  */
@@ -8186,16 +8399,9 @@ append_tool_bar_item ()
   /* Enlarge tool_bar_items_vector if necessary.  */
   if (ntool_bar_items + TOOL_BAR_ITEM_NSLOTS
       >= XVECTOR (tool_bar_items_vector)->size)
-    {
-      Lisp_Object new_vector;
-      int old_size = XVECTOR (tool_bar_items_vector)->size;
-
-      new_vector = Fmake_vector (make_number (2 * old_size), Qnil);
-      bcopy (XVECTOR (tool_bar_items_vector)->contents,
-            XVECTOR (new_vector)->contents,
-            old_size * sizeof (Lisp_Object));
-      tool_bar_items_vector = new_vector;
-    }
+    tool_bar_items_vector
+      = larger_vector (tool_bar_items_vector,
+                      2 * XVECTOR (tool_bar_items_vector)->size, Qnil);
 
   /* Append entries from tool_bar_item_properties to the end of
      tool_bar_items_vector.  */
@@ -8299,7 +8505,7 @@ read_char_x_menu_prompt (nmaps, maps, prev_event, used_mouse_menu)
             to indicate that they came from a mouse menu,
             so that when present in last_nonmenu_event
             they won't confuse things.  */
-         for (tem = XCDR (value); !NILP (tem); tem = XCDR (tem))
+         for (tem = XCDR (value); CONSP (tem); tem = XCDR (tem))
            {
              record_menu_key (XCAR (tem));
              if (SYMBOLP (XCAR (tem))
@@ -8563,6 +8769,8 @@ read_char_minibuf_menu_prompt (commandflag, nmaps, maps)
 
       if (!INTEGERP (obj))
        return obj;
+      else if (XINT (obj) == -2)
+        return obj;
       else
        ch = XINT (obj);
 
@@ -8873,8 +9081,13 @@ read_key_sequence (keybuf, bufsize, prompt, dont_downcase_last,
      key's again in Vfunction_key_map.  */
   volatile keyremap fkey;
 
-  /* Likewise, for key_translation_map.  */
-  volatile keyremap keytran;
+  /* Likewise, for key_translation_map and input-decode-map.  */
+  volatile keyremap keytran, indec;
+
+  /* Non-zero if we are trying to map a key by changing an upper-case
+     letter to lower case, or a shifted function key to an unshifted
+     one. */
+  volatile int shift_translated = 0;
 
   /* If we receive a `switch-frame' or `select-window' event in the middle of
      a key sequence, we put it off for later.
@@ -8909,10 +9122,6 @@ read_key_sequence (keybuf, bufsize, prompt, dont_downcase_last,
   last_nonmenu_event = Qnil;
 
   delayed_switch_frame = Qnil;
-  fkey.map = fkey.parent = Vfunction_key_map;
-  keytran.map = keytran.parent = Vkey_translation_map;
-  fkey.start = fkey.end = 0;
-  keytran.start = keytran.end = 0;
 
   if (INTERACTIVE)
     {
@@ -8948,6 +9157,23 @@ read_key_sequence (keybuf, bufsize, prompt, dont_downcase_last,
   orig_keymap = get_local_map (PT, current_buffer, Qkeymap);
   from_string = Qnil;
 
+  /* The multi-tty merge moved the code below to right after
+   `replay_sequence' which caused all these translation maps to be applied
+   repeatedly, even tho their doc says very clearly they are not applied to
+   their own output.
+   The reason for this move was: "We may switch keyboards between rescans,
+   so we need to reinitialize fkey and keytran before each replay".
+   This move was wrong (even if we switch keyboards, keybuf still holds the
+   keys we've read already from the original keyboard and some of those keys
+   may have already been translated).  So there may still be a bug out there
+   lurking.  */
+  indec.map = indec.parent = current_kboard->Vinput_decode_map;
+  fkey.map = fkey.parent = current_kboard->Vlocal_function_key_map;
+  keytran.map = keytran.parent = Vkey_translation_map;
+  indec.start = indec.end = 0;
+  fkey.start = fkey.end = 0;
+  keytran.start = keytran.end = 0;
+
   /* We jump here when the key sequence has been thoroughly changed, and
      we need to rescan it starting from the beginning.  When we jump here,
      keybuf[0..mock_input] holds the sequence we should reread.  */
@@ -8971,8 +9197,7 @@ read_key_sequence (keybuf, bufsize, prompt, dont_downcase_last,
          defs    = (Lisp_Object *) alloca (2 * sizeof (defs[0]));
          nmaps_allocated = 2;
        }
-      if (!NILP (current_kboard->Voverriding_terminal_local_map))
-       submaps[nmaps++] = current_kboard->Voverriding_terminal_local_map;
+      submaps[nmaps++] = current_kboard->Voverriding_terminal_local_map;
     }
   else if (!NILP (Voverriding_local_map))
     {
@@ -8982,8 +9207,7 @@ read_key_sequence (keybuf, bufsize, prompt, dont_downcase_last,
          defs    = (Lisp_Object *) alloca (2 * sizeof (defs[0]));
          nmaps_allocated = 2;
        }
-      if (!NILP (Voverriding_local_map))
-       submaps[nmaps++] = Voverriding_local_map;
+      submaps[nmaps++] = Voverriding_local_map;
     }
   else
     {
@@ -9038,7 +9262,7 @@ read_key_sequence (keybuf, bufsize, prompt, dont_downcase_last,
            Thus, if ESC O a has a function-key-map translation
            and ESC o has a binding, don't return after ESC O,
            so that we can translate ESC O plus the next character.  */
-        : (fkey.start < t || keytran.start < t))
+        : (/* indec.start < t || fkey.start < t || */ keytran.start < t))
     {
       Lisp_Object key;
       int used_mouse_menu = 0;
@@ -9056,13 +9280,17 @@ read_key_sequence (keybuf, bufsize, prompt, dont_downcase_last,
         just one key.  */
       volatile int echo_local_start, keys_local_start, local_first_binding;
 
-      eassert (fkey.end == t || (fkey.end > t && fkey.end <= mock_input));
+      eassert (indec.end == t || (indec.end > t && indec.end <= mock_input));
+      eassert (indec.start <= indec.end);
       eassert (fkey.start <= fkey.end);
       eassert (keytran.start <= keytran.end);
-      /* key-translation-map is applied *after* function-key-map.  */
+      /* key-translation-map is applied *after* function-key-map
+        which is itself applied *after* input-decode-map.  */
+      eassert (fkey.end <= indec.start);
       eassert (keytran.end <= fkey.start);
 
-      if (first_unbound < fkey.start && first_unbound < keytran.start)
+      if (/* first_unbound < indec.start && first_unbound < fkey.start && */
+         first_unbound < keytran.start)
        { /* The prefix upto first_unbound has no binding and has
             no translation left to do either, so we know it's unbound.
             If we don't stop now, we risk staying here indefinitely
@@ -9072,6 +9300,8 @@ read_key_sequence (keybuf, bufsize, prompt, dont_downcase_last,
          for (i = first_unbound + 1; i < t; i++)
            keybuf[i - first_unbound - 1] = keybuf[i];
          mock_input = t - first_unbound - 1;
+         indec.end = indec.start -= first_unbound + 1;
+         indec.map = indec.parent;
          fkey.end = fkey.start -= first_unbound + 1;
          fkey.map = fkey.parent;
          keytran.end = keytran.start -= first_unbound + 1;
@@ -9114,11 +9344,28 @@ read_key_sequence (keybuf, bufsize, prompt, dont_downcase_last,
       else
        {
          {
-#ifdef MULTI_KBOARD
            KBOARD *interrupted_kboard = current_kboard;
            struct frame *interrupted_frame = SELECTED_FRAME ();
-           if (setjmp (wrong_kboard_jmpbuf))
+           key = read_char (NILP (prompt), nmaps,
+                            (Lisp_Object *) submaps, last_nonmenu_event,
+                            &used_mouse_menu, NULL);
+           if (INTEGERP (key) && XINT (key) == -2) /* wrong_kboard_jmpbuf */
              {
+               int found = 0;
+               struct kboard *k;
+
+               for (k = all_kboards; k; k = k->next_kboard)
+                 if (k == interrupted_kboard)
+                   found = 1;
+
+               if (!found)
+                 {
+                   /* Don't touch interrupted_kboard when it's been
+                      deleted. */
+                   delayed_switch_frame = Qnil;
+                   goto replay_sequence;
+                 }
+
                if (!NILP (delayed_switch_frame))
                  {
                    interrupted_kboard->kbd_queue
@@ -9126,6 +9373,7 @@ read_key_sequence (keybuf, bufsize, prompt, dont_downcase_last,
                               interrupted_kboard->kbd_queue);
                    delayed_switch_frame = Qnil;
                  }
+
                while (t > 0)
                  interrupted_kboard->kbd_queue
                    = Fcons (keybuf[--t], interrupted_kboard->kbd_queue);
@@ -9149,10 +9397,6 @@ read_key_sequence (keybuf, bufsize, prompt, dont_downcase_last,
                orig_keymap = get_local_map (PT, current_buffer, Qkeymap);
                goto replay_sequence;
              }
-#endif
-           key = read_char (NILP (prompt), nmaps,
-                            (Lisp_Object *) submaps, last_nonmenu_event,
-                            &used_mouse_menu, NULL);
          }
 
          /* read_char returns t when it shows a menu and the user rejects it.
@@ -9234,7 +9478,8 @@ read_key_sequence (keybuf, bufsize, prompt, dont_downcase_last,
            }
 
          GROW_RAW_KEYBUF;
-         XVECTOR (raw_keybuf)->contents[raw_keybuf_count++] = key;
+         ASET (raw_keybuf, raw_keybuf_count, key);
+         raw_keybuf_count++;
        }
 
       /* Clicks in non-text areas get prefixed by the symbol
@@ -9261,7 +9506,7 @@ read_key_sequence (keybuf, bufsize, prompt, dont_downcase_last,
            {
              Lisp_Object window, posn;
 
-             window = POSN_WINDOW      (EVENT_START (key));
+             window = POSN_WINDOW (EVENT_START (key));
              posn   = POSN_POSN (EVENT_START (key));
 
              if (CONSP (posn)
@@ -9479,15 +9724,15 @@ read_key_sequence (keybuf, bufsize, prompt, dont_downcase_last,
        /* This is needed for the following scenario:
           event 0: a down-event that gets dropped by calling replay_key.
           event 1: some normal prefix like C-h.
-          After event 0, first_unbound is 0, after event 1 fkey.start
-          and keytran.start are both 1, so when we see that C-h is bound,
-          we need to update first_unbound.  */
+          After event 0, first_unbound is 0, after event 1 indec.start,
+          fkey.start, and keytran.start are all 1, so when we see that
+          C-h is bound, we need to update first_unbound.  */
        first_unbound = max (t + 1, first_unbound);
       else
        {
          Lisp_Object head;
 
-         /* Remember the position to put an upper bound on fkey.start.  */
+         /* Remember the position to put an upper bound on indec.start.  */
          first_unbound = min (t, first_unbound);
 
          head = EVENT_HEAD (key);
@@ -9572,21 +9817,27 @@ read_key_sequence (keybuf, bufsize, prompt, dont_downcase_last,
                          /* If mock_input > t + 1, the above simplification
                             will actually end up dropping keys on the floor.
                             This is probably OK for now, but even
-                            if mock_input <= t + 1, we need to adjust fkey
-                            and keytran.
+                            if mock_input <= t + 1, we need to adjust indec,
+                            fkey, and keytran.
                             Typical case [header-line down-mouse-N]:
                             mock_input = 2, t = 1, fkey.end = 1,
                             last_real_key_start = 0.  */
-                         if (fkey.end > last_real_key_start)
+                         if (indec.end > last_real_key_start)
                            {
-                             fkey.end = fkey.start
-                               = min (last_real_key_start, fkey.start);
-                             fkey.map = fkey.parent;
-                             if (keytran.end > last_real_key_start)
+                             indec.end = indec.start
+                               = min (last_real_key_start, indec.start);
+                             indec.map = indec.parent;
+                             if (fkey.end > last_real_key_start)
                                {
-                                 keytran.end = keytran.start
-                                   = min (last_real_key_start, keytran.start);
-                                 keytran.map = keytran.parent;
+                                 fkey.end = fkey.start
+                                   = min (last_real_key_start, fkey.start);
+                                 fkey.map = fkey.parent;
+                                 if (keytran.end > last_real_key_start)
+                                   {
+                                     keytran.end = keytran.start
+                                       = min (last_real_key_start, keytran.start);
+                                     keytran.map = keytran.parent;
+                                   }
                                }
                            }
                          if (t == last_real_key_start)
@@ -9640,8 +9891,28 @@ read_key_sequence (keybuf, bufsize, prompt, dont_downcase_last,
       /* Record what part of this_command_keys is the current key sequence.  */
       this_single_command_key_start = this_command_key_count - t;
 
-      if (first_binding < nmaps && NILP (submaps[first_binding]))
+      /* Look for this sequence in input-decode-map.
+        Scan from indec.end until we find a bound suffix.  */
+      while (indec.end < t)
+       {
+         struct gcpro gcpro1, gcpro2, gcpro3, gcpro4;
+         int done, diff;
+
+         GCPRO4 (indec.map, fkey.map, keytran.map, delayed_switch_frame);
+         done = keyremap_step (keybuf, bufsize, &indec, max (t, mock_input),
+                               1, &diff, prompt);
+         UNGCPRO;
+         if (done)
+           {
+             mock_input = diff + max (t, mock_input);
+             goto replay_sequence;
+           }
+       }
+
+      if (first_binding < nmaps && NILP (submaps[first_binding])
+         && indec.start >= t)
        /* There is a binding and it's not a prefix.
+          (and it doesn't have any input-decode-map translation pending).
           There is thus no function-key in this sequence.
           Moving fkey.start is important in this case to allow keytran.start
           to go over the sequence before we return (since we keep the
@@ -9654,12 +9925,12 @@ read_key_sequence (keybuf, bufsize, prompt, dont_downcase_last,
        /* If the sequence is unbound, see if we can hang a function key
           off the end of it.  */
        /* Continue scan from fkey.end until we find a bound suffix.  */
-       while (fkey.end < t)
+       while (fkey.end < indec.start)
          {
-           struct gcpro gcpro1, gcpro2, gcpro3;
+           struct gcpro gcpro1, gcpro2, gcpro3, gcpro4;
            int done, diff;
 
-           GCPRO3 (fkey.map, keytran.map, delayed_switch_frame);
+           GCPRO4 (indec.map, fkey.map, keytran.map, delayed_switch_frame);
            done = keyremap_step (keybuf, bufsize, &fkey,
                                  max (t, mock_input),
                                  /* If there's a binding (i.e.
@@ -9671,6 +9942,10 @@ read_key_sequence (keybuf, bufsize, prompt, dont_downcase_last,
            if (done)
              {
                mock_input = diff + max (t, mock_input);
+               /* Adjust the input-decode-map counters.  */
+               indec.end += diff;
+               indec.start += diff;
+
                goto replay_sequence;
              }
          }
@@ -9679,17 +9954,19 @@ read_key_sequence (keybuf, bufsize, prompt, dont_downcase_last,
         Scan from keytran.end until we find a bound suffix.  */
       while (keytran.end < fkey.start)
        {
-         struct gcpro gcpro1, gcpro2, gcpro3;
+         struct gcpro gcpro1, gcpro2, gcpro3, gcpro4;
          int done, diff;
 
-         GCPRO3 (fkey.map, keytran.map, delayed_switch_frame);
+         GCPRO4 (indec.map, fkey.map, keytran.map, delayed_switch_frame);
          done = keyremap_step (keybuf, bufsize, &keytran, max (t, mock_input),
                                1, &diff, prompt);
          UNGCPRO;
          if (done)
            {
              mock_input = diff + max (t, mock_input);
-             /* Adjust the function-key-map counters.  */
+             /* Adjust the function-key-map and input-decode-map counters.  */
+             indec.end += diff;
+             indec.start += diff;
              fkey.end += diff;
              fkey.start += diff;
 
@@ -9702,11 +9979,10 @@ read_key_sequence (keybuf, bufsize, prompt, dont_downcase_last,
         and is an upper case letter
         use the corresponding lower-case letter instead.  */
       if (first_binding >= nmaps
-         && fkey.start >= t && keytran.start >= t
+         && /* indec.start >= t && fkey.start >= t && */ keytran.start >= t
          && INTEGERP (key)
-         && ((((XINT (key) & 0x3ffff)
-               < XCHAR_TABLE (current_buffer->downcase_table)->size)
-              && UPPERCASEP (XINT (key) & 0x3ffff))
+         && ((CHARACTERP (make_number (XINT (key) & ~CHAR_MODIFIER_MASK))
+              && UPPERCASEP (XINT (key) & ~CHAR_MODIFIER_MASK))
              || (XINT (key) & shift_modifier)))
        {
          Lisp_Object new_key;
@@ -9717,14 +9993,15 @@ read_key_sequence (keybuf, bufsize, prompt, dont_downcase_last,
          if (XINT (key) & shift_modifier)
            XSETINT (new_key, XINT (key) & ~shift_modifier);
          else
-           XSETINT (new_key, (DOWNCASE (XINT (key) & 0x3ffff)
-                              | (XINT (key) & ~0x3ffff)));
+           XSETINT (new_key, (DOWNCASE (XINT (key) & ~CHAR_MODIFIER_MASK)
+                              | (XINT (key) & CHAR_MODIFIER_MASK)));
 
          /* We have to do this unconditionally, regardless of whether
             the lower-case char is defined in the keymaps, because they
             might get translated through function-key-map.  */
          keybuf[t - 1] = new_key;
          mock_input = max (t, mock_input);
+         shift_translated = 1;
 
          goto replay_sequence;
        }
@@ -9733,35 +10010,45 @@ read_key_sequence (keybuf, bufsize, prompt, dont_downcase_last,
         and is a shifted function key,
         use the corresponding unshifted function key instead.  */
       if (first_binding >= nmaps
-         && fkey.start >= t && keytran.start >= t
-         && SYMBOLP (key))
-       {
-         Lisp_Object breakdown;
-         int modifiers;
-
-         breakdown = parse_modifiers (key);
-         modifiers = XINT (XCAR (XCDR (breakdown)));
-         if (modifiers & shift_modifier)
+         && /* indec.start >= t && fkey.start >= t && */ keytran.start >= t)
+       {
+         Lisp_Object breakdown = parse_modifiers (key);
+         int modifiers
+           = CONSP (breakdown) ? (XINT (XCAR (XCDR (breakdown)))) : 0;
+
+         if (modifiers & shift_modifier
+             /* Treat uppercase keys as shifted.  */
+             || (INTEGERP (key)
+                 && (KEY_TO_CHAR (key)
+                     < XCHAR_TABLE (current_buffer->downcase_table)->size)
+                 && UPPERCASEP (KEY_TO_CHAR (key))))
            {
-             Lisp_Object new_key;
+             Lisp_Object new_key
+               = (modifiers & shift_modifier
+                  ? apply_modifiers (modifiers & ~shift_modifier,
+                                     XCAR (breakdown))
+                  : make_number (DOWNCASE (KEY_TO_CHAR (key)) | modifiers));
 
              original_uppercase = key;
              original_uppercase_position = t - 1;
 
-             modifiers &= ~shift_modifier;
-             new_key = apply_modifiers (modifiers,
-                                        XCAR (breakdown));
-
+             /* We have to do this unconditionally, regardless of whether
+                the lower-case char is defined in the keymaps, because they
+                might get translated through function-key-map.  */
              keybuf[t - 1] = new_key;
              mock_input = max (t, mock_input);
+             /* Reset fkey (and consequently keytran) to apply
+                function-key-map on the result, so that S-backspace is
+                correctly mapped to DEL (via backspace).  OTOH,
+                input-decode-map doesn't need to go through it again.  */
              fkey.start = fkey.end = 0;
              keytran.start = keytran.end = 0;
+             shift_translated = 1;
 
              goto replay_sequence;
            }
        }
     }
-
   if (!dummyflag)
     read_key_sequence_cmd = (first_binding < nmaps
                             ? defs[first_binding]
@@ -9775,7 +10062,13 @@ read_key_sequence (keybuf, bufsize, prompt, dont_downcase_last,
   if ((dont_downcase_last || first_binding >= nmaps)
       && t > 0
       && t - 1 == original_uppercase_position)
-    keybuf[t - 1] = original_uppercase;
+    {
+      keybuf[t - 1] = original_uppercase;
+      shift_translated = 0;
+    }
+
+  if (shift_translated)
+    Vthis_command_keys_shift_translated = Qt;
 
   /* Occasionally we fabricate events, perhaps by expanding something
      according to function-key-map, or by adding a prefix symbol to a
@@ -9794,8 +10087,6 @@ read_key_sequence (keybuf, bufsize, prompt, dont_downcase_last,
       add_command_key (keybuf[t]);
     }
 
-
-
   UNGCPRO;
   return t;
 }
@@ -9877,7 +10168,7 @@ will read just one key sequence.  */)
       this_single_command_key_start = 0;
     }
 
-#ifdef HAVE_X_WINDOWS
+#ifdef HAVE_WINDOW_SYSTEM
   if (display_hourglass_p)
     cancel_hourglass ();
 #endif
@@ -9889,7 +10180,7 @@ will read just one key sequence.  */)
 #if 0  /* The following is fine for code reading a key sequence and
          then proceeding with a lenghty computation, but it's not good
          for code reading keys in a loop, like an input method.  */
-#ifdef HAVE_X_WINDOWS
+#ifdef HAVE_WINDOW_SYSTEM
   if (display_hourglass_p)
     start_hourglass ();
 #endif
@@ -9937,7 +10228,7 @@ DEFUN ("read-key-sequence-vector", Fread_key_sequence_vector,
       this_single_command_key_start = 0;
     }
 
-#ifdef HAVE_X_WINDOWS
+#ifdef HAVE_WINDOW_SYSTEM
   if (display_hourglass_p)
     cancel_hourglass ();
 #endif
@@ -9946,7 +10237,7 @@ DEFUN ("read-key-sequence-vector", Fread_key_sequence_vector,
                         prompt, ! NILP (dont_downcase_last),
                         ! NILP (can_return_switch_frame), 0);
 
-#ifdef HAVE_X_WINDOWS
+#ifdef HAVE_WINDOW_SYSTEM
   if (display_hourglass_p)
     start_hourglass ();
 #endif
@@ -9976,7 +10267,6 @@ a special event, so ignore the prefix argument and don't clear it.  */)
   register Lisp_Object final;
   register Lisp_Object tem;
   Lisp_Object prefixarg;
-  struct backtrace backtrace;
   extern int debug_on_next_call;
 
   debug_on_next_call = 0;
@@ -10042,20 +10332,11 @@ a special event, so ignore the prefix argument and don't clear it.  */)
     }
 
   if (CONSP (final) || SUBRP (final) || COMPILEDP (final))
-    {
-      backtrace.next = backtrace_list;
-      backtrace_list = &backtrace;
-      backtrace.function = &Qcall_interactively;
-      backtrace.args = &cmd;
-      backtrace.nargs = 1;
-      backtrace.evalargs = 0;
-      backtrace.debug_on_exit = 0;
-
-      tem = Fcall_interactively (cmd, record_flag, keys);
+    /* Don't call Fcall_interactively directly because we want to make
+       sure the backtrace has an entry for `call-interactively'.
+       For the same reason, pass `cmd' rather than `final'.  */
+      return call3 (Qcall_interactively, cmd, record_flag, keys);
 
-      backtrace_list = backtrace.next;
-      return tem;
-    }
   return Qnil;
 }
 
@@ -10079,7 +10360,7 @@ give to the command you invoke, if it asks for an argument.  */)
   Lisp_Object saved_keys, saved_last_point_position_buffer;
   Lisp_Object bindings, value;
   struct gcpro gcpro1, gcpro2, gcpro3;
-#ifdef HAVE_X_WINDOWS
+#ifdef HAVE_WINDOW_SYSTEM
   /* The call to Fcompleting_read wil start and cancel the hourglass,
      but if the hourglass was already scheduled, this means that no
      hourglass will be shown for the actual M-x command itself.
@@ -10119,7 +10400,7 @@ give to the command you invoke, if it asks for an argument.  */)
                               Qt, Qnil, Qextended_command_history, Qnil,
                               Qnil);
 
-#ifdef HAVE_X_WINDOWS
+#ifdef HAVE_WINDOW_SYSTEM
   if (hstarted) start_hourglass ();
 #endif
 
@@ -10166,7 +10447,7 @@ give to the command you invoke, if it asks for an argument.  */)
     bindings = Qnil;
 
   value = Qnil;
-  GCPRO2 (bindings, value);
+  GCPRO3 (bindings, value, function);
   value = Fcommand_execute (function, Qt, Qnil, Qnil);
 
   /* If the command has a key binding, print it now.  */
@@ -10264,8 +10545,12 @@ detect_input_pending_run_timers (do_display)
         from an idle timer function.  The symptom of the bug is that
         the cursor sometimes doesn't become visible until the next X
         event is processed.  --gerd.  */
-      if (rif)
-       rif->flush_display (NULL);
+      {
+        Lisp_Object tail, frame;
+        FOR_EACH_FRAME (tail, frame)
+          if (FRAME_RIF (XFRAME (frame)))
+            FRAME_RIF (XFRAME (frame))->flush_display (XFRAME (frame));
+      }
     }
 
   return input_pending;
@@ -10517,6 +10802,9 @@ On such systems, Emacs starts a subshell instead of suspending.  */)
   int width, height;
   struct gcpro gcpro1;
 
+  if (tty_list && tty_list->next)
+    error ("There are other tty frames open; close them before suspending Emacs");
+
   if (!NILP (stuffstring))
     CHECK_STRING (stuffstring);
 
@@ -10525,11 +10813,11 @@ On such systems, Emacs starts a subshell instead of suspending.  */)
     call1 (Vrun_hooks, intern ("suspend-hook"));
 
   GCPRO1 (stuffstring);
-  get_frame_size (&old_width, &old_height);
-  reset_sys_modes ();
+  get_tty_size (fileno (CURTTY ()->input), &old_width, &old_height);
+  reset_all_sys_modes ();
   /* sys_suspend can get an error if it tries to fork a subshell
      and the system resources aren't available for that.  */
-  record_unwind_protect ((Lisp_Object (*) P_ ((Lisp_Object))) init_sys_modes,
+  record_unwind_protect ((Lisp_Object (*) P_ ((Lisp_Object))) init_all_sys_modes,
                         Qnil);
   stuff_buffered_input (stuffstring);
   if (cannot_suspend)
@@ -10541,7 +10829,7 @@ On such systems, Emacs starts a subshell instead of suspending.  */)
   /* Check if terminal/window size has changed.
      Note that this is not useful when we are running directly
      with a window system; but suspend should be disabled in that case.  */
-  get_frame_size (&width, &height);
+  get_tty_size (fileno (CURTTY ()->input), &width, &height);
   if (width != old_width || height != old_height)
     change_frame_size (SELECTED_FRAME (), height, width, 0, 0, 0);
 
@@ -10601,10 +10889,10 @@ set_waiting_for_input (time_to_clear)
 {
   input_available_clear_time = time_to_clear;
 
-  /* Tell interrupt_signal to throw back to read_char,  */
+  /* Tell handle_interrupt to throw back to read_char,  */
   waiting_for_input = 1;
 
-  /* If interrupt_signal was called before and buffered a C-g,
+  /* If handle_interrupt was called before and buffered a C-g,
      make it run again now, to avoid timing error. */
   if (!NILP (Vquit_flag))
     quit_throw_to_read_char ();
@@ -10613,48 +10901,82 @@ set_waiting_for_input (time_to_clear)
 void
 clear_waiting_for_input ()
 {
-  /* Tell interrupt_signal not to throw back to read_char,  */
+  /* Tell handle_interrupt not to throw back to read_char,  */
   waiting_for_input = 0;
   input_available_clear_time = 0;
 }
 
-/* This routine is called at interrupt level in response to C-g.
-
-   If interrupt_input, this is the handler for SIGINT.  Otherwise, it
-   is called from kbd_buffer_store_event, in handling SIGIO or
-   SIGTINT.
-
-   If `waiting_for_input' is non zero, then unless `echoing' is
-   nonzero, immediately throw back to read_char.
+/* The SIGINT handler.
 
-   Otherwise it sets the Lisp variable quit-flag not-nil.  This causes
-   eval to throw, when it gets a chance.  If quit-flag is already
-   non-nil, it stops the job right away.  */
+   If we have a frame on the controlling tty, we assume that the
+   SIGINT was generated by C-g, so we call handle_interrupt.
+   Otherwise, the handler kills Emacs.  */
 
 static SIGTYPE
 interrupt_signal (signalnum)   /* If we don't have an argument, */
      int signalnum;            /* some compilers complain in signal calls. */
 {
-  char c;
   /* Must preserve main program's value of errno.  */
   int old_errno = errno;
-  struct frame *sf = SELECTED_FRAME ();
+  struct terminal *terminal;
 
 #if defined (USG) && !defined (POSIX_SIGNALS)
-  if (!read_socket_hook && NILP (Vwindow_system))
-    {
-      /* USG systems forget handlers when they are used;
-        must reestablish each time */
-      signal (SIGINT, interrupt_signal);
-      signal (SIGQUIT, interrupt_signal);
-    }
+  /* USG systems forget handlers when they are used;
+     must reestablish each time */
+  signal (SIGINT, interrupt_signal);
+  signal (SIGQUIT, interrupt_signal);
 #endif /* USG */
 
   SIGNAL_THREAD_CHECK (signalnum);
+
+  /* See if we have an active terminal on our controlling tty. */
+  terminal = get_named_tty ("/dev/tty");
+  if (!terminal)
+    {
+      /* If there are no frames there, let's pretend that we are a
+         well-behaving UN*X program and quit. */
+      Fkill_emacs (Qnil);
+    }
+  else
+    {
+      /* Otherwise, the SIGINT was probably generated by C-g.  */
+
+      /* Set internal_last_event_frame to the top frame of the
+         controlling tty, if we have a frame there.  We disable the
+         interrupt key on secondary ttys, so the SIGINT must have come
+         from the controlling tty.  */
+      internal_last_event_frame = terminal->display_info.tty->top_frame;
+
+      handle_interrupt ();
+    }
+
+  errno = old_errno;
+}
+
+/* This routine is called at interrupt level in response to C-g.
+
+   It is called from the SIGINT handler or kbd_buffer_store_event.
+
+   If `waiting_for_input' is non zero, then unless `echoing' is
+   nonzero, immediately throw back to read_char.
+
+   Otherwise it sets the Lisp variable quit-flag not-nil.  This causes
+   eval to throw, when it gets a chance.  If quit-flag is already
+   non-nil, it stops the job right away. */
+
+static void
+handle_interrupt ()
+{
+  char c;
+
   cancel_echoing ();
 
+  /* XXX This code needs to be revised for multi-tty support. */
   if (!NILP (Vquit_flag)
-      && (FRAME_TERMCAP_P (sf) || FRAME_MSDOS_P (sf)))
+#ifndef MSDOS
+      && get_named_tty ("/dev/tty")
+#endif
+      )
     {
       /* If SIGINT isn't blocked, don't let us be interrupted by
         another SIGINT, it might be harmful due to non-reentrancy
@@ -10662,7 +10984,7 @@ interrupt_signal (signalnum)    /* If we don't have an argument, */
       sigblock (sigmask (SIGINT));
 
       fflush (stdout);
-      reset_sys_modes ();
+      reset_all_sys_modes ();
 
 #ifdef SIGTSTP                 /* Support possible in later USG versions */
 /*
@@ -10674,19 +10996,11 @@ interrupt_signal (signalnum)  /* If we don't have an argument, */
  */
       sys_suspend ();
 #else
-#ifdef VMS
-      if (sys_suspend () == -1)
-       {
-         printf ("Not running as a subprocess;\n");
-         printf ("you can continue or abort.\n");
-       }
-#else /* not VMS */
       /* Perhaps should really fork an inferior shell?
         But that would not provide any way to get back
         to the original shell, ever.  */
       printf ("No support for stopping a process on this operating system;\n");
       printf ("you can continue or abort.\n");
-#endif /* not VMS */
 #endif /* not SIGTSTP */
 #ifdef MSDOS
       /* We must remain inside the screen area when the internal terminal
@@ -10725,11 +11039,7 @@ interrupt_signal (signalnum)   /* If we don't have an argument, */
 #ifdef MSDOS
       printf ("\r\nAbort?  (y or n) ");
 #else /* not MSDOS */
-#ifdef VMS
-      printf ("Abort (and enter debugger)? (y or n) ");
-#else /* not VMS */
       printf ("Abort (and dump core)? (y or n) ");
-#endif /* not VMS */
 #endif /* not MSDOS */
       fflush (stdout);
       if (((c = getchar ()) & ~040) == 'Y')
@@ -10741,7 +11051,7 @@ interrupt_signal (signalnum)    /* If we don't have an argument, */
       printf ("Continuing...\n");
 #endif /* not MSDOS */
       fflush (stdout);
-      init_sys_modes ();
+      init_all_sys_modes ();
       sigfree ();
     }
   else
@@ -10769,9 +11079,7 @@ interrupt_signal (signalnum)    /* If we don't have an argument, */
     }
 
   if (waiting_for_input && !echoing)
-    quit_throw_to_read_char ();
-
-  errno = old_errno;
+      quit_throw_to_read_char ();
 }
 
 /* Handle a C-g by making read_char return C-g.  */
@@ -10804,75 +11112,198 @@ quit_throw_to_read_char ()
   _longjmp (getcjmp, 1);
 }
 \f
-DEFUN ("set-input-mode", Fset_input_mode, Sset_input_mode, 3, 4, 0,
-       doc: /* Set mode of reading keyboard input.
-First arg INTERRUPT non-nil means use input interrupts;
- nil means use CBREAK mode.
-Second arg FLOW non-nil means use ^S/^Q flow control for output to terminal
- (no effect except in CBREAK mode).
-Third arg META t means accept 8-bit input (for a Meta key).
- META nil means ignore the top bit, on the assumption it is parity.
- Otherwise, accept 8-bit input and don't use the top bit for Meta.
-Optional fourth arg QUIT if non-nil specifies character to use for quitting.
+DEFUN ("set-input-interrupt-mode", Fset_input_interrupt_mode, Sset_input_interrupt_mode, 1, 1, 0,
+       doc: /* Set interrupt mode of reading keyboard input.
+If INTERRUPT is non-nil, Emacs will use input interrupts;
+otherwise Emacs uses CBREAK mode.
+
 See also `current-input-mode'.  */)
-     (interrupt, flow, meta, quit)
-     Lisp_Object interrupt, flow, meta, quit;
+     (interrupt)
+     Lisp_Object interrupt;
 {
-  if (!NILP (quit)
-      && (!INTEGERP (quit) || XINT (quit) < 0 || XINT (quit) > 0400))
-    error ("set-input-mode: QUIT must be an ASCII character");
-
-#ifdef POLL_FOR_INPUT
-  stop_polling ();
-#endif
-
-#ifndef DOS_NT
-  /* this causes startup screen to be restored and messes with the mouse */
-  reset_sys_modes ();
-#endif
-
+  int new_interrupt_input;
 #ifdef SIGIO
 /* Note SIGIO has been undef'd if FIONREAD is missing.  */
-  if (read_socket_hook)
+#ifdef HAVE_X_WINDOWS
+  if (x_display_list != NULL)
     {
       /* When using X, don't give the user a real choice,
         because we haven't implemented the mechanisms to support it.  */
 #ifdef NO_SOCK_SIGIO
-      interrupt_input = 0;
+      new_interrupt_input = 0;
 #else /* not NO_SOCK_SIGIO */
-      interrupt_input = 1;
+      new_interrupt_input = 1;
 #endif /* NO_SOCK_SIGIO */
     }
   else
-    interrupt_input = !NILP (interrupt);
+#endif
+    new_interrupt_input = !NILP (interrupt);
 #else /* not SIGIO */
-  interrupt_input = 0;
+  new_interrupt_input = 0;
 #endif /* not SIGIO */
 
-/* Our VMS input only works by interrupts, as of now.  */
-#ifdef VMS
-  interrupt_input = 1;
+  if (new_interrupt_input != interrupt_input)
+    {
+#ifdef POLL_FOR_INPUT
+      stop_polling ();
+#endif
+#ifndef DOS_NT
+      /* this causes startup screen to be restored and messes with the mouse */
+      reset_all_sys_modes ();
+#endif
+      interrupt_input = new_interrupt_input;
+#ifndef DOS_NT
+      init_all_sys_modes ();
+#endif
+
+#ifdef POLL_FOR_INPUT
+      poll_suppress_count = 1;
+      start_polling ();
 #endif
+    }
+  return Qnil;
+}
+
+DEFUN ("set-output-flow-control", Fset_output_flow_control, Sset_output_flow_control, 1, 2, 0,
+       doc: /* Enable or disable ^S/^Q flow control for output to TERMINAL.
+If FLOW is non-nil, flow control is enabled and you cannot use C-s or
+C-q in key sequences.
+
+This setting only has an effect on tty terminals and only when
+Emacs reads input in CBREAK mode; see `set-input-interrupt-mode'.
+
+See also `current-input-mode'.  */)
+       (flow, terminal)
+       Lisp_Object flow, terminal;
+{
+  struct terminal *t = get_terminal (terminal, 1);
+  struct tty_display_info *tty;
+  if (t == NULL || t->type != output_termcap)
+    return Qnil;
+  tty = t->display_info.tty;
+
+  if (tty->flow_control != !NILP (flow))
+    {
+#ifndef DOS_NT
+      /* this causes startup screen to be restored and messes with the mouse */
+      reset_sys_modes (tty);
+#endif
+
+      tty->flow_control = !NILP (flow);
+
+#ifndef DOS_NT
+      init_sys_modes (tty);
+#endif
+    }
+  return Qnil;
+}
+
+DEFUN ("set-input-meta-mode", Fset_input_meta_mode, Sset_input_meta_mode, 1, 2, 0,
+       doc: /* Enable or disable 8-bit input on TERMINAL.
+If META is t, Emacs will accept 8-bit input, and interpret the 8th
+bit as the Meta modifier.
+
+If META is nil, Emacs will ignore the top bit, on the assumption it is
+parity.
+
+Otherwise, Emacs will accept and pass through 8-bit input without
+specially interpreting the top bit.
+
+This setting only has an effect on tty terminal devices.
+
+Optional parameter TERMINAL specifies the tty terminal device to use.
+It may be a terminal id, a frame, or nil for the terminal used by the
+currently selected frame.
+
+See also `current-input-mode'.  */)
+       (meta, terminal)
+       Lisp_Object meta, terminal;
+{
+  struct terminal *t = get_terminal (terminal, 1);
+  struct tty_display_info *tty;
+  int new_meta;
+
+  if (t == NULL || t->type != output_termcap)
+    return Qnil;
+  tty = t->display_info.tty;
 
-  flow_control = !NILP (flow);
   if (NILP (meta))
-    meta_key = 0;
+    new_meta = 0;
   else if (EQ (meta, Qt))
-    meta_key = 1;
+    new_meta = 1;
   else
-    meta_key = 2;
-  if (!NILP (quit))
-    /* Don't let this value be out of range.  */
-    quit_char = XINT (quit) & (meta_key ? 0377 : 0177);
+    new_meta = 2;
 
+  if (tty->meta_key != new_meta)
+    {
 #ifndef DOS_NT
-  init_sys_modes ();
+      /* this causes startup screen to be restored and messes with the mouse */
+      reset_sys_modes (tty);
 #endif
 
-#ifdef POLL_FOR_INPUT
-  poll_suppress_count = 1;
-  start_polling ();
+      tty->meta_key = new_meta;
+
+#ifndef DOS_NT
+      init_sys_modes (tty);
 #endif
+    }
+  return Qnil;
+}
+
+DEFUN ("set-quit-char", Fset_quit_char, Sset_quit_char, 1, 1, 0,
+       doc: /* Specify character used for quitting.
+QUIT must be an ASCII character.
+
+This function only has an effect on the controlling tty of the Emacs
+process.
+
+See also `current-input-mode'.  */)
+       (quit)
+       Lisp_Object quit;
+{
+  struct terminal *t = get_named_tty ("/dev/tty");
+  struct tty_display_info *tty;
+  if (t == NULL || t->type != output_termcap)
+    return Qnil;
+  tty = t->display_info.tty;
+
+  if (NILP (quit) || !INTEGERP (quit) || XINT (quit) < 0 || XINT (quit) > 0400)
+    error ("QUIT must be an ASCII character");
+
+#ifndef DOS_NT
+  /* this causes startup screen to be restored and messes with the mouse */
+  reset_sys_modes (tty);
+#endif
+
+  /* Don't let this value be out of range.  */
+  quit_char = XINT (quit) & (tty->meta_key == 0 ? 0177 : 0377);
+
+#ifndef DOS_NT
+  init_sys_modes (tty);
+#endif
+
+  return Qnil;
+}
+
+DEFUN ("set-input-mode", Fset_input_mode, Sset_input_mode, 3, 4, 0,
+       doc: /* Set mode of reading keyboard input.
+First arg INTERRUPT non-nil means use input interrupts;
+ nil means use CBREAK mode.
+Second arg FLOW non-nil means use ^S/^Q flow control for output to terminal
+ (no effect except in CBREAK mode).
+Third arg META t means accept 8-bit input (for a Meta key).
+ META nil means ignore the top bit, on the assumption it is parity.
+ Otherwise, accept 8-bit input and don't use the top bit for Meta.
+Optional fourth arg QUIT if non-nil specifies character to use for quitting.
+See also `current-input-mode'.  */)
+     (interrupt, flow, meta, quit)
+     Lisp_Object interrupt, flow, meta, quit;
+{
+  Fset_input_interrupt_mode (interrupt);
+  Fset_output_flow_control (flow, Qnil);
+  Fset_input_meta_mode (meta, Qnil);
+  if (!NILP (quit))
+    Fset_quit_char (quit);
   return Qnil;
 }
 
@@ -10893,10 +11324,21 @@ The elements of this list correspond to the arguments of
      ()
 {
   Lisp_Object val[4];
+  struct frame *sf = XFRAME (selected_frame);
 
   val[0] = interrupt_input ? Qt : Qnil;
-  val[1] = flow_control ? Qt : Qnil;
-  val[2] = meta_key == 2 ? make_number (0) : meta_key == 1 ? Qt : Qnil;
+  if (FRAME_TERMCAP_P (sf))
+    {
+      val[1] = FRAME_TTY (sf)->flow_control ? Qt : Qnil;
+      val[2] = (FRAME_TTY (sf)->meta_key == 2
+                ? make_number (0)
+                : (CURTTY ()->meta_key == 1 ? Qt : Qnil));
+    }
+  else
+    {
+      val[1] = Qnil;
+      val[2] = Qt;
+    }
   XSETFASTINT (val[3], quit_char);
 
   return Flist (sizeof (val) / sizeof (val[0]), val);
@@ -10988,6 +11430,7 @@ init_kboard (kb)
   kb->Voverriding_terminal_local_map = Qnil;
   kb->Vlast_command = Qnil;
   kb->Vreal_last_command = Qnil;
+  kb->Vkeyboard_translate_table = Qnil;
   kb->Vlast_repeatable_command = Qnil;
   kb->Vprefix_arg = Qnil;
   kb->Vlast_prefix_arg = Qnil;
@@ -11003,6 +11446,10 @@ init_kboard (kb)
   kb->reference_count = 0;
   kb->Vsystem_key_alist = Qnil;
   kb->system_key_syms = Qnil;
+  kb->Vwindow_system = Qt;     /* Unset.  */
+  kb->Vinput_decode_map = Fmake_sparse_keymap (Qnil);
+  kb->Vlocal_function_key_map = Fmake_sparse_keymap (Qnil);
+  Fset_keymap_parent (kb->Vlocal_function_key_map, Vfunction_key_map);
   kb->Vdefault_minibuffer_frame = Qnil;
 }
 
@@ -11015,12 +11462,9 @@ static void
 wipe_kboard (kb)
      KBOARD *kb;
 {
-  if (kb->kbd_macro_buffer)
-    xfree (kb->kbd_macro_buffer);
+  xfree (kb->kbd_macro_buffer);
 }
 
-#ifdef MULTI_KBOARD
-
 /* Free KB and memory referenced from it.  */
 
 void
@@ -11039,7 +11483,8 @@ delete_kboard (kb)
       && FRAMEP (selected_frame)
       && FRAME_LIVE_P (XFRAME (selected_frame)))
     {
-      current_kboard = XFRAME (selected_frame)->kboard;
+      current_kboard = FRAME_KBOARD (XFRAME (selected_frame));
+      single_kboard = 0;
       if (current_kboard == kb)
        abort ();
     }
@@ -11048,8 +11493,6 @@ delete_kboard (kb)
   xfree (kb);
 }
 
-#endif /* MULTI_KBOARD */
-
 void
 init_keyboard ()
 {
@@ -11064,7 +11507,7 @@ init_keyboard ()
   recent_keys_index = 0;
   kbd_fetch_ptr = kbd_buffer;
   kbd_store_ptr = kbd_buffer;
-#ifdef HAVE_MOUSE
+#if defined (HAVE_MOUSE) || defined (HAVE_GPM)
   do_mouse_tracking = Qnil;
 #endif
   input_pending = 0;
@@ -11076,14 +11519,22 @@ init_keyboard ()
   internal_last_event_frame = Qnil;
   Vlast_event_frame = internal_last_event_frame;
 
-#ifdef MULTI_KBOARD
   current_kboard = initial_kboard;
-#endif
+  /* Re-initialize the keyboard again.  */
   wipe_kboard (current_kboard);
   init_kboard (current_kboard);
+  /* A value of nil for Vwindow_system normally means a tty, but we also use
+     it for the initial terminal since there is no window system there.  */
+  current_kboard->Vwindow_system = Qnil;
 
-  if (!noninteractive && !read_socket_hook && NILP (Vwindow_system))
+  if (!noninteractive)
     {
+      /* Before multi-tty support, these handlers used to be installed
+         only if the current session was a tty session.  Now an Emacs
+         session may have multiple display types, so we always handle
+         SIGINT.  There is special code in interrupt_signal to exit
+         Emacs on SIGINT when there are no termcap frames on the
+         controlling terminal. */
       signal (SIGINT, interrupt_signal);
 #if defined (HAVE_TERMIO) || defined (HAVE_TERMIOS)
       /* For systems with SysV TERMIO, C-g is set up for both SIGINT and
@@ -11106,11 +11557,6 @@ init_keyboard ()
   interrupt_input = 0;
 #endif
 
-/* Our VMS input only works by interrupts, as of now.  */
-#ifdef VMS
-  interrupt_input = 1;
-#endif
-
   sigfree ();
   dribble = 0;
 
@@ -11146,8 +11592,7 @@ struct event_head head_table[] = {
 void
 syms_of_keyboard ()
 {
-  Vpre_help_message = Qnil;
-  staticpro (&Vpre_help_message);
+  pending_funcalls = Qnil;
 
   Vlispy_mouse_stem = build_string ("mouse");
   staticpro (&Vlispy_mouse_stem);
@@ -11210,7 +11655,7 @@ syms_of_keyboard ()
   staticpro (&Qfunction_key);
   Qmouse_click = intern ("mouse-click");
   staticpro (&Qmouse_click);
-#if defined (WINDOWSNT) || defined (MAC_OS)
+#if defined (WINDOWSNT)
   Qlanguage_change = intern ("language-change");
   staticpro (&Qlanguage_change);
 #endif
@@ -11220,9 +11665,9 @@ syms_of_keyboard ()
   Qsave_session = intern ("save-session");
   staticpro (&Qsave_session);
 
-#ifdef MAC_OS
-  Qmac_apple_event = intern ("mac-apple-event");
-  staticpro (&Qmac_apple_event);
+#ifdef HAVE_DBUS
+  Qdbus_event = intern ("dbus-event");
+  staticpro (&Qdbus_event);
 #endif
 
   Qmenu_enable = intern ("menu-enable");
@@ -11257,7 +11702,7 @@ syms_of_keyboard ()
   Qmenu_bar = intern ("menu-bar");
   staticpro (&Qmenu_bar);
 
-#ifdef HAVE_MOUSE
+#if defined (HAVE_MOUSE) || defined (HAVE_GPM)
   Qmouse_fixup_help_message = intern ("mouse-fixup-help-message");
   staticpro (&Qmouse_fixup_help_message);
 #endif
@@ -11330,7 +11775,7 @@ syms_of_keyboard ()
   staticpro (&button_down_location);
   mouse_syms = Fmake_vector (make_number (1), Qnil);
   staticpro (&mouse_syms);
-  wheel_syms = Fmake_vector (make_number (2), Qnil);
+  wheel_syms = Fmake_vector (make_number (4), Qnil);
   staticpro (&wheel_syms);
 
   {
@@ -11385,11 +11830,12 @@ syms_of_keyboard ()
   staticpro (&help_form_saved_window_configs);
 
   defsubr (&Scurrent_idle_time);
+  defsubr (&Sevent_symbol_parse_modifiers);
   defsubr (&Sevent_convert_list);
   defsubr (&Sread_key_sequence);
   defsubr (&Sread_key_sequence_vector);
   defsubr (&Srecursive_edit);
-#ifdef HAVE_MOUSE
+#if defined (HAVE_MOUSE) || defined (HAVE_GPM)
   defsubr (&Strack_mouse);
 #endif
   defsubr (&Sinput_pending_p);
@@ -11408,6 +11854,10 @@ syms_of_keyboard ()
   defsubr (&Stop_level);
   defsubr (&Sdiscard_input);
   defsubr (&Sopen_dribble_file);
+  defsubr (&Sset_input_interrupt_mode);
+  defsubr (&Sset_output_flow_control);
+  defsubr (&Sset_input_meta_mode);
+  defsubr (&Sset_quit_char);
   defsubr (&Sset_input_mode);
   defsubr (&Scurrent_input_mode);
   defsubr (&Sexecute_extended_command);
@@ -11474,7 +11924,10 @@ In other words, the present command is the event that made the previous
 command exit.
 
 The value `kill-region' is special; it means that the previous command
-was a kill command.  */);
+was a kill command.
+
+`last-command' has a separate binding for each terminal device.
+See Info node `(elisp)Multiple displays'.  */);
 
   DEFVAR_KBOARD ("real-last-command", Vreal_last_command,
                 doc: /* Same as `last-command', but never altered by Lisp code.  */);
@@ -11490,6 +11943,14 @@ The command can set this variable; whatever is put here
 will be in `last-command' during the following command.  */);
   Vthis_command = Qnil;
 
+  DEFVAR_LISP ("this-command-keys-shift-translated",
+              &Vthis_command_keys_shift_translated,
+              doc: /* Non-nil if the key sequence activating this command was shift-translated.
+Shift-translation occurs when there is no binding for the key sequence
+as entered, but a binding was found by changing an upper-case letter
+to lower-case, or a shifted function key to an unshifted one.  */);
+  Vthis_command_keys_shift_translated = Qnil;
+
   DEFVAR_LISP ("this-original-command", &Vthis_original_command,
               doc: /* The command bound to the current key sequence before remapping.
 It equals `this-command' if the original command was not remapped through
@@ -11591,8 +12052,8 @@ for that character after that prefix key.  */);
 Useful to set before you dump a modified Emacs.  */);
   Vtop_level = Qnil;
 
-  DEFVAR_LISP ("keyboard-translate-table", &Vkeyboard_translate_table,
-              doc: /* Translate table for keyboard input, or nil.
+  DEFVAR_KBOARD ("keyboard-translate-table", Vkeyboard_translate_table,
+                 doc: /* Translate table for local keyboard input, or nil.
 If non-nil, the value should be a char-table.  Each character read
 from the keyboard is looked up in this char-table.  If the value found
 there is non-nil, then it is used instead of the actual input character.
@@ -11602,8 +12063,10 @@ If it is a string or vector of length N, character codes N and up are left
 untranslated.  In a vector, an element which is nil means "no translation".
 
 This is applied to the characters supplied to input methods, not their
-output.  See also `translation-table-for-input'.  */);
-  Vkeyboard_translate_table = Qnil;
+output.  See also `translation-table-for-input'.
+
+This variable has a separate binding for each terminal.  See Info node
+`(elisp)Multiple displays'.  */);
 
   DEFVAR_BOOL ("cannot-suspend", &cannot_suspend,
               doc: /* Non-nil means to always spawn a subshell instead of suspending.
@@ -11644,6 +12107,8 @@ The command loop sets this to nil before each command,
 and tests the value when the command returns.
 Buffer modification stores t in this variable.  */);
   Vdeactivate_mark = Qnil;
+  Qdeactivate_mark = intern ("deactivate-mark");
+  staticpro (&Qdeactivate_mark);
 
   DEFVAR_LISP ("command-hook-internal", &Vcommand_hook_internal,
               doc: /* Temporary storage of pre-command-hook or post-command-hook.  */);
@@ -11688,7 +12153,11 @@ buffer's local map, and the minor mode keymaps and text property keymaps.
 It also replaces `overriding-local-map'.
 
 This variable is intended to let commands such as `universal-argument'
-set up a different keymap for reading the next command.  */);
+set up a different keymap for reading the next command.
+
+`overriding-terminal-local-map' has a separate binding for each
+terminal device.
+See Info node `(elisp)Multiple displays'.  */);
 
   DEFVAR_LISP ("overriding-local-map", &Voverriding_local_map,
               doc: /* Keymap that overrides all other local keymaps.
@@ -11713,7 +12182,73 @@ and the minor mode maps regardless of `overriding-local-map'.  */);
                 doc: /* Alist of system-specific X windows key symbols.
 Each element should have the form (N . SYMBOL) where N is the
 numeric keysym code (sans the \"system-specific\" bit 1<<28)
-and SYMBOL is its name.  */);
+and SYMBOL is its name.
+
+`system-key-alist' has a separate binding for each terminal device.
+See Info node `(elisp)Multiple displays'.  */);
+
+  DEFVAR_KBOARD ("local-function-key-map", Vlocal_function_key_map,
+                 doc: /* Keymap that translates key sequences to key sequences during input.
+This is used mainly for mapping key sequences into some preferred
+key events (symbols).
+
+The `read-key-sequence' function replaces any subsequence bound by
+`local-function-key-map' with its binding.  More precisely, when the
+active keymaps have no binding for the current key sequence but
+`local-function-key-map' binds a suffix of the sequence to a vector or
+string, `read-key-sequence' replaces the matching suffix with its
+binding, and continues with the new sequence.
+
+If the binding is a function, it is called with one argument (the prompt)
+and its return value (a key sequence) is used.
+
+The events that come from bindings in `local-function-key-map' are not
+themselves looked up in `local-function-key-map'.
+
+For example, suppose `local-function-key-map' binds `ESC O P' to [f1].
+Typing `ESC O P' to `read-key-sequence' would return [f1].  Typing
+`C-x ESC O P' would return [?\\C-x f1].  If [f1] were a prefix key,
+typing `ESC O P x' would return [f1 x].
+
+`local-function-key-map' has a separate binding for each terminal
+device.  See Info node `(elisp)Multiple displays'.  If you need to
+define a binding on all terminals, change `function-key-map'
+instead.  Initially, `local-function-key-map' is an empty keymap that
+has `function-key-map' as its parent on all terminal devices.  */);
+
+  DEFVAR_KBOARD ("input-decode-map", Vinput_decode_map,
+                doc: /* Keymap that decodes input escape sequences.
+This is used mainly for mapping ASCII function key sequences into
+real Emacs function key events (symbols).
+
+The `read-key-sequence' function replaces any subsequence bound by
+`local-function-key-map' with its binding.  Contrary to `function-key-map',
+this map applies its rebinding regardless of the presence of an ordinary
+binding.  So it is more like `key-translation-map' except that it applies
+before `function-key-map' rather than after.
+
+If the binding is a function, it is called with one argument (the prompt)
+and its return value (a key sequence) is used.
+
+The events that come from bindings in `input-decode-map' are not
+themselves looked up in `input-decode-map'.
+
+This variable is keyboard-local.  */);
+
+  DEFVAR_LISP ("function-key-map", &Vfunction_key_map,
+               doc: /* The parent keymap of all `local-function-key-map' instances.
+Function key definitions that apply to all terminal devices should go
+here.  If a mapping is defined in both the current
+`local-function-key-map' binding and this variable, then the local
+definition will take precendence.  */);
+  Vfunction_key_map = Fmake_sparse_keymap (Qnil);
+
+  DEFVAR_LISP ("key-translation-map", &Vkey_translation_map,
+               doc: /* Keymap of key translations that can override keymaps.
+This keymap works like `function-key-map', but comes after that,
+and its non-prefix bindings override ordinary bindings.
+Another difference is that it is global rather than keyboard-local.  */);
+  Vkey_translation_map = Fmake_sparse_keymap (Qnil);
 
   DEFVAR_LISP ("deferred-action-list", &Vdeferred_action_list,
               doc: /* List of deferred actions to be performed at a later time.
@@ -11821,6 +12356,13 @@ and the Lisp function within which the error was signaled.  */);
 Help functions bind this to allow help on disabled menu items
 and tool-bar buttons.  */);
   Venable_disabled_menus_and_buttons = Qnil;
+
+  /* Create the initial keyboard. */
+  initial_kboard = (KBOARD *) xmalloc (sizeof (KBOARD));
+  init_kboard (initial_kboard);
+  /* Vwindow_system is left at t for now.  */
+  initial_kboard->next_kboard = all_kboards;
+  all_kboards = initial_kboard;
 }
 
 void
@@ -11865,6 +12407,13 @@ keys_of_keyboard ()
    *                       "handle-select-window"); */
   initial_define_lispy_key (Vspecial_event_map, "save-session",
                            "handle-save-session");
+
+#ifdef HAVE_DBUS
+  /* Define a special event which is raised for dbus callback
+     functions.  */
+  initial_define_lispy_key (Vspecial_event_map, "dbus-event",
+                           "dbus-handle-event");
+#endif
 }
 
 /* Mark the pointers in the kboard objects.
@@ -11882,6 +12431,7 @@ mark_kboards ()
       mark_object (kb->Voverriding_terminal_local_map);
       mark_object (kb->Vlast_command);
       mark_object (kb->Vreal_last_command);
+      mark_object (kb->Vkeyboard_translate_table);
       mark_object (kb->Vlast_repeatable_command);
       mark_object (kb->Vprefix_arg);
       mark_object (kb->Vlast_prefix_arg);
@@ -11890,6 +12440,9 @@ mark_kboards ()
       mark_object (kb->Vlast_kbd_macro);
       mark_object (kb->Vsystem_key_alist);
       mark_object (kb->system_key_syms);
+      mark_object (kb->Vwindow_system);
+      mark_object (kb->Vinput_decode_map);
+      mark_object (kb->Vlocal_function_key_map);
       mark_object (kb->Vdefault_minibuffer_frame);
       mark_object (kb->echo_string);
     }