1 /* Keyboard and mouse input; editor command loop.
    2    Copyright (C) 1985, 1986, 1987, 1988, 1989, 1993, 1994, 1995,
    3                  1996, 1997, 1999, 2000, 2001, 2002, 2003, 2004,
    4                  2005, 2006, 2007, 2008, 2009, 2010 Free Software Foundation, Inc.
    5 
    6 This file is part of GNU Emacs.
    7 
    8 GNU Emacs is free software: you can redistribute it and/or modify
    9 it under the terms of the GNU General Public License as published by
   10 the Free Software Foundation, either version 3 of the License, or
   11 (at your option) any later version.
   12 
   13 GNU Emacs is distributed in the hope that it will be useful,
   14 but WITHOUT ANY WARRANTY; without even the implied warranty of
   15 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
   16 GNU General Public License for more details.
   17 
   18 You should have received a copy of the GNU General Public License
   19 along with GNU Emacs.  If not, see <http://www.gnu.org/licenses/>.  */
   20 
   21 #include <config.h>
   22 #include <signal.h>
   23 #include <stdio.h>
   24 #include <setjmp.h>
   25 #include "lisp.h"
   26 #include "termchar.h"
   27 #include "termopts.h"
   28 #include "frame.h"
   29 #include "termhooks.h"
   30 #include "macros.h"
   31 #include "keyboard.h"
   32 #include "window.h"
   33 #include "commands.h"
   34 #include "buffer.h"
   35 #include "character.h"
   36 #include "disptab.h"
   37 #include "dispextern.h"
   38 #include "syntax.h"
   39 #include "intervals.h"
   40 #include "keymap.h"
   41 #include "blockinput.h"
   42 #include "puresize.h"
   43 #include "systime.h"
   44 #include "atimer.h"
   45 #include <setjmp.h>
   46 #include <errno.h>
   47 
   48 #ifdef HAVE_GTK_AND_PTHREAD
   49 #include <pthread.h>
   50 #endif
   51 #ifdef MSDOS
   52 #include "msdos.h"
   53 #include <time.h>
   54 #else /* not MSDOS */
   55 #include <sys/ioctl.h>
   56 #endif /* not MSDOS */
   57 
   58 #include "syssignal.h"
   59 
   60 #include <sys/types.h>
   61 #ifdef HAVE_UNISTD_H
   62 #include <unistd.h>
   63 #endif
   64 
   65 #ifdef HAVE_FCNTL_H
   66 #include <fcntl.h>
   67 #endif
   68 
   69 /* This is to get the definitions of the XK_ symbols.  */
   70 #ifdef HAVE_X_WINDOWS
   71 #include "xterm.h"
   72 #endif
   73 
   74 #ifdef HAVE_NTGUI
   75 #include "w32term.h"
   76 #endif /* HAVE_NTGUI */
   77 
   78 #ifdef HAVE_NS
   79 #include "nsterm.h"
   80 #endif
   81 
   82 /* Variables for blockinput.h: */
   83 
   84 /* Non-zero if interrupt input is blocked right now.  */
   85 volatile int interrupt_input_blocked;
   86 
   87 /* Nonzero means an input interrupt has arrived
   88    during the current critical section.  */
   89 int interrupt_input_pending;
   90 
   91 /* This var should be (interrupt_input_pending || pending_atimers).
   92    The QUIT macro checks this instead of interrupt_input_pending and
   93    pending_atimers separately, to reduce code size.  So, any code that
   94    changes interrupt_input_pending or pending_atimers should update
   95    this too.  */
   96 #ifdef SYNC_INPUT
   97 int pending_signals;
   98 #endif
   99 
  100 #define KBD_BUFFER_SIZE 4096
  101 
  102 KBOARD *initial_kboard;
  103 KBOARD *current_kboard;
  104 KBOARD *all_kboards;
  105 int single_kboard;
  106 
  107 /* Non-nil disable property on a command means
  108    do not execute it; call disabled-command-function's value instead.  */
  109 Lisp_Object Qdisabled, Qdisabled_command_function;
  110 
  111 #define NUM_RECENT_KEYS (300)
  112 int recent_keys_index;  /* Index for storing next element into recent_keys */
  113 int total_keys;         /* Total number of elements stored into recent_keys */
  114 Lisp_Object recent_keys; /* Vector holds the last NUM_RECENT_KEYS keystrokes */
  115 
  116 /* Vector holding the key sequence that invoked the current command.
  117    It is reused for each command, and it may be longer than the current
  118    sequence; this_command_key_count indicates how many elements
  119    actually mean something.
  120    It's easier to staticpro a single Lisp_Object than an array.  */
  121 Lisp_Object this_command_keys;
  122 int this_command_key_count;
  123 
  124 /* 1 after calling Freset_this_command_lengths.
  125    Usually it is 0.  */
  126 int this_command_key_count_reset;
  127 
  128 /* This vector is used as a buffer to record the events that were actually read
  129    by read_key_sequence.  */
  130 Lisp_Object raw_keybuf;
  131 int raw_keybuf_count;
  132 
  133 /* Non-nil if the present key sequence was obtained by shift translation.  */
  134 Lisp_Object Vthis_command_keys_shift_translated;
  135 
  136 #define GROW_RAW_KEYBUF                                                 \
  137  if (raw_keybuf_count == XVECTOR (raw_keybuf)->size)                    \
  138    raw_keybuf = larger_vector (raw_keybuf, raw_keybuf_count * 2, Qnil)  \
  139 
  140 /* Number of elements of this_command_keys
  141    that precede this key sequence.  */
  142 int this_single_command_key_start;
  143 
  144 /* Record values of this_command_key_count and echo_length ()
  145    before this command was read.  */
  146 static int before_command_key_count;
  147 static int before_command_echo_length;
  148 
  149 extern int minbuf_level;
  150 
  151 extern int message_enable_multibyte;
  152 
  153 /* If non-nil, the function that implements the display of help.
  154    It's called with one argument, the help string to display.  */
  155 
  156 Lisp_Object Vshow_help_function;
  157 
  158 /* Nonzero means do menu prompting.  */
  159 
  160 static int menu_prompting;
  161 
  162 /* Character to see next line of menu prompt.  */
  163 
  164 static Lisp_Object menu_prompt_more_char;
  165 
  166 /* For longjmp to where kbd input is being done.  */
  167 
  168 static jmp_buf getcjmp;
  169 
  170 /* True while doing kbd input.  */
  171 int waiting_for_input;
  172 
  173 /* True while displaying for echoing.   Delays C-g throwing.  */
  174 
  175 int echoing;
  176 
  177 /* Non-null means we can start echoing at the next input pause even
  178    though there is something in the echo area.  */
  179 
  180 static struct kboard *ok_to_echo_at_next_pause;
  181 
  182 /* The kboard last echoing, or null for none.  Reset to 0 in
  183    cancel_echoing.  If non-null, and a current echo area message
  184    exists, and echo_message_buffer is eq to the current message
  185    buffer, we know that the message comes from echo_kboard.  */
  186 
  187 struct kboard *echo_kboard;
  188 
  189 /* The buffer used for echoing.  Set in echo_now, reset in
  190    cancel_echoing.  */
  191 
  192 Lisp_Object echo_message_buffer;
  193 
  194 /* Nonzero means disregard local maps for the menu bar.  */
  195 static int inhibit_local_menu_bar_menus;
  196 
  197 /* Nonzero means C-g should cause immediate error-signal.  */
  198 int immediate_quit;
  199 
  200 /* The user's hook function for outputting an error message.  */
  201 Lisp_Object Vcommand_error_function;
  202 
  203 /* The user's ERASE setting.  */
  204 Lisp_Object Vtty_erase_char;
  205 
  206 /* Character to recognize as the help char.  */
  207 Lisp_Object Vhelp_char;
  208 
  209 /* List of other event types to recognize as meaning "help".  */
  210 Lisp_Object Vhelp_event_list;
  211 
  212 /* Form to execute when help char is typed.  */
  213 Lisp_Object Vhelp_form;
  214 
  215 /* Command to run when the help character follows a prefix key.  */
  216 Lisp_Object Vprefix_help_command;
  217 
  218 /* List of items that should move to the end of the menu bar.  */
  219 Lisp_Object Vmenu_bar_final_items;
  220 
  221 /* Non-nil means show the equivalent key-binding for
  222    any M-x command that has one.
  223    The value can be a length of time to show the message for.
  224    If the value is non-nil and not a number, we wait 2 seconds.  */
  225 Lisp_Object Vsuggest_key_bindings;
  226 
  227 /* How long to display an echo-area message when the minibuffer is active.
  228    If the value is not a number, such messages don't time out.  */
  229 Lisp_Object Vminibuffer_message_timeout;
  230 
  231 /* Character that causes a quit.  Normally C-g.
  232 
  233    If we are running on an ordinary terminal, this must be an ordinary
  234    ASCII char, since we want to make it our interrupt character.
  235 
  236    If we are not running on an ordinary terminal, it still needs to be
  237    an ordinary ASCII char.  This character needs to be recognized in
  238    the input interrupt handler.  At this point, the keystroke is
  239    represented as a struct input_event, while the desired quit
  240    character is specified as a lispy event.  The mapping from struct
  241    input_events to lispy events cannot run in an interrupt handler,
  242    and the reverse mapping is difficult for anything but ASCII
  243    keystrokes.
  244 
  245    FOR THESE ELABORATE AND UNSATISFYING REASONS, quit_char must be an
  246    ASCII character.  */
  247 int quit_char;
  248 
  249 extern Lisp_Object current_global_map;
  250 extern int minibuf_level;
  251 
  252 /* If non-nil, this is a map that overrides all other local maps.  */
  253 Lisp_Object Voverriding_local_map;
  254 
  255 /* If non-nil, Voverriding_local_map applies to the menu bar.  */
  256 Lisp_Object Voverriding_local_map_menu_flag;
  257 
  258 /* Keymap that defines special misc events that should
  259    be processed immediately at a low level.  */
  260 Lisp_Object Vspecial_event_map;
  261 
  262 /* Current depth in recursive edits.  */
  263 int command_loop_level;
  264 
  265 /* Total number of times command_loop has read a key sequence.  */
  266 EMACS_INT num_input_keys;
  267 
  268 /* Last input event read as a command.  */
  269 Lisp_Object last_command_event;
  270 
  271 /* Last input character read as a command, not counting menus
  272    reached by the mouse.  */
  273 Lisp_Object last_nonmenu_event;
  274 
  275 /* Last input event read for any purpose.  */
  276 Lisp_Object last_input_event;
  277 
  278 /* If not Qnil, a list of objects to be read as subsequent command input.  */
  279 Lisp_Object Vunread_command_events;
  280 
  281 /* If not Qnil, a list of objects to be read as subsequent command input
  282    including input method processing.  */
  283 Lisp_Object Vunread_input_method_events;
  284 
  285 /* If not Qnil, a list of objects to be read as subsequent command input
  286    but NOT including input method processing.  */
  287 Lisp_Object Vunread_post_input_method_events;
  288 
  289 /* If not -1, an event to be read as subsequent command input.  */
  290 EMACS_INT unread_command_char;
  291 
  292 /* If not Qnil, this is a switch-frame event which we decided to put
  293    off until the end of a key sequence.  This should be read as the
  294    next command input, after any unread_command_events.
  295 
  296    read_key_sequence uses this to delay switch-frame events until the
  297    end of the key sequence; Fread_char uses it to put off switch-frame
  298    events until a non-ASCII event is acceptable as input.  */
  299 Lisp_Object unread_switch_frame;
  300 
  301 /* A mask of extra modifier bits to put into every keyboard char.  */
  302 EMACS_INT extra_keyboard_modifiers;
  303 
  304 /* Char to use as prefix when a meta character is typed in.
  305    This is bound on entry to minibuffer in case ESC is changed there.  */
  306 
  307 Lisp_Object meta_prefix_char;
  308 
  309 /* Last size recorded for a current buffer which is not a minibuffer.  */
  310 static int last_non_minibuf_size;
  311 
  312 /* Number of idle seconds before an auto-save and garbage collection.  */
  313 static Lisp_Object Vauto_save_timeout;
  314 
  315 /* Total number of times read_char has returned.  */
  316 int num_input_events;
  317 
  318 /* Total number of times read_char has returned, outside of macros.  */
  319 EMACS_INT num_nonmacro_input_events;
  320 
  321 /* Auto-save automatically when this many characters have been typed
  322    since the last time.  */
  323 
  324 static EMACS_INT auto_save_interval;
  325 
  326 /* Value of num_nonmacro_input_events as of last auto save.  */
  327 
  328 int last_auto_save;
  329 
  330 /* The command being executed by the command loop.
  331    Commands may set this, and the value set will be copied into
  332    current_kboard->Vlast_command instead of the actual command.  */
  333 Lisp_Object Vthis_command;
  334 
  335 /* This is like Vthis_command, except that commands never set it.  */
  336 Lisp_Object real_this_command;
  337 
  338 /* If the lookup of the command returns a binding, the original
  339    command is stored in this-original-command.  It is nil otherwise.  */
  340 Lisp_Object Vthis_original_command;
  341 
  342 /* The value of point when the last command was started.  */
  343 int last_point_position;
  344 
  345 /* The buffer that was current when the last command was started.  */
  346 Lisp_Object last_point_position_buffer;
  347 
  348 /* The window that was selected when the last command was started.  */
  349 Lisp_Object last_point_position_window;
  350 
  351 /* The frame in which the last input event occurred, or Qmacro if the
  352    last event came from a macro.  We use this to determine when to
  353    generate switch-frame events.  This may be cleared by functions
  354    like Fselect_frame, to make sure that a switch-frame event is
  355    generated by the next character.  */
  356 Lisp_Object internal_last_event_frame;
  357 
  358 /* A user-visible version of the above, intended to allow users to
  359    figure out where the last event came from, if the event doesn't
  360    carry that information itself (i.e. if it was a character).  */
  361 Lisp_Object Vlast_event_frame;
  362 
  363 /* The timestamp of the last input event we received from the X server.
  364    X Windows wants this for selection ownership.  */
  365 unsigned long last_event_timestamp;
  366 
  367 Lisp_Object Qself_insert_command;
  368 Lisp_Object Qforward_char;
  369 Lisp_Object Qbackward_char;
  370 Lisp_Object Qundefined;
  371 Lisp_Object Qtimer_event_handler;
  372 
  373 /* read_key_sequence stores here the command definition of the
  374    key sequence that it reads.  */
  375 Lisp_Object read_key_sequence_cmd;
  376 
  377 /* Echo unfinished commands after this many seconds of pause.  */
  378 Lisp_Object Vecho_keystrokes;
  379 
  380 /* Form to evaluate (if non-nil) when Emacs is started.  */
  381 Lisp_Object Vtop_level;
  382 
  383 /* If non-nil, this implements the current input method.  */
  384 Lisp_Object Vinput_method_function;
  385 Lisp_Object Qinput_method_function;
  386 
  387 /* When we call Vinput_method_function,
  388    this holds the echo area message that was just erased.  */
  389 Lisp_Object Vinput_method_previous_message;
  390 
  391 /* Non-nil means deactivate the mark at end of this command.  */
  392 Lisp_Object Vdeactivate_mark;
  393 Lisp_Object Qdeactivate_mark;
  394 
  395 /* Menu bar specified in Lucid Emacs fashion.  */
  396 
  397 Lisp_Object Vlucid_menu_bar_dirty_flag;
  398 Lisp_Object Qrecompute_lucid_menubar, Qactivate_menubar_hook;
  399 
  400 Lisp_Object Qecho_area_clear_hook;
  401 
  402 /* Hooks to run before and after each command.  */
  403 Lisp_Object Qpre_command_hook, Vpre_command_hook;
  404 Lisp_Object Qpost_command_hook, Vpost_command_hook;
  405 Lisp_Object Qcommand_hook_internal, Vcommand_hook_internal;
  406 
  407 /* Parent keymap of terminal-local function-key-map instances.  */
  408 Lisp_Object Vfunction_key_map;
  409 
  410 /* Keymap of key translations that can override keymaps.  */
  411 Lisp_Object Vkey_translation_map;
  412 
  413 /* List of deferred actions to be performed at a later time.
  414    The precise format isn't relevant here; we just check whether it is nil.  */
  415 Lisp_Object Vdeferred_action_list;
  416 
  417 /* Function to call to handle deferred actions, when there are any.  */
  418 Lisp_Object Vdeferred_action_function;
  419 Lisp_Object Qdeferred_action_function;
  420 
  421 Lisp_Object Qinput_method_exit_on_first_char;
  422 Lisp_Object Qinput_method_use_echo_area;
  423 
  424 /* File in which we write all commands we read.  */
  425 FILE *dribble;
  426 
  427 /* Nonzero if input is available.  */
  428 int input_pending;
  429 
  430 extern char *pending_malloc_warning;
  431 
  432 /* Circular buffer for pre-read keyboard input.  */
  433 
  434 static struct input_event kbd_buffer[KBD_BUFFER_SIZE];
  435 
  436 /* Pointer to next available character in kbd_buffer.
  437    If kbd_fetch_ptr == kbd_store_ptr, the buffer is empty.
  438    This may be kbd_buffer + KBD_BUFFER_SIZE, meaning that the
  439    next available char is in kbd_buffer[0].  */
  440 static struct input_event *kbd_fetch_ptr;
  441 
  442 /* Pointer to next place to store character in kbd_buffer.  This
  443    may be kbd_buffer + KBD_BUFFER_SIZE, meaning that the next
  444    character should go in kbd_buffer[0].  */
  445 static struct input_event * volatile kbd_store_ptr;
  446 
  447 /* The above pair of variables forms a "queue empty" flag.  When we
  448    enqueue a non-hook event, we increment kbd_store_ptr.  When we
  449    dequeue a non-hook event, we increment kbd_fetch_ptr.  We say that
  450    there is input available if the two pointers are not equal.
  451 
  452    Why not just have a flag set and cleared by the enqueuing and
  453    dequeuing functions?  Such a flag could be screwed up by interrupts
  454    at inopportune times.  */
  455 
  456 /* If this flag is non-nil, we check mouse_moved to see when the
  457    mouse moves, and motion events will appear in the input stream.
  458    Otherwise, mouse motion is ignored.  */
  459 Lisp_Object do_mouse_tracking;
  460 
  461 /* Symbols to head events.  */
  462 Lisp_Object Qmouse_movement;
  463 Lisp_Object Qscroll_bar_movement;
  464 Lisp_Object Qswitch_frame;
  465 Lisp_Object Qdelete_frame;
  466 Lisp_Object Qiconify_frame;
  467 Lisp_Object Qmake_frame_visible;
  468 Lisp_Object Qselect_window;
  469 Lisp_Object Qhelp_echo;
  470 
  471 extern Lisp_Object Qremap;
  472 
  473 #if defined (HAVE_MOUSE) || defined (HAVE_GPM)
  474 Lisp_Object Qmouse_fixup_help_message;
  475 #endif
  476 
  477 /* Symbols to denote kinds of events.  */
  478 Lisp_Object Qfunction_key;
  479 Lisp_Object Qmouse_click;
  480 #if defined (WINDOWSNT)
  481 Lisp_Object Qlanguage_change;
  482 #endif
  483 Lisp_Object Qdrag_n_drop;
  484 Lisp_Object Qsave_session;
  485 #ifdef HAVE_DBUS
  486 Lisp_Object Qdbus_event;
  487 #endif
  488 Lisp_Object Qconfig_changed_event;
  489 
  490 /* Lisp_Object Qmouse_movement; - also an event header */
  491 
  492 /* Properties of event headers.  */
  493 Lisp_Object Qevent_kind;
  494 Lisp_Object Qevent_symbol_elements;
  495 
  496 /* menu item parts */
  497 Lisp_Object Qmenu_enable;
  498 Lisp_Object QCenable, QCvisible, QChelp, QCfilter, QCkeys, QCkey_sequence;
  499 Lisp_Object QCbutton, QCtoggle, QCradio, QClabel;
  500 extern Lisp_Object Qmenu_item;
  501 
  502 /* An event header symbol HEAD may have a property named
  503    Qevent_symbol_element_mask, which is of the form (BASE MODIFIERS);
  504    BASE is the base, unmodified version of HEAD, and MODIFIERS is the
  505    mask of modifiers applied to it.  If present, this is used to help
  506    speed up parse_modifiers.  */
  507 Lisp_Object Qevent_symbol_element_mask;
  508 
  509 /* An unmodified event header BASE may have a property named
  510    Qmodifier_cache, which is an alist mapping modifier masks onto
  511    modified versions of BASE.  If present, this helps speed up
  512    apply_modifiers.  */
  513 Lisp_Object Qmodifier_cache;
  514 
  515 /* Symbols to use for parts of windows.  */
  516 Lisp_Object Qmode_line;
  517 Lisp_Object Qvertical_line;
  518 Lisp_Object Qvertical_scroll_bar;
  519 Lisp_Object Qmenu_bar;
  520 extern Lisp_Object Qleft_margin, Qright_margin;
  521 extern Lisp_Object Qleft_fringe, Qright_fringe;
  522 extern Lisp_Object QCmap;
  523 
  524 Lisp_Object recursive_edit_unwind (), command_loop ();
  525 Lisp_Object Fthis_command_keys ();
  526 Lisp_Object Qextended_command_history;
  527 EMACS_TIME timer_check ();
  528 
  529 extern Lisp_Object Vhistory_length, Vtranslation_table_for_input;
  530 
  531 extern char *x_get_keysym_name ();
  532 
  533 static void record_menu_key ();
  534 static int echo_length ();
  535 
  536 Lisp_Object Qpolling_period;
  537 
  538 /* List of absolute timers.  Appears in order of next scheduled event.  */
  539 Lisp_Object Vtimer_list;
  540 
  541 /* List of idle time timers.  Appears in order of next scheduled event.  */
  542 Lisp_Object Vtimer_idle_list;
  543 
  544 /* Incremented whenever a timer is run.  */
  545 int timers_run;
  546 
  547 extern Lisp_Object Vprint_level, Vprint_length;
  548 
  549 /* Address (if not 0) of EMACS_TIME to zero out if a SIGIO interrupt
  550    happens.  */
  551 EMACS_TIME *input_available_clear_time;
  552 
  553 /* Nonzero means use SIGIO interrupts; zero means use CBREAK mode.
  554    Default is 1 if INTERRUPT_INPUT is defined.  */
  555 int interrupt_input;
  556 
  557 /* Nonzero while interrupts are temporarily deferred during redisplay.  */
  558 int interrupts_deferred;
  559 
  560 /* Allow m- file to inhibit use of FIONREAD.  */
  561 #ifdef BROKEN_FIONREAD
  562 #undef FIONREAD
  563 #endif
  564 
  565 /* We are unable to use interrupts if FIONREAD is not available,
  566    so flush SIGIO so we won't try.  */
  567 #if !defined (FIONREAD)
  568 #ifdef SIGIO
  569 #undef SIGIO
  570 #endif
  571 #endif
  572 
  573 /* If we support a window system, turn on the code to poll periodically
  574    to detect C-g.  It isn't actually used when doing interrupt input.  */
  575 #if defined(HAVE_WINDOW_SYSTEM) && !defined(USE_ASYNC_EVENTS)
  576 #define POLL_FOR_INPUT
  577 #endif
  578 
  579 /* After a command is executed, if point is moved into a region that
  580    has specific properties (e.g. composition, display), we adjust
  581    point to the boundary of the region.  But, if a command sets this
  582    variable to non-nil, we suppress this point adjustment.  This
  583    variable is set to nil before reading a command.  */
  584 
  585 Lisp_Object Vdisable_point_adjustment;
  586 
  587 /* If non-nil, always disable point adjustment.  */
  588 
  589 Lisp_Object Vglobal_disable_point_adjustment;
  590 
  591 /* The time when Emacs started being idle.  */
  592 
  593 static EMACS_TIME timer_idleness_start_time;
  594 
  595 /* After Emacs stops being idle, this saves the last value
  596    of timer_idleness_start_time from when it was idle.  */
  597 
  598 static EMACS_TIME timer_last_idleness_start_time;
  599 
  600 /* If non-nil, events produced by disabled menu items and tool-bar
  601    buttons are not ignored.  Help functions bind this to allow help on
  602    those items and buttons.  */
  603 Lisp_Object Venable_disabled_menus_and_buttons;
  604 
  605 
  606 /* Global variable declarations.  */
  607 
  608 /* Flags for readable_events.  */
  609 #define READABLE_EVENTS_DO_TIMERS_NOW           (1 << 0)
  610 #define READABLE_EVENTS_FILTER_EVENTS           (1 << 1)
  611 #define READABLE_EVENTS_IGNORE_SQUEEZABLES      (1 << 2)
  612 
  613 /* Function for init_keyboard to call with no args (if nonzero).  */
  614 void (*keyboard_init_hook) ();
  615 
  616 static int read_avail_input P_ ((int));
  617 static void get_input_pending P_ ((int *, int));
  618 static int readable_events P_ ((int));
  619 static Lisp_Object read_char_x_menu_prompt P_ ((int, Lisp_Object *,
  620                                                 Lisp_Object, int *));
  621 static Lisp_Object read_char_x_menu_prompt ();
  622 static Lisp_Object read_char_minibuf_menu_prompt P_ ((int, int,
  623                                                       Lisp_Object *));
  624 static Lisp_Object make_lispy_event P_ ((struct input_event *));
  625 #if defined (HAVE_MOUSE) || defined (HAVE_GPM)
  626 static Lisp_Object make_lispy_movement P_ ((struct frame *, Lisp_Object,
  627                                             enum scroll_bar_part,
  628                                             Lisp_Object, Lisp_Object,
  629                                             unsigned long));
  630 #endif
  631 static Lisp_Object modify_event_symbol P_ ((int, unsigned, Lisp_Object,
  632                                             Lisp_Object, char **,
  633                                             Lisp_Object *, unsigned));
  634 static Lisp_Object make_lispy_switch_frame P_ ((Lisp_Object));
  635 static void save_getcjmp P_ ((jmp_buf));
  636 static void save_getcjmp ();
  637 static void restore_getcjmp P_ ((jmp_buf));
  638 static Lisp_Object apply_modifiers P_ ((int, Lisp_Object));
  639 static void clear_event P_ ((struct input_event *));
  640 static Lisp_Object restore_kboard_configuration P_ ((Lisp_Object));
  641 static SIGTYPE interrupt_signal P_ ((int signalnum));
  642 static void handle_interrupt P_ ((void));
  643 static void timer_start_idle P_ ((void));
  644 static void timer_stop_idle P_ ((void));
  645 static void timer_resume_idle P_ ((void));
  646 static SIGTYPE handle_user_signal P_ ((int));
  647 static char *find_user_signal_name P_ ((int));
  648 static int store_user_signal_events P_ ((void));
  649 
  650 /* Nonzero means don't try to suspend even if the operating system seems
  651    to support it.  */
  652 static int cannot_suspend;
  653 
  654 extern Lisp_Object Qidentity, Qonly;
  655 
  656 /* Install the string STR as the beginning of the string of echoing,
  657    so that it serves as a prompt for the next character.
  658    Also start echoing.  */
  659 
  660 void
  661 echo_prompt (str)
  662      Lisp_Object str;
  663 {
  664   current_kboard->echo_string = str;
  665   current_kboard->echo_after_prompt = SCHARS (str);
  666   echo_now ();
  667 }
  668 
  669 /* Add C to the echo string, if echoing is going on.
  670    C can be a character, which is printed prettily ("M-C-x" and all that
  671    jazz), or a symbol, whose name is printed.  */
  672 
  673 void
  674 echo_char (c)
  675      Lisp_Object c;
  676 {
  677   if (current_kboard->immediate_echo)
  678     {
  679       int size = KEY_DESCRIPTION_SIZE + 100;
  680       char *buffer = (char *) alloca (size);
  681       char *ptr = buffer;
  682       Lisp_Object echo_string;
  683 
  684       echo_string = current_kboard->echo_string;
  685 
  686       /* If someone has passed us a composite event, use its head symbol.  */
  687       c = EVENT_HEAD (c);
  688 
  689       if (INTEGERP (c))
  690         {
  691           ptr = push_key_description (XINT (c), ptr, 1);
  692         }
  693       else if (SYMBOLP (c))
  694         {
  695           Lisp_Object name = SYMBOL_NAME (c);
  696           int nbytes = SBYTES (name);
  697 
  698           if (size - (ptr - buffer) < nbytes)
  699             {
  700               int offset = ptr - buffer;
  701               size = max (2 * size, size + nbytes);
  702               buffer = (char *) alloca (size);
  703               ptr = buffer + offset;
  704             }
  705 
  706           ptr += copy_text (SDATA (name), ptr, nbytes,
  707                             STRING_MULTIBYTE (name), 1);
  708         }
  709 
  710       if ((NILP (echo_string) || SCHARS (echo_string) == 0)
  711           && help_char_p (c))
  712         {
  713           const char *text = " (Type ? for further options)";
  714           int len = strlen (text);
  715 
  716           if (size - (ptr - buffer) < len)
  717             {
  718               int offset = ptr - buffer;
  719               size += len;
  720               buffer = (char *) alloca (size);
  721               ptr = buffer + offset;
  722             }
  723 
  724           bcopy (text, ptr, len);
  725           ptr += len;
  726         }
  727 
  728       /* Replace a dash from echo_dash with a space, otherwise
  729          add a space at the end as a separator between keys.  */
  730       if (STRINGP (echo_string)
  731           && SCHARS (echo_string) > 1)
  732         {
  733           Lisp_Object last_char, prev_char, idx;
  734 
  735           idx = make_number (SCHARS (echo_string) - 2);
  736           prev_char = Faref (echo_string, idx);
  737 
  738           idx = make_number (SCHARS (echo_string) - 1);
  739           last_char = Faref (echo_string, idx);
  740 
  741           /* We test PREV_CHAR to make sure this isn't the echoing
  742              of a minus-sign.  */
  743           if (XINT (last_char) == '-' && XINT (prev_char) != ' ')
  744             Faset (echo_string, idx, make_number (' '));
  745           else
  746             echo_string = concat2 (echo_string, build_string (" "));
  747         }
  748       else if (STRINGP (echo_string))
  749         echo_string = concat2 (echo_string, build_string (" "));
  750 
  751       current_kboard->echo_string
  752         = concat2 (echo_string, make_string (buffer, ptr - buffer));
  753 
  754       echo_now ();
  755     }
  756 }
  757 
  758 /* Temporarily add a dash to the end of the echo string if it's not
  759    empty, so that it serves as a mini-prompt for the very next character.  */
  760 
  761 void
  762 echo_dash ()
  763 {
  764   /* Do nothing if not echoing at all.  */
  765   if (NILP (current_kboard->echo_string))
  766     return;
  767 
  768   if (!current_kboard->immediate_echo
  769       && SCHARS (current_kboard->echo_string) == 0)
  770     return;
  771 
  772   /* Do nothing if we just printed a prompt.  */
  773   if (current_kboard->echo_after_prompt
  774       == SCHARS (current_kboard->echo_string))
  775     return;
  776 
  777   /* Do nothing if we have already put a dash at the end.  */
  778   if (SCHARS (current_kboard->echo_string) > 1)
  779     {
  780       Lisp_Object last_char, prev_char, idx;
  781 
  782       idx = make_number (SCHARS (current_kboard->echo_string) - 2);
  783       prev_char = Faref (current_kboard->echo_string, idx);
  784 
  785       idx = make_number (SCHARS (current_kboard->echo_string) - 1);
  786       last_char = Faref (current_kboard->echo_string, idx);
  787 
  788       if (XINT (last_char) == '-' && XINT (prev_char) != ' ')
  789         return;
  790     }
  791 
  792   /* Put a dash at the end of the buffer temporarily,
  793      but make it go away when the next character is added.  */
  794   current_kboard->echo_string = concat2 (current_kboard->echo_string,
  795                                          build_string ("-"));
  796   echo_now ();
  797 }
  798 
  799 /* Display the current echo string, and begin echoing if not already
  800    doing so.  */
  801 
  802 void
  803 echo_now ()
  804 {
  805   if (!current_kboard->immediate_echo)
  806     {
  807       int i;
  808       current_kboard->immediate_echo = 1;
  809 
  810       for (i = 0; i < this_command_key_count; i++)
  811         {
  812           Lisp_Object c;
  813 
  814           /* Set before_command_echo_length to the value that would
  815              have been saved before the start of this subcommand in
  816              command_loop_1, if we had already been echoing then.  */
  817           if (i == this_single_command_key_start)
  818             before_command_echo_length = echo_length ();
  819 
  820           c = XVECTOR (this_command_keys)->contents[i];
  821           if (! (EVENT_HAS_PARAMETERS (c)
  822                  && EQ (EVENT_HEAD_KIND (EVENT_HEAD (c)), Qmouse_movement)))
  823             echo_char (c);
  824         }
  825 
  826       /* Set before_command_echo_length to the value that would
  827          have been saved before the start of this subcommand in
  828          command_loop_1, if we had already been echoing then.  */
  829       if (this_command_key_count == this_single_command_key_start)
  830         before_command_echo_length = echo_length ();
  831 
  832       /* Put a dash at the end to invite the user to type more.  */
  833       echo_dash ();
  834     }
  835 
  836   echoing = 1;
  837   message3_nolog (current_kboard->echo_string,
  838                   SBYTES (current_kboard->echo_string),
  839                   STRING_MULTIBYTE (current_kboard->echo_string));
  840   echoing = 0;
  841 
  842   /* Record in what buffer we echoed, and from which kboard.  */
  843   echo_message_buffer = echo_area_buffer[0];
  844   echo_kboard = current_kboard;
  845 
  846   if (waiting_for_input && !NILP (Vquit_flag))
  847     quit_throw_to_read_char ();
  848 }
  849 
  850 /* Turn off echoing, for the start of a new command.  */
  851 
  852 void
  853 cancel_echoing ()
  854 {
  855   current_kboard->immediate_echo = 0;
  856   current_kboard->echo_after_prompt = -1;
  857   current_kboard->echo_string = Qnil;
  858   ok_to_echo_at_next_pause = NULL;
  859   echo_kboard = NULL;
  860   echo_message_buffer = Qnil;
  861 }
  862 
  863 /* Return the length of the current echo string.  */
  864 
  865 static int
  866 echo_length ()
  867 {
  868   return (STRINGP (current_kboard->echo_string)
  869           ? SCHARS (current_kboard->echo_string)
  870           : 0);
  871 }
  872 
  873 /* Truncate the current echo message to its first LEN chars.
  874    This and echo_char get used by read_key_sequence when the user
  875    switches frames while entering a key sequence.  */
  876 
  877 static void
  878 echo_truncate (nchars)
  879      int nchars;
  880 {
  881   if (STRINGP (current_kboard->echo_string))
  882     current_kboard->echo_string
  883       = Fsubstring (current_kboard->echo_string,
  884                     make_number (0), make_number (nchars));
  885   truncate_echo_area (nchars);
  886 }
  887 
  888 
  889 /* Functions for manipulating this_command_keys.  */
  890 static void
  891 add_command_key (key)
  892      Lisp_Object key;
  893 {
  894 #if 0 /* Not needed after we made Freset_this_command_lengths
  895          do the job immediately.  */
  896   /* If reset-this-command-length was called recently, obey it now.
  897      See the doc string of that function for an explanation of why.  */
  898   if (before_command_restore_flag)
  899     {
  900       this_command_key_count = before_command_key_count_1;
  901       if (this_command_key_count < this_single_command_key_start)
  902         this_single_command_key_start = this_command_key_count;
  903       echo_truncate (before_command_echo_length_1);
  904       before_command_restore_flag = 0;
  905     }
  906 #endif
  907 
  908   if (this_command_key_count >= ASIZE (this_command_keys))
  909     this_command_keys = larger_vector (this_command_keys,
  910                                        2 * ASIZE (this_command_keys),
  911                                        Qnil);
  912 
  913   ASET (this_command_keys, this_command_key_count, key);
  914   ++this_command_key_count;
  915 }
  916 
  917 
  918 Lisp_Object
  919 recursive_edit_1 ()
  920 {
  921   int count = SPECPDL_INDEX ();
  922   Lisp_Object val;
  923 
  924   if (command_loop_level > 0)
  925     {
  926       specbind (Qstandard_output, Qt);
  927       specbind (Qstandard_input, Qt);
  928     }
  929 
  930 #ifdef HAVE_WINDOW_SYSTEM
  931   /* The command loop has started an hourglass timer, so we have to
  932      cancel it here, otherwise it will fire because the recursive edit
  933      can take some time.  Do not check for display_hourglass_p here,
  934      because it could already be nil.  */
  935     cancel_hourglass ();
  936 #endif
  937 
  938   /* This function may have been called from a debugger called from
  939      within redisplay, for instance by Edebugging a function called
  940      from fontification-functions.  We want to allow redisplay in
  941      the debugging session.
  942 
  943      The recursive edit is left with a `(throw exit ...)'.  The `exit'
  944      tag is not caught anywhere in redisplay, i.e. when we leave the
  945      recursive edit, the original redisplay leading to the recursive
  946      edit will be unwound.  The outcome should therefore be safe.  */
  947   specbind (Qinhibit_redisplay, Qnil);
  948   redisplaying_p = 0;
  949 
  950   val = command_loop ();
  951   if (EQ (val, Qt))
  952     Fsignal (Qquit, Qnil);
  953   /* Handle throw from read_minibuf when using minibuffer
  954      while it's active but we're in another window.  */
  955   if (STRINGP (val))
  956     xsignal1 (Qerror, val);
  957 
  958   return unbind_to (count, Qnil);
  959 }
  960 
  961 /* When an auto-save happens, record the "time", and don't do again soon.  */
  962 
  963 void
  964 record_auto_save ()
  965 {
  966   last_auto_save = num_nonmacro_input_events;
  967 }
  968 
  969 /* Make an auto save happen as soon as possible at command level.  */
  970 
  971 void
  972 force_auto_save_soon ()
  973 {
  974   last_auto_save = - auto_save_interval - 1;
  975 
  976   record_asynch_buffer_change ();
  977 }
  978 
  979 DEFUN ("recursive-edit", Frecursive_edit, Srecursive_edit, 0, 0, "",
  980        doc: /* Invoke the editor command loop recursively.
  981 To get out of the recursive edit, a command can do `(throw 'exit nil)';
  982 that tells this function to return.
  983 Alternatively, `(throw 'exit t)' makes this function signal an error.
  984 This function is called by the editor initialization to begin editing.  */)
  985      ()
  986 {
  987   int count = SPECPDL_INDEX ();
  988   Lisp_Object buffer;
  989 
  990   /* If we enter while input is blocked, don't lock up here.
  991      This may happen through the debugger during redisplay.  */
  992   if (INPUT_BLOCKED_P)
  993     return Qnil;
  994 
  995   command_loop_level++;
  996   update_mode_lines = 1;
  997 
  998   if (command_loop_level
  999       && current_buffer != XBUFFER (XWINDOW (selected_window)->buffer))
 1000     buffer = Fcurrent_buffer ();
 1001   else
 1002     buffer = Qnil;
 1003 
 1004   /* If we leave recursive_edit_1 below with a `throw' for instance,
 1005      like it is done in the splash screen display, we have to
 1006      make sure that we restore single_kboard as command_loop_1
 1007      would have done if it were left normally.  */
 1008   if (command_loop_level > 0)
 1009     temporarily_switch_to_single_kboard (SELECTED_FRAME ());
 1010   record_unwind_protect (recursive_edit_unwind, buffer);
 1011 
 1012   recursive_edit_1 ();
 1013   return unbind_to (count, Qnil);
 1014 }
 1015 
 1016 Lisp_Object
 1017 recursive_edit_unwind (buffer)
 1018      Lisp_Object buffer;
 1019 {
 1020   if (BUFFERP (buffer))
 1021     Fset_buffer (buffer);
 1022 
 1023   command_loop_level--;
 1024   update_mode_lines = 1;
 1025   return Qnil;
 1026 }
 1027 
 1028 
 1029 #if 0  /* These two functions are now replaced with
 1030           temporarily_switch_to_single_kboard. */
 1031 static void
 1032 any_kboard_state ()
 1033 {
 1034 #if 0 /* Theory: if there's anything in Vunread_command_events,
 1035          it will right away be read by read_key_sequence,
 1036          and then if we do switch KBOARDS, it will go into the side
 1037          queue then.  So we don't need to do anything special here -- rms.  */
 1038   if (CONSP (Vunread_command_events))
 1039     {
 1040       current_kboard->kbd_queue
 1041         = nconc2 (Vunread_command_events, current_kboard->kbd_queue);
 1042       current_kboard->kbd_queue_has_data = 1;
 1043     }
 1044   Vunread_command_events = Qnil;
 1045 #endif
 1046   single_kboard = 0;
 1047 }
 1048 
 1049 /* Switch to the single-kboard state, making current_kboard
 1050    the only KBOARD from which further input is accepted.  */
 1051 
 1052 void
 1053 single_kboard_state ()
 1054 {
 1055   single_kboard = 1;
 1056 }
 1057 #endif
 1058 
 1059 /* If we're in single_kboard state for kboard KBOARD,
 1060    get out of it.  */
 1061 
 1062 void
 1063 not_single_kboard_state (kboard)
 1064      KBOARD *kboard;
 1065 {
 1066   if (kboard == current_kboard)
 1067     single_kboard = 0;
 1068 }
 1069 
 1070 /* Maintain a stack of kboards, so other parts of Emacs
 1071    can switch temporarily to the kboard of a given frame
 1072    and then revert to the previous status.  */
 1073 
 1074 struct kboard_stack
 1075 {
 1076   KBOARD *kboard;
 1077   struct kboard_stack *next;
 1078 };
 1079 
 1080 static struct kboard_stack *kboard_stack;
 1081 
 1082 void
 1083 push_kboard (k)
 1084      struct kboard *k;
 1085 {
 1086   struct kboard_stack *p
 1087     = (struct kboard_stack *) xmalloc (sizeof (struct kboard_stack));
 1088 
 1089   p->next = kboard_stack;
 1090   p->kboard = current_kboard;
 1091   kboard_stack = p;
 1092 
 1093   current_kboard = k;
 1094 }
 1095 
 1096 void
 1097 pop_kboard ()
 1098 {
 1099   struct terminal *t;
 1100   struct kboard_stack *p = kboard_stack;
 1101   int found = 0;
 1102   for (t = terminal_list; t; t = t->next_terminal)
 1103     {
 1104       if (t->kboard == p->kboard)
 1105         {
 1106           current_kboard = p->kboard;
 1107           found = 1;
 1108           break;
 1109         }
 1110     }
 1111   if (!found)
 1112     {
 1113       /* The terminal we remembered has been deleted.  */
 1114       current_kboard = FRAME_KBOARD (SELECTED_FRAME ());
 1115       single_kboard = 0;
 1116     }
 1117   kboard_stack = p->next;
 1118   xfree (p);
 1119 }
 1120 
 1121 /* Switch to single_kboard mode, making current_kboard the only KBOARD
 1122   from which further input is accepted.  If F is non-nil, set its
 1123   KBOARD as the current keyboard.
 1124 
 1125   This function uses record_unwind_protect to return to the previous
 1126   state later.
 1127 
 1128   If Emacs is already in single_kboard mode, and F's keyboard is
 1129   locked, then this function will throw an errow.  */
 1130 
 1131 void
 1132 temporarily_switch_to_single_kboard (f)
 1133      struct frame *f;
 1134 {
 1135   int was_locked = single_kboard;
 1136   if (was_locked)
 1137     {
 1138       if (f != NULL && FRAME_KBOARD (f) != current_kboard)
 1139         /* We can not switch keyboards while in single_kboard mode.
 1140            In rare cases, Lisp code may call `recursive-edit' (or
 1141            `read-minibuffer' or `y-or-n-p') after it switched to a
 1142            locked frame.  For example, this is likely to happen
 1143            when server.el connects to a new terminal while Emacs is in
 1144            single_kboard mode.  It is best to throw an error instead
 1145            of presenting the user with a frozen screen.  */
 1146         error ("Terminal %d is locked, cannot read from it",
 1147                FRAME_TERMINAL (f)->id);
 1148       else
 1149         /* This call is unnecessary, but helps
 1150            `restore_kboard_configuration' discover if somebody changed
 1151            `current_kboard' behind our back.  */
 1152         push_kboard (current_kboard);
 1153     }
 1154   else if (f != NULL)
 1155     current_kboard = FRAME_KBOARD (f);
 1156   single_kboard = 1;
 1157   record_unwind_protect (restore_kboard_configuration,
 1158                          (was_locked ? Qt : Qnil));
 1159 }
 1160 
 1161 #if 0 /* This function is not needed anymore.  */
 1162 void
 1163 record_single_kboard_state ()
 1164 {
 1165   if (single_kboard)
 1166     push_kboard (current_kboard);
 1167   record_unwind_protect (restore_kboard_configuration,
 1168                          (single_kboard ? Qt : Qnil));
 1169 }
 1170 #endif
 1171 
 1172 static Lisp_Object
 1173 restore_kboard_configuration (was_locked)
 1174      Lisp_Object was_locked;
 1175 {
 1176   if (NILP (was_locked))
 1177     single_kboard = 0;
 1178   else
 1179     {
 1180       struct kboard *prev = current_kboard;
 1181       single_kboard = 1;
 1182       pop_kboard ();
 1183       /* The pop should not change the kboard.  */
 1184       if (single_kboard && current_kboard != prev)
 1185         abort ();
 1186     }
 1187   return Qnil;
 1188 }
 1189 
 1190 
 1191 /* Handle errors that are not handled at inner levels
 1192    by printing an error message and returning to the editor command loop.  */
 1193 
 1194 Lisp_Object
 1195 cmd_error (data)
 1196      Lisp_Object data;
 1197 {
 1198   Lisp_Object old_level, old_length;
 1199   char macroerror[50];
 1200 
 1201 #ifdef HAVE_WINDOW_SYSTEM
 1202   if (display_hourglass_p)
 1203     cancel_hourglass ();
 1204 #endif
 1205 
 1206   if (!NILP (executing_kbd_macro))
 1207     {
 1208       if (executing_kbd_macro_iterations == 1)
 1209         sprintf (macroerror, "After 1 kbd macro iteration: ");
 1210       else
 1211         sprintf (macroerror, "After %d kbd macro iterations: ",
 1212                  executing_kbd_macro_iterations);
 1213     }
 1214   else
 1215     *macroerror = 0;
 1216 
 1217   Vstandard_output = Qt;
 1218   Vstandard_input = Qt;
 1219   Vexecuting_kbd_macro = Qnil;
 1220   executing_kbd_macro = Qnil;
 1221   current_kboard->Vprefix_arg = Qnil;
 1222   current_kboard->Vlast_prefix_arg = Qnil;
 1223   cancel_echoing ();
 1224 
 1225   /* Avoid unquittable loop if data contains a circular list.  */
 1226   old_level = Vprint_level;
 1227   old_length = Vprint_length;
 1228   XSETFASTINT (Vprint_level, 10);
 1229   XSETFASTINT (Vprint_length, 10);
 1230   cmd_error_internal (data, macroerror);
 1231   Vprint_level = old_level;
 1232   Vprint_length = old_length;
 1233 
 1234   Vquit_flag = Qnil;
 1235 
 1236   Vinhibit_quit = Qnil;
 1237 #if 0 /* This shouldn't be necessary anymore. --lorentey */
 1238   if (command_loop_level == 0 && minibuf_level == 0)
 1239     any_kboard_state ();
 1240 #endif
 1241 
 1242   return make_number (0);
 1243 }
 1244 
 1245 /* Take actions on handling an error.  DATA is the data that describes
 1246    the error.
 1247 
 1248    CONTEXT is a C-string containing ASCII characters only which
 1249    describes the context in which the error happened.  If we need to
 1250    generalize CONTEXT to allow multibyte characters, make it a Lisp
 1251    string.  */
 1252 
 1253 void
 1254 cmd_error_internal (data, context)
 1255      Lisp_Object data;
 1256      char *context;
 1257 {
 1258   struct frame *sf = SELECTED_FRAME ();
 1259 
 1260   /* The immediate context is not interesting for Quits,
 1261      since they are asyncronous.  */
 1262   if (EQ (XCAR (data), Qquit))
 1263     Vsignaling_function = Qnil;
 1264 
 1265   Vquit_flag = Qnil;
 1266   Vinhibit_quit = Qt;
 1267 
 1268   /* Use user's specified output function if any.  */
 1269   if (!NILP (Vcommand_error_function))
 1270     call3 (Vcommand_error_function, data,
 1271            context ? build_string (context) : empty_unibyte_string,
 1272            Vsignaling_function);
 1273   /* If the window system or terminal frame hasn't been initialized
 1274      yet, or we're not interactive, write the message to stderr and exit.  */
 1275   else if (!sf->glyphs_initialized_p
 1276            /* The initial frame is a special non-displaying frame. It
 1277               will be current in daemon mode when there are no frames
 1278               to display, and in non-daemon mode before the real frame
 1279               has finished initializing.  If an error is thrown in the
 1280               latter case while creating the frame, then the frame
 1281               will never be displayed, so the safest thing to do is
 1282               write to stderr and quit.  In daemon mode, there are
 1283               many other potential errors that do not prevent frames
 1284               from being created, so continuing as normal is better in
 1285               that case.  */
 1286            || (!IS_DAEMON && FRAME_INITIAL_P (sf))
 1287            || noninteractive)
 1288     {
 1289       print_error_message (data, Qexternal_debugging_output,
 1290                            context, Vsignaling_function);
 1291       Fterpri (Qexternal_debugging_output);
 1292       Fkill_emacs (make_number (-1));
 1293     }
 1294   else
 1295     {
 1296       clear_message (1, 0);
 1297       Fdiscard_input ();
 1298       message_log_maybe_newline ();
 1299       bitch_at_user ();
 1300 
 1301       print_error_message (data, Qt, context, Vsignaling_function);
 1302     }
 1303 
 1304   Vsignaling_function = Qnil;
 1305 }
 1306 
 1307 Lisp_Object command_loop_1 ();
 1308 Lisp_Object command_loop_2 ();
 1309 Lisp_Object top_level_1 ();
 1310 
 1311 /* Entry to editor-command-loop.
 1312    This level has the catches for exiting/returning to editor command loop.
 1313    It returns nil to exit recursive edit, t to abort it.  */
 1314 
 1315 Lisp_Object
 1316 command_loop ()
 1317 {
 1318   if (command_loop_level > 0 || minibuf_level > 0)
 1319     {
 1320       Lisp_Object val;
 1321       val = internal_catch (Qexit, command_loop_2, Qnil);
 1322       executing_kbd_macro = Qnil;
 1323       return val;
 1324     }
 1325   else
 1326     while (1)
 1327       {
 1328         internal_catch (Qtop_level, top_level_1, Qnil);
 1329 #if 0 /* This shouldn't be necessary anymore.  --lorentey  */
 1330         /* Reset single_kboard in case top-level set it while
 1331            evaluating an -f option, or we are stuck there for some
 1332            other reason. */
 1333         any_kboard_state ();
 1334 #endif
 1335         internal_catch (Qtop_level, command_loop_2, Qnil);
 1336         executing_kbd_macro = Qnil;
 1337 
 1338         /* End of file in -batch run causes exit here.  */
 1339         if (noninteractive)
 1340           Fkill_emacs (Qt);
 1341       }
 1342 }
 1343 
 1344 /* Here we catch errors in execution of commands within the
 1345    editing loop, and reenter the editing loop.
 1346    When there is an error, cmd_error runs and returns a non-nil
 1347    value to us.  A value of nil means that command_loop_1 itself
 1348    returned due to end of file (or end of kbd macro).  */
 1349 
 1350 Lisp_Object
 1351 command_loop_2 ()
 1352 {
 1353   register Lisp_Object val;
 1354 
 1355   do
 1356     val = internal_condition_case (command_loop_1, Qerror, cmd_error);
 1357   while (!NILP (val));
 1358 
 1359   return Qnil;
 1360 }
 1361 
 1362 Lisp_Object
 1363 top_level_2 ()
 1364 {
 1365   return Feval (Vtop_level);
 1366 }
 1367 
 1368 Lisp_Object
 1369 top_level_1 ()
 1370 {
 1371   /* On entry to the outer level, run the startup file */
 1372   if (!NILP (Vtop_level))
 1373     internal_condition_case (top_level_2, Qerror, cmd_error);
 1374   else if (!NILP (Vpurify_flag))
 1375     message ("Bare impure Emacs (standard Lisp code not loaded)");
 1376   else
 1377     message ("Bare Emacs (standard Lisp code not loaded)");
 1378   return Qnil;
 1379 }
 1380 
 1381 DEFUN ("top-level", Ftop_level, Stop_level, 0, 0, "",
 1382        doc: /* Exit all recursive editing levels.
 1383 This also exits all active minibuffers.  */)
 1384      ()
 1385 {
 1386 #ifdef HAVE_WINDOW_SYSTEM
 1387   if (display_hourglass_p)
 1388     cancel_hourglass ();
 1389 #endif
 1390 
 1391   /* Unblock input if we enter with input blocked.  This may happen if
 1392      redisplay traps e.g. during tool-bar update with input blocked.  */
 1393   while (INPUT_BLOCKED_P)
 1394     UNBLOCK_INPUT;
 1395 
 1396   return Fthrow (Qtop_level, Qnil);
 1397 }
 1398 
 1399 DEFUN ("exit-recursive-edit", Fexit_recursive_edit, Sexit_recursive_edit, 0, 0, "",
 1400        doc: /* Exit from the innermost recursive edit or minibuffer.  */)
 1401      ()
 1402 {
 1403   if (command_loop_level > 0 || minibuf_level > 0)
 1404     Fthrow (Qexit, Qnil);
 1405 
 1406   error ("No recursive edit is in progress");
 1407   return Qnil;
 1408 }
 1409 
 1410 DEFUN ("abort-recursive-edit", Fabort_recursive_edit, Sabort_recursive_edit, 0, 0, "",
 1411        doc: /* Abort the command that requested this recursive edit or minibuffer input.  */)
 1412      ()
 1413 {
 1414   if (command_loop_level > 0 || minibuf_level > 0)
 1415     Fthrow (Qexit, Qt);
 1416 
 1417   error ("No recursive edit is in progress");
 1418   return Qnil;
 1419 }
 1420 
 1421 #if defined (HAVE_MOUSE) || defined (HAVE_GPM)
 1422 
 1423 /* Restore mouse tracking enablement.  See Ftrack_mouse for the only use
 1424    of this function.  */
 1425 
 1426 static Lisp_Object
 1427 tracking_off (old_value)
 1428      Lisp_Object old_value;
 1429 {
 1430   do_mouse_tracking = old_value;
 1431   if (NILP (old_value))
 1432     {
 1433       /* Redisplay may have been preempted because there was input
 1434          available, and it assumes it will be called again after the
 1435          input has been processed.  If the only input available was
 1436          the sort that we have just disabled, then we need to call
 1437          redisplay.  */
 1438       if (!readable_events (READABLE_EVENTS_DO_TIMERS_NOW))
 1439         {
 1440           redisplay_preserve_echo_area (6);
 1441           get_input_pending (&input_pending,
 1442                              READABLE_EVENTS_DO_TIMERS_NOW);
 1443         }
 1444     }
 1445   return Qnil;
 1446 }
 1447 
 1448 DEFUN ("track-mouse", Ftrack_mouse, Strack_mouse, 0, UNEVALLED, 0,
 1449        doc: /* Evaluate BODY with mouse movement events enabled.
 1450 Within a `track-mouse' form, mouse motion generates input events that
 1451 you can read with `read-event'.
 1452 Normally, mouse motion is ignored.
 1453 usage: (track-mouse BODY...)  */)
 1454      (args)
 1455      Lisp_Object args;
 1456 {
 1457   int count = SPECPDL_INDEX ();
 1458   Lisp_Object val;
 1459 
 1460   record_unwind_protect (tracking_off, do_mouse_tracking);
 1461 
 1462   do_mouse_tracking = Qt;
 1463 
 1464   val = Fprogn (args);
 1465   return unbind_to (count, val);
 1466 }
 1467 
 1468 /* If mouse has moved on some frame, return one of those frames.
 1469 
 1470    Return 0 otherwise.
 1471 
 1472    If ignore_mouse_drag_p is non-zero, ignore (implicit) mouse movement
 1473    after resizing the tool-bar window.  */
 1474 
 1475 int ignore_mouse_drag_p;
 1476 
 1477 static FRAME_PTR
 1478 some_mouse_moved ()
 1479 {
 1480   Lisp_Object tail, frame;
 1481 
 1482   if (ignore_mouse_drag_p)
 1483     {
 1484       /* ignore_mouse_drag_p = 0; */
 1485       return 0;
 1486     }
 1487 
 1488   FOR_EACH_FRAME (tail, frame)
 1489     {
 1490       if (XFRAME (frame)->mouse_moved)
 1491         return XFRAME (frame);
 1492     }
 1493 
 1494   return 0;
 1495 }
 1496 
 1497 #endif  /* HAVE_MOUSE || HAVE_GPM */
 1498 
 1499 /* This is the actual command reading loop,
 1500    sans error-handling encapsulation.  */
 1501 
 1502 static int read_key_sequence P_ ((Lisp_Object *, int, Lisp_Object,
 1503                                   int, int, int));
 1504 void safe_run_hooks P_ ((Lisp_Object));
 1505 static void adjust_point_for_property P_ ((int, int));
 1506 
 1507 /* Cancel hourglass from protect_unwind.
 1508    ARG is not used.  */
 1509 #ifdef HAVE_WINDOW_SYSTEM
 1510 static Lisp_Object
 1511 cancel_hourglass_unwind (arg)
 1512      Lisp_Object arg;
 1513 {
 1514   cancel_hourglass ();
 1515   return Qnil;
 1516 }
 1517 #endif
 1518 
 1519 Lisp_Object
 1520 command_loop_1 ()
 1521 {
 1522   Lisp_Object cmd;
 1523   Lisp_Object keybuf[30];
 1524   int i;
 1525   int prev_modiff = 0;
 1526   struct buffer *prev_buffer = NULL;
 1527 #if 0 /* This shouldn't be necessary anymore.  --lorentey  */
 1528   int was_locked = single_kboard;
 1529 #endif
 1530   int already_adjusted = 0;
 1531 
 1532   current_kboard->Vprefix_arg = Qnil;
 1533   current_kboard->Vlast_prefix_arg = Qnil;
 1534   Vdeactivate_mark = Qnil;
 1535   waiting_for_input = 0;
 1536   cancel_echoing ();
 1537 
 1538   this_command_key_count = 0;
 1539   this_command_key_count_reset = 0;
 1540   this_single_command_key_start = 0;
 1541 
 1542   if (NILP (Vmemory_full))
 1543     {
 1544       /* Make sure this hook runs after commands that get errors and
 1545          throw to top level.  */
 1546       /* Note that the value cell will never directly contain nil
 1547          if the symbol is a local variable.  */
 1548       if (!NILP (Vpost_command_hook) && !NILP (Vrun_hooks))
 1549         safe_run_hooks (Qpost_command_hook);
 1550 
 1551       /* If displaying a message, resize the echo area window to fit
 1552          that message's size exactly.  */
 1553       if (!NILP (echo_area_buffer[0]))
 1554         resize_echo_area_exactly ();
 1555 
 1556       if (!NILP (Vdeferred_action_list))
 1557         safe_run_hooks (Qdeferred_action_function);
 1558     }
 1559 
 1560   /* Do this after running Vpost_command_hook, for consistency.  */
 1561   current_kboard->Vlast_command = Vthis_command;
 1562   current_kboard->Vreal_last_command = real_this_command;
 1563   if (!CONSP (last_command_event))
 1564     current_kboard->Vlast_repeatable_command = real_this_command;
 1565 
 1566   while (1)
 1567     {
 1568       if (! FRAME_LIVE_P (XFRAME (selected_frame)))
 1569         Fkill_emacs (Qnil);
 1570 
 1571       /* Make sure the current window's buffer is selected.  */
 1572       if (XBUFFER (XWINDOW (selected_window)->buffer) != current_buffer)
 1573         set_buffer_internal (XBUFFER (XWINDOW (selected_window)->buffer));
 1574 
 1575       /* Display any malloc warning that just came out.  Use while because
 1576          displaying one warning can cause another.  */
 1577 
 1578       while (pending_malloc_warning)
 1579         display_malloc_warning ();
 1580 
 1581       Vdeactivate_mark = Qnil;
 1582 
 1583       /* If minibuffer on and echo area in use,
 1584          wait a short time and redraw minibuffer.  */
 1585 
 1586       if (minibuf_level
 1587           && !NILP (echo_area_buffer[0])
 1588           && EQ (minibuf_window, echo_area_window)
 1589           && NUMBERP (Vminibuffer_message_timeout))
 1590         {
 1591           /* Bind inhibit-quit to t so that C-g gets read in
 1592              rather than quitting back to the minibuffer.  */
 1593           int count = SPECPDL_INDEX ();
 1594           specbind (Qinhibit_quit, Qt);
 1595 
 1596           sit_for (Vminibuffer_message_timeout, 0, 2);
 1597 
 1598           /* Clear the echo area.  */
 1599           message2 (0, 0, 0);
 1600           safe_run_hooks (Qecho_area_clear_hook);
 1601 
 1602           unbind_to (count, Qnil);
 1603 
 1604           /* If a C-g came in before, treat it as input now.  */
 1605           if (!NILP (Vquit_flag))
 1606             {
 1607               Vquit_flag = Qnil;
 1608               Vunread_command_events = Fcons (make_number (quit_char), Qnil);
 1609             }
 1610         }
 1611 
 1612 #if 0
 1613       /* Select the frame that the last event came from.  Usually,
 1614          switch-frame events will take care of this, but if some lisp
 1615          code swallows a switch-frame event, we'll fix things up here.
 1616          Is this a good idea?  */
 1617       if (FRAMEP (internal_last_event_frame)
 1618           && !EQ (internal_last_event_frame, selected_frame))
 1619         Fselect_frame (internal_last_event_frame, Qnil);
 1620 #endif
 1621       /* If it has changed current-menubar from previous value,
 1622          really recompute the menubar from the value.  */
 1623       if (! NILP (Vlucid_menu_bar_dirty_flag)
 1624           && !NILP (Ffboundp (Qrecompute_lucid_menubar)))
 1625         call0 (Qrecompute_lucid_menubar);
 1626 
 1627       before_command_key_count = this_command_key_count;
 1628       before_command_echo_length = echo_length ();
 1629 
 1630       Vthis_command = Qnil;
 1631       real_this_command = Qnil;
 1632       Vthis_original_command = Qnil;
 1633       Vthis_command_keys_shift_translated = Qnil;
 1634 
 1635       /* Read next key sequence; i gets its length.  */
 1636       i = read_key_sequence (keybuf, sizeof keybuf / sizeof keybuf[0],
 1637                              Qnil, 0, 1, 1);
 1638 
 1639       /* A filter may have run while we were reading the input.  */
 1640       if (! FRAME_LIVE_P (XFRAME (selected_frame)))
 1641         Fkill_emacs (Qnil);
 1642       if (XBUFFER (XWINDOW (selected_window)->buffer) != current_buffer)
 1643         set_buffer_internal (XBUFFER (XWINDOW (selected_window)->buffer));
 1644 
 1645       ++num_input_keys;
 1646 
 1647       /* Now we have read a key sequence of length I,
 1648          or else I is 0 and we found end of file.  */
 1649 
 1650       if (i == 0)               /* End of file -- happens only in */
 1651         return Qnil;            /* a kbd macro, at the end.  */
 1652       /* -1 means read_key_sequence got a menu that was rejected.
 1653          Just loop around and read another command.  */
 1654       if (i == -1)
 1655         {
 1656           cancel_echoing ();
 1657           this_command_key_count = 0;
 1658           this_command_key_count_reset = 0;
 1659           this_single_command_key_start = 0;
 1660           goto finalize;
 1661         }
 1662 
 1663       last_command_event = keybuf[i - 1];
 1664 
 1665       /* If the previous command tried to force a specific window-start,
 1666          forget about that, in case this command moves point far away
 1667          from that position.  But also throw away beg_unchanged and
 1668          end_unchanged information in that case, so that redisplay will
 1669          update the whole window properly.  */
 1670       if (!NILP (XWINDOW (selected_window)->force_start))
 1671         {
 1672           struct buffer *b;
 1673           XWINDOW (selected_window)->force_start = Qnil;
 1674           b = XBUFFER (XWINDOW (selected_window)->buffer);
 1675           BUF_BEG_UNCHANGED (b) = BUF_END_UNCHANGED (b) = 0;
 1676         }
 1677 
 1678       cmd = read_key_sequence_cmd;
 1679       if (!NILP (Vexecuting_kbd_macro))
 1680         {
 1681           if (!NILP (Vquit_flag))
 1682             {
 1683               Vexecuting_kbd_macro = Qt;
 1684               QUIT;             /* Make some noise. */
 1685                                 /* Will return since macro now empty. */
 1686             }
 1687         }
 1688 
 1689       /* Do redisplay processing after this command except in special
 1690          cases identified below.  */
 1691       prev_buffer = current_buffer;
 1692       prev_modiff = MODIFF;
 1693       last_point_position = PT;
 1694       last_point_position_window = selected_window;
 1695       XSETBUFFER (last_point_position_buffer, prev_buffer);
 1696 
 1697       /* By default, we adjust point to a boundary of a region that
 1698          has such a property that should be treated intangible
 1699          (e.g. composition, display).  But, some commands will set
 1700          this variable differently.  */
 1701       Vdisable_point_adjustment = Qnil;
 1702 
 1703       /* Process filters and timers may have messed with deactivate-mark.
 1704          reset it before we execute the command. */
 1705       Vdeactivate_mark = Qnil;
 1706 
 1707       /* Remap command through active keymaps */
 1708       Vthis_original_command = cmd;
 1709       if (SYMBOLP (cmd))
 1710         {
 1711           Lisp_Object cmd1;
 1712           if (cmd1 = Fcommand_remapping (cmd, Qnil, Qnil), !NILP (cmd1))
 1713             cmd = cmd1;
 1714         }
 1715 
 1716       /* Execute the command.  */
 1717 
 1718       Vthis_command = cmd;
 1719       real_this_command = cmd;
 1720       /* Note that the value cell will never directly contain nil
 1721          if the symbol is a local variable.  */
 1722       if (!NILP (Vpre_command_hook) && !NILP (Vrun_hooks))
 1723         safe_run_hooks (Qpre_command_hook);
 1724 
 1725       already_adjusted = 0;
 1726 
 1727       if (NILP (Vthis_command))
 1728         {
 1729           /* nil means key is undefined.  */
 1730           Lisp_Object keys = Fvector (i, keybuf);
 1731           keys = Fkey_description (keys, Qnil);
 1732           bitch_at_user ();
 1733           message_with_string ("%s is undefined", keys, 0);
 1734           current_kboard->defining_kbd_macro = Qnil;
 1735           update_mode_lines = 1;
 1736           current_kboard->Vprefix_arg = Qnil;
 1737         }
 1738       else
 1739         {
 1740           /* Here for a command that isn't executed directly */
 1741 
 1742 #ifdef HAVE_WINDOW_SYSTEM
 1743             int scount = SPECPDL_INDEX ();
 1744 
 1745             if (display_hourglass_p
 1746                 && NILP (Vexecuting_kbd_macro))
 1747               {
 1748                 record_unwind_protect (cancel_hourglass_unwind, Qnil);
 1749                 start_hourglass ();
 1750               }
 1751 #endif
 1752 
 1753             if (NILP (current_kboard->Vprefix_arg)) /* FIXME: Why?  --Stef  */
 1754               Fundo_boundary ();
 1755             Fcommand_execute (Vthis_command, Qnil, Qnil, Qnil);
 1756 
 1757 #ifdef HAVE_WINDOW_SYSTEM
 1758           /* Do not check display_hourglass_p here, because
 1759              Fcommand_execute could change it, but we should cancel
 1760              hourglass cursor anyway.
 1761              But don't cancel the hourglass within a macro
 1762              just because a command in the macro finishes.  */
 1763           if (NILP (Vexecuting_kbd_macro))
 1764             unbind_to (scount, Qnil);
 1765 #endif
 1766           }
 1767       current_kboard->Vlast_prefix_arg = Vcurrent_prefix_arg;
 1768 
 1769       /* Note that the value cell will never directly contain nil
 1770          if the symbol is a local variable.  */
 1771       if (!NILP (Vpost_command_hook) && !NILP (Vrun_hooks))
 1772         safe_run_hooks (Qpost_command_hook);
 1773 
 1774       /* If displaying a message, resize the echo area window to fit
 1775          that message's size exactly.  */
 1776       if (!NILP (echo_area_buffer[0]))
 1777         resize_echo_area_exactly ();
 1778 
 1779       if (!NILP (Vdeferred_action_list))
 1780         safe_run_hooks (Qdeferred_action_function);
 1781 
 1782       /* If there is a prefix argument,
 1783          1) We don't want Vlast_command to be ``universal-argument''
 1784          (that would be dumb), so don't set Vlast_command,
 1785          2) we want to leave echoing on so that the prefix will be
 1786          echoed as part of this key sequence, so don't call
 1787          cancel_echoing, and
 1788          3) we want to leave this_command_key_count non-zero, so that
 1789          read_char will realize that it is re-reading a character, and
 1790          not echo it a second time.
 1791 
 1792          If the command didn't actually create a prefix arg,
 1793          but is merely a frame event that is transparent to prefix args,
 1794          then the above doesn't apply.  */
 1795       if (NILP (current_kboard->Vprefix_arg) || CONSP (last_command_event))
 1796         {
 1797           current_kboard->Vlast_command = Vthis_command;
 1798           current_kboard->Vreal_last_command = real_this_command;
 1799           if (!CONSP (last_command_event))
 1800             current_kboard->Vlast_repeatable_command = real_this_command;
 1801           cancel_echoing ();
 1802           this_command_key_count = 0;
 1803           this_command_key_count_reset = 0;
 1804           this_single_command_key_start = 0;
 1805         }
 1806 
 1807       if (!NILP (current_buffer->mark_active) && !NILP (Vrun_hooks))
 1808         {
 1809           /* In Emacs 22, setting transient-mark-mode to `only' was a
 1810              way of turning it on for just one command.  This usage is
 1811              obsolete, but support it anyway.  */
 1812           if (EQ (Vtransient_mark_mode, Qidentity))
 1813             Vtransient_mark_mode = Qnil;
 1814           else if (EQ (Vtransient_mark_mode, Qonly))
 1815             Vtransient_mark_mode = Qidentity;
 1816 
 1817           if (!NILP (Vdeactivate_mark))
 1818             call0 (Qdeactivate_mark);
 1819           else if (current_buffer != prev_buffer || MODIFF != prev_modiff)
 1820             call1 (Vrun_hooks, intern ("activate-mark-hook"));
 1821         }
 1822 
 1823     finalize:
 1824 
 1825       if (current_buffer == prev_buffer
 1826           && last_point_position != PT
 1827           && NILP (Vdisable_point_adjustment)
 1828           && NILP (Vglobal_disable_point_adjustment))
 1829         {
 1830           if (last_point_position > BEGV
 1831               && last_point_position < ZV
 1832               && (composition_adjust_point (last_point_position,
 1833                                             last_point_position)
 1834                   != last_point_position))
 1835             /* The last point was temporarily set within a grapheme
 1836                cluster to prevent automatic composition.  To recover
 1837                the automatic composition, we must update the
 1838                display.  */
 1839             windows_or_buffers_changed++;
 1840           if (!already_adjusted)
 1841             adjust_point_for_property (last_point_position,
 1842                                        MODIFF != prev_modiff);
 1843         }
 1844 
 1845       /* Install chars successfully executed in kbd macro.  */
 1846 
 1847       if (!NILP (current_kboard->defining_kbd_macro)
 1848           && NILP (current_kboard->Vprefix_arg))
 1849         finalize_kbd_macro_chars ();
 1850 #if 0 /* This shouldn't be necessary anymore.  --lorentey  */
 1851       if (!was_locked)
 1852         any_kboard_state ();
 1853 #endif
 1854     }
 1855 }
 1856 
 1857 extern Lisp_Object Qcomposition, Qdisplay;
 1858 
 1859 /* Adjust point to a boundary of a region that has such a property
 1860    that should be treated intangible.  For the moment, we check
 1861    `composition', `display' and `invisible' properties.
 1862    LAST_PT is the last position of point.  */
 1863 
 1864 extern Lisp_Object Qafter_string, Qbefore_string;
 1865 extern Lisp_Object get_pos_property P_ ((Lisp_Object, Lisp_Object, Lisp_Object));
 1866 
 1867 static void
 1868 adjust_point_for_property (last_pt, modified)
 1869      int last_pt;
 1870      int modified;
 1871 {
 1872   EMACS_INT beg, end;
 1873   Lisp_Object val, overlay, tmp;
 1874   /* When called after buffer modification, we should temporarily
 1875      suppress the point adjustment for automatic composition so that a
 1876      user can keep inserting another character at point or keep
 1877      deleting characters around point.  */
 1878   int check_composition = ! modified, check_display = 1, check_invisible = 1;
 1879   int orig_pt = PT;
 1880 
 1881   /* FIXME: cycling is probably not necessary because these properties
 1882      can't be usefully combined anyway.  */
 1883   while (check_composition || check_display || check_invisible)
 1884     {
 1885       /* FIXME: check `intangible'.  */
 1886       if (check_composition
 1887           && PT > BEGV && PT < ZV
 1888           && (beg = composition_adjust_point (last_pt, PT)) != PT)
 1889         {
 1890           SET_PT (beg);
 1891           check_display = check_invisible = 1;
 1892         }
 1893       check_composition = 0;
 1894       if (check_display
 1895           && PT > BEGV && PT < ZV
 1896           && !NILP (val = get_char_property_and_overlay
 1897                               (make_number (PT), Qdisplay, Qnil, &overlay))
 1898           && display_prop_intangible_p (val)
 1899           && (!OVERLAYP (overlay)
 1900               ? get_property_and_range (PT, Qdisplay, &val, &beg, &end, Qnil)
 1901               : (beg = OVERLAY_POSITION (OVERLAY_START (overlay)),
 1902                  end = OVERLAY_POSITION (OVERLAY_END (overlay))))
 1903           && (beg < PT /* && end > PT   <- It's always the case.  */
 1904               || (beg <= PT && STRINGP (val) && SCHARS (val) == 0)))
 1905         {
 1906           xassert (end > PT);
 1907           SET_PT (PT < last_pt
 1908                   ? (STRINGP (val) && SCHARS (val) == 0 ? beg - 1 : beg)
 1909                   : end);
 1910           check_composition = check_invisible = 1;
 1911         }
 1912       check_display = 0;
 1913       if (check_invisible && PT > BEGV && PT < ZV)
 1914         {
 1915           int inv, ellipsis = 0;
 1916           beg = end = PT;
 1917 
 1918           /* Find boundaries `beg' and `end' of the invisible area, if any.  */
 1919           while (end < ZV
 1920 #if 0
 1921                  /* FIXME: We should stop if we find a spot between
 1922                     two runs of `invisible' where inserted text would
 1923                     be visible.  This is important when we have two
 1924                     invisible boundaries that enclose an area: if the
 1925                     area is empty, we need this test in order to make
 1926                     it possible to place point in the middle rather
 1927                     than skip both boundaries.  However, this code
 1928                     also stops anywhere in a non-sticky text-property,
 1929                     which breaks (e.g.) Org mode.  */
 1930                  && (val = get_pos_property (make_number (end),
 1931                                              Qinvisible, Qnil),
 1932                      TEXT_PROP_MEANS_INVISIBLE (val))
 1933 #endif
 1934                  && !NILP (val = get_char_property_and_overlay
 1935                            (make_number (end), Qinvisible, Qnil, &overlay))
 1936                  && (inv = TEXT_PROP_MEANS_INVISIBLE (val)))
 1937             {
 1938               ellipsis = ellipsis || inv > 1
 1939                 || (OVERLAYP (overlay)
 1940                     && (!NILP (Foverlay_get (overlay, Qafter_string))
 1941                         || !NILP (Foverlay_get (overlay, Qbefore_string))));
 1942               tmp = Fnext_single_char_property_change
 1943                 (make_number (end), Qinvisible, Qnil, Qnil);
 1944               end = NATNUMP (tmp) ? XFASTINT (tmp) : ZV;
 1945             }
 1946           while (beg > BEGV
 1947 #if 0
 1948                  && (val = get_pos_property (make_number (beg),
 1949                                              Qinvisible, Qnil),
 1950                      TEXT_PROP_MEANS_INVISIBLE (val))
 1951 #endif
 1952                  && !NILP (val = get_char_property_and_overlay
 1953                            (make_number (beg - 1), Qinvisible, Qnil, &overlay))
 1954                  && (inv = TEXT_PROP_MEANS_INVISIBLE (val)))
 1955             {
 1956               ellipsis = ellipsis || inv > 1
 1957                 || (OVERLAYP (overlay)
 1958                     && (!NILP (Foverlay_get (overlay, Qafter_string))
 1959                         || !NILP (Foverlay_get (overlay, Qbefore_string))));
 1960               tmp = Fprevious_single_char_property_change
 1961                 (make_number (beg), Qinvisible, Qnil, Qnil);
 1962               beg = NATNUMP (tmp) ? XFASTINT (tmp) : BEGV;
 1963             }
 1964 
 1965           /* Move away from the inside area.  */
 1966           if (beg < PT && end > PT)
 1967             {
 1968               SET_PT ((orig_pt == PT && (last_pt < beg || last_pt > end))
 1969                       /* We haven't moved yet (so we don't need to fear
 1970                          infinite-looping) and we were outside the range
 1971                          before (so either end of the range still corresponds
 1972                          to a move in the right direction): pretend we moved
 1973                          less than we actually did, so that we still have
 1974                          more freedom below in choosing which end of the range
 1975                          to go to.  */
 1976                       ? (orig_pt = -1, PT < last_pt ? end : beg)
 1977                       /* We either have moved already or the last point
 1978                          was already in the range: we don't get to choose
 1979                          which end of the range we have to go to.  */
 1980                       : (PT < last_pt ? beg : end));
 1981               check_composition = check_display = 1;
 1982             }
 1983 #if 0 /* This assertion isn't correct, because SET_PT may end up setting
 1984          the point to something other than its argument, due to
 1985          point-motion hooks, intangibility, etc.  */
 1986           xassert (PT == beg || PT == end);
 1987 #endif
 1988 
 1989           /* Pretend the area doesn't exist if the buffer is not
 1990              modified.  */
 1991           if (!modified && !ellipsis && beg < end)
 1992             {
 1993               if (last_pt == beg && PT == end && end < ZV)
 1994                 (check_composition = check_display = 1, SET_PT (end + 1));
 1995               else if (last_pt == end && PT == beg && beg > BEGV)
 1996                 (check_composition = check_display = 1, SET_PT (beg - 1));
 1997               else if (PT == ((PT < last_pt) ? beg : end))
 1998                 /* We've already moved as far as we can.  Trying to go
 1999                    to the other end would mean moving backwards and thus
 2000                    could lead to an infinite loop.  */
 2001                 ;
 2002               else if (val = get_pos_property (make_number (PT),
 2003                                                Qinvisible, Qnil),
 2004                        TEXT_PROP_MEANS_INVISIBLE (val)
 2005                        && (val = get_pos_property
 2006                            (make_number (PT == beg ? end : beg),
 2007                             Qinvisible, Qnil),
 2008                            !TEXT_PROP_MEANS_INVISIBLE (val)))
 2009                 (check_composition = check_display = 1,
 2010                  SET_PT (PT == beg ? end : beg));
 2011             }
 2012         }
 2013       check_invisible = 0;
 2014     }
 2015 }
 2016 
 2017 /* Subroutine for safe_run_hooks: run the hook HOOK.  */
 2018 
 2019 static Lisp_Object
 2020 safe_run_hooks_1 (hook)
 2021      Lisp_Object hook;
 2022 {
 2023   if (NILP (Vrun_hooks))
 2024     return Qnil;
 2025   return call1 (Vrun_hooks, Vinhibit_quit);
 2026 }
 2027 
 2028 /* Subroutine for safe_run_hooks: handle an error by clearing out the hook.  */
 2029 
 2030 static Lisp_Object
 2031 safe_run_hooks_error (data)
 2032      Lisp_Object data;
 2033 {
 2034   Lisp_Object args[3];
 2035   args[0] = build_string ("Error in %s: %s");
 2036   args[1] = Vinhibit_quit;
 2037   args[2] = data;
 2038   Fmessage (3, args);
 2039   return Fset (Vinhibit_quit, Qnil);
 2040 }
 2041 
 2042 /* If we get an error while running the hook, cause the hook variable
 2043    to be nil.  Also inhibit quits, so that C-g won't cause the hook
 2044    to mysteriously evaporate.  */
 2045 
 2046 void
 2047 safe_run_hooks (hook)
 2048      Lisp_Object hook;
 2049 {
 2050   int count = SPECPDL_INDEX ();
 2051   specbind (Qinhibit_quit, hook);
 2052 
 2053   internal_condition_case (safe_run_hooks_1, Qt, safe_run_hooks_error);
 2054 
 2055   unbind_to (count, Qnil);
 2056 }
 2057 
 2058 
 2059 /* Number of seconds between polling for input.  This is a Lisp
 2060    variable that can be bound.  */
 2061 
 2062 EMACS_INT polling_period;
 2063 
 2064 /* Nonzero means polling for input is temporarily suppressed.  */
 2065 
 2066 int poll_suppress_count;
 2067 
 2068 /* Asynchronous timer for polling.  */
 2069 
 2070 struct atimer *poll_timer;
 2071 
 2072 
 2073 #ifdef POLL_FOR_INPUT
 2074 
 2075 /* Poll for input, so that we catch a C-g if it comes in.  This
 2076    function is called from x_make_frame_visible, see comment
 2077    there.  */
 2078 
 2079 void
 2080 poll_for_input_1 ()
 2081 {
 2082 /* Tell ns_read_socket() it is being called asynchronously so it can avoid
 2083    doing anything dangerous. */
 2084 #ifdef HAVE_NS
 2085   ++handling_signal;
 2086 #endif
 2087   if (interrupt_input_blocked == 0
 2088       && !waiting_for_input)
 2089     read_avail_input (0);
 2090 #ifdef HAVE_NS
 2091   --handling_signal;
 2092 #endif
 2093 }
 2094 
 2095 /* Timer callback function for poll_timer.  TIMER is equal to
 2096    poll_timer.  */
 2097 
 2098 void
 2099 poll_for_input (timer)
 2100      struct atimer *timer;
 2101 {
 2102   if (poll_suppress_count == 0)
 2103     {
 2104 #ifdef SYNC_INPUT
 2105       interrupt_input_pending = 1;
 2106       pending_signals = 1;
 2107 #else
 2108       poll_for_input_1 ();
 2109 #endif
 2110     }
 2111 }
 2112 
 2113 #endif /* POLL_FOR_INPUT */
 2114 
 2115 /* Begin signals to poll for input, if they are appropriate.
 2116    This function is called unconditionally from various places.  */
 2117 
 2118 void
 2119 start_polling ()
 2120 {
 2121 #ifdef POLL_FOR_INPUT
 2122   /* XXX This condition was (read_socket_hook && !interrupt_input),
 2123      but read_socket_hook is not global anymore.  Let's pretend that
 2124      it's always set. */
 2125   if (!interrupt_input)
 2126     {
 2127       /* Turn alarm handling on unconditionally.  It might have
 2128          been turned off in process.c.  */
 2129       turn_on_atimers (1);
 2130 
 2131       /* If poll timer doesn't exist, are we need one with
 2132          a different interval, start a new one.  */
 2133       if (poll_timer == NULL
 2134           || EMACS_SECS (poll_timer->interval) != polling_period)
 2135         {
 2136           EMACS_TIME interval;
 2137 
 2138           if (poll_timer)
 2139             cancel_atimer (poll_timer);
 2140 
 2141           EMACS_SET_SECS_USECS (interval, polling_period, 0);
 2142           poll_timer = start_atimer (ATIMER_CONTINUOUS, interval,
 2143                                      poll_for_input, NULL);
 2144         }
 2145 
 2146       /* Let the timer's callback function poll for input
 2147          if this becomes zero.  */
 2148       --poll_suppress_count;
 2149     }
 2150 #endif
 2151 }
 2152 
 2153 /* Nonzero if we are using polling to handle input asynchronously.  */
 2154 
 2155 int
 2156 input_polling_used ()
 2157 {
 2158 #ifdef POLL_FOR_INPUT
 2159   /* XXX This condition was (read_socket_hook && !interrupt_input),
 2160      but read_socket_hook is not global anymore.  Let's pretend that
 2161      it's always set. */
 2162   return !interrupt_input;
 2163 #else
 2164   return 0;
 2165 #endif
 2166 }
 2167 
 2168 /* Turn off polling.  */
 2169 
 2170 void
 2171 stop_polling ()
 2172 {
 2173 #ifdef POLL_FOR_INPUT
 2174   /* XXX This condition was (read_socket_hook && !interrupt_input),
 2175      but read_socket_hook is not global anymore.  Let's pretend that
 2176      it's always set. */
 2177   if (!interrupt_input)
 2178     ++poll_suppress_count;
 2179 #endif
 2180 }
 2181 
 2182 /* Set the value of poll_suppress_count to COUNT
 2183    and start or stop polling accordingly.  */
 2184 
 2185 void
 2186 set_poll_suppress_count (count)
 2187      int count;
 2188 {
 2189 #ifdef POLL_FOR_INPUT
 2190   if (count == 0 && poll_suppress_count != 0)
 2191     {
 2192       poll_suppress_count = 1;
 2193       start_polling ();
 2194     }
 2195   else if (count != 0 && poll_suppress_count == 0)
 2196     {
 2197       stop_polling ();
 2198     }
 2199   poll_suppress_count = count;
 2200 #endif
 2201 }
 2202 
 2203 /* Bind polling_period to a value at least N.
 2204    But don't decrease it.  */
 2205 
 2206 void
 2207 bind_polling_period (n)
 2208      int n;
 2209 {
 2210 #ifdef POLL_FOR_INPUT
 2211   int new = polling_period;
 2212 
 2213   if (n > new)
 2214     new = n;
 2215 
 2216   stop_other_atimers (poll_timer);
 2217   stop_polling ();
 2218   specbind (Qpolling_period, make_number (new));
 2219   /* Start a new alarm with the new period.  */
 2220   start_polling ();
 2221 #endif
 2222 }
 2223 
 2224 /* Apply the control modifier to CHARACTER.  */
 2225 
 2226 int
 2227 make_ctrl_char (c)
 2228      int c;
 2229 {
 2230   /* Save the upper bits here.  */
 2231   int upper = c & ~0177;
 2232 
 2233   if (! ASCII_BYTE_P (c))
 2234     return c |= ctrl_modifier;
 2235 
 2236   c &= 0177;
 2237 
 2238   /* Everything in the columns containing the upper-case letters
 2239      denotes a control character.  */
 2240   if (c >= 0100 && c < 0140)
 2241     {
 2242       int oc = c;
 2243       c &= ~0140;
 2244       /* Set the shift modifier for a control char
 2245          made from a shifted letter.  But only for letters!  */
 2246       if (oc >= 'A' && oc <= 'Z')
 2247         c |= shift_modifier;
 2248     }
 2249 
 2250   /* The lower-case letters denote control characters too.  */
 2251   else if (c >= 'a' && c <= 'z')
 2252     c &= ~0140;
 2253 
 2254   /* Include the bits for control and shift
 2255      only if the basic ASCII code can't indicate them.  */
 2256   else if (c >= ' ')
 2257     c |= ctrl_modifier;
 2258 
 2259   /* Replace the high bits.  */
 2260   c |= (upper & ~ctrl_modifier);
 2261 
 2262   return c;
 2263 }
 2264 
 2265 /* Display the help-echo property of the character after the mouse pointer.
 2266    Either show it in the echo area, or call show-help-function to display
 2267    it by other means (maybe in a tooltip).
 2268 
 2269    If HELP is nil, that means clear the previous help echo.
 2270 
 2271    If HELP is a string, display that string.  If HELP is a function,
 2272    call it with OBJECT and POS as arguments; the function should
 2273    return a help string or nil for none.  For all other types of HELP,
 2274    evaluate it to obtain a string.
 2275 
 2276    WINDOW is the window in which the help was generated, if any.
 2277    It is nil if not in a window.
 2278 
 2279    If OBJECT is a buffer, POS is the position in the buffer where the
 2280    `help-echo' text property was found.
 2281 
 2282    If OBJECT is an overlay, that overlay has a `help-echo' property,
 2283    and POS is the position in the overlay's buffer under the mouse.
 2284 
 2285    If OBJECT is a string (an overlay string or a string displayed with
 2286    the `display' property).  POS is the position in that string under
 2287    the mouse.
 2288 
 2289    OK_TO_OVERWRITE_KEYSTROKE_ECHO non-zero means it's okay if the help
 2290    echo overwrites a keystroke echo currently displayed in the echo
 2291    area.
 2292 
 2293    Note: this function may only be called with HELP nil or a string
 2294    from X code running asynchronously.  */
 2295 
 2296 void
 2297 show_help_echo (help, window, object, pos, ok_to_overwrite_keystroke_echo)
 2298      Lisp_Object help, window, object, pos;
 2299      int ok_to_overwrite_keystroke_echo;
 2300 {
 2301   if (!NILP (help) && !STRINGP (help))
 2302     {
 2303       if (FUNCTIONP (help))
 2304         {
 2305           Lisp_Object args[4];
 2306           args[0] = help;
 2307           args[1] = window;
 2308           args[2] = object;
 2309           args[3] = pos;
 2310           help = safe_call (4, args);
 2311         }
 2312       else
 2313         help = safe_eval (help);
 2314 
 2315       if (!STRINGP (help))
 2316         return;
 2317     }
 2318 
 2319 #if defined (HAVE_MOUSE) || defined (HAVE_GPM)
 2320   if (!noninteractive && STRINGP (help))
 2321     {
 2322       /* The mouse-fixup-help-message Lisp function can call
 2323          mouse_position_hook, which resets the mouse_moved flags.
 2324          This causes trouble if we are trying to read a mouse motion
 2325          event (i.e., if we are inside a `track-mouse' form), so we
 2326          restore the mouse_moved flag.  */
 2327       FRAME_PTR f = NILP (do_mouse_tracking) ? NULL : some_mouse_moved ();
 2328       help = call1 (Qmouse_fixup_help_message, help);
 2329       if (f)
 2330         f->mouse_moved = 1;
 2331     }
 2332 #endif
 2333 
 2334   if (STRINGP (help) || NILP (help))
 2335     {
 2336       if (!NILP (Vshow_help_function))
 2337         call1 (Vshow_help_function, help);
 2338       help_echo_showing_p = STRINGP (help);
 2339     }
 2340 }
 2341 
 2342 
 2343 
 2344 /* Input of single characters from keyboard */
 2345 
 2346 Lisp_Object print_help ();
 2347 static Lisp_Object kbd_buffer_get_event ();
 2348 static void record_char ();
 2349 
 2350 static Lisp_Object help_form_saved_window_configs;
 2351 static Lisp_Object
 2352 read_char_help_form_unwind (Lisp_Object arg)
 2353 {
 2354   Lisp_Object window_config = XCAR (help_form_saved_window_configs);
 2355   help_form_saved_window_configs = XCDR (help_form_saved_window_configs);
 2356   if (!NILP (window_config))
 2357     Fset_window_configuration (window_config);
 2358   return Qnil;
 2359 }
 2360 
 2361 #define STOP_POLLING                                    \
 2362 do { if (! polling_stopped_here) stop_polling ();       \
 2363        polling_stopped_here = 1; } while (0)
 2364 
 2365 #define RESUME_POLLING                                  \
 2366 do { if (polling_stopped_here) start_polling ();        \
 2367        polling_stopped_here = 0; } while (0)
 2368 
 2369 /* read a character from the keyboard; call the redisplay if needed */
 2370 /* commandflag 0 means do not do auto-saving, but do do redisplay.
 2371    -1 means do not do redisplay, but do do autosaving.
 2372    1 means do both.  */
 2373 
 2374 /* The arguments MAPS and NMAPS are for menu prompting.
 2375    MAPS is an array of keymaps;  NMAPS is the length of MAPS.
 2376 
 2377    PREV_EVENT is the previous input event, or nil if we are reading
 2378    the first event of a key sequence (or not reading a key sequence).
 2379    If PREV_EVENT is t, that is a "magic" value that says
 2380    not to run input methods, but in other respects to act as if
 2381    not reading a key sequence.
 2382 
 2383    If USED_MOUSE_MENU is non-null, then we set *USED_MOUSE_MENU to 1
 2384    if we used a mouse menu to read the input, or zero otherwise.  If
 2385    USED_MOUSE_MENU is null, we don't dereference it.
 2386 
 2387    Value is -2 when we find input on another keyboard.  A second call
 2388    to read_char will read it.
 2389 
 2390    If END_TIME is non-null, it is a pointer to an EMACS_TIME
 2391    specifying the maximum time to wait until.  If no input arrives by
 2392    that time, stop waiting and return nil.
 2393 
 2394    Value is t if we showed a menu and the user rejected it.  */
 2395 
 2396 Lisp_Object
 2397 read_char (commandflag, nmaps, maps, prev_event, used_mouse_menu, end_time)
 2398      int commandflag;
 2399      int nmaps;
 2400      Lisp_Object *maps;
 2401      Lisp_Object prev_event;
 2402      int *used_mouse_menu;
 2403      EMACS_TIME *end_time;
 2404 {
 2405   volatile Lisp_Object c;
 2406   int count, jmpcount;
 2407   jmp_buf local_getcjmp;
 2408   jmp_buf save_jump;
 2409   volatile int key_already_recorded = 0;
 2410   Lisp_Object tem, save;
 2411   volatile Lisp_Object previous_echo_area_message;
 2412   volatile Lisp_Object also_record;
 2413   volatile int reread;
 2414   struct gcpro gcpro1, gcpro2;
 2415   int polling_stopped_here = 0;
 2416   struct kboard *orig_kboard = current_kboard;
 2417 
 2418   also_record = Qnil;
 2419 
 2420 #if 0  /* This was commented out as part of fixing echo for C-u left.  */
 2421   before_command_key_count = this_command_key_count;
 2422   before_command_echo_length = echo_length ();
 2423 #endif
 2424   c = Qnil;
 2425   previous_echo_area_message = Qnil;
 2426 
 2427   GCPRO2 (c, previous_echo_area_message);
 2428 
 2429  retry:
 2430 
 2431   reread = 0;
 2432   if (CONSP (Vunread_post_input_method_events))
 2433     {
 2434       c = XCAR (Vunread_post_input_method_events);
 2435       Vunread_post_input_method_events
 2436         = XCDR (Vunread_post_input_method_events);
 2437 
 2438       /* Undo what read_char_x_menu_prompt did when it unread
 2439          additional keys returned by Fx_popup_menu.  */
 2440       if (CONSP (c)
 2441           && (SYMBOLP (XCAR (c)) || INTEGERP (XCAR (c)))
 2442           && NILP (XCDR (c)))
 2443         c = XCAR (c);
 2444 
 2445       reread = 1;
 2446       goto reread_first;
 2447     }
 2448 
 2449   if (unread_command_char != -1)
 2450     {
 2451       XSETINT (c, unread_command_char);
 2452       unread_command_char = -1;
 2453 
 2454       reread = 1;
 2455       goto reread_first;
 2456     }
 2457 
 2458   if (CONSP (Vunread_command_events))
 2459     {
 2460       int was_disabled = 0;
 2461 
 2462       c = XCAR (Vunread_command_events);
 2463       Vunread_command_events = XCDR (Vunread_command_events);
 2464 
 2465       reread = 1;
 2466 
 2467       /* Undo what sit-for did when it unread additional keys
 2468          inside universal-argument.  */
 2469 
 2470       if (CONSP (c)
 2471           && EQ (XCAR (c), Qt))
 2472         {
 2473           reread = 0;
 2474           c = XCDR (c);
 2475         }
 2476 
 2477       /* Undo what read_char_x_menu_prompt did when it unread
 2478          additional keys returned by Fx_popup_menu.  */
 2479       if (CONSP (c)
 2480           && EQ (XCDR (c), Qdisabled)
 2481           && (SYMBOLP (XCAR (c)) || INTEGERP (XCAR (c))))
 2482         {
 2483           was_disabled = 1;
 2484           c = XCAR (c);
 2485         }
 2486 
 2487       /* If the queued event is something that used the mouse,
 2488          set used_mouse_menu accordingly.  */
 2489       if (used_mouse_menu
 2490           /* Also check was_disabled so last-nonmenu-event won't return
 2491              a bad value when submenus are involved.  (Bug#447)  */
 2492           && (EQ (c, Qtool_bar) || EQ (c, Qmenu_bar) || was_disabled))
 2493         *used_mouse_menu = 1;
 2494 
 2495       goto reread_for_input_method;
 2496     }
 2497 
 2498   if (CONSP (Vunread_input_method_events))
 2499     {
 2500       c = XCAR (Vunread_input_method_events);
 2501       Vunread_input_method_events = XCDR (Vunread_input_method_events);
 2502 
 2503       /* Undo what read_char_x_menu_prompt did when it unread
 2504          additional keys returned by Fx_popup_menu.  */
 2505       if (CONSP (c)
 2506           && (SYMBOLP (XCAR (c)) || INTEGERP (XCAR (c)))
 2507           && NILP (XCDR (c)))
 2508         c = XCAR (c);
 2509       reread = 1;
 2510       goto reread_for_input_method;
 2511     }
 2512 
 2513   this_command_key_count_reset = 0;
 2514 
 2515   if (!NILP (Vexecuting_kbd_macro))
 2516     {
 2517       /* We set this to Qmacro; since that's not a frame, nobody will
 2518          try to switch frames on us, and the selected window will
 2519          remain unchanged.
 2520 
 2521          Since this event came from a macro, it would be misleading to
 2522          leave internal_last_event_frame set to wherever the last
 2523          real event came from.  Normally, a switch-frame event selects
 2524          internal_last_event_frame after each command is read, but
 2525          events read from a macro should never cause a new frame to be
 2526          selected. */
 2527       Vlast_event_frame = internal_last_event_frame = Qmacro;
 2528 
 2529       /* Exit the macro if we are at the end.
 2530          Also, some things replace the macro with t
 2531          to force an early exit.  */
 2532       if (EQ (Vexecuting_kbd_macro, Qt)
 2533           || executing_kbd_macro_index >= XFASTINT (Flength (Vexecuting_kbd_macro)))
 2534         {
 2535           XSETINT (c, -1);
 2536           goto exit;
 2537         }
 2538 
 2539       c = Faref (Vexecuting_kbd_macro, make_number (executing_kbd_macro_index));
 2540       if (STRINGP (Vexecuting_kbd_macro)
 2541           && (XINT (c) & 0x80) && (XUINT (c) <= 0xff))
 2542         XSETFASTINT (c, CHAR_META | (XINT (c) & ~0x80));
 2543 
 2544       executing_kbd_macro_index++;
 2545 
 2546       goto from_macro;
 2547     }
 2548 
 2549   if (!NILP (unread_switch_frame))
 2550     {
 2551       c = unread_switch_frame;
 2552       unread_switch_frame = Qnil;
 2553 
 2554       /* This event should make it into this_command_keys, and get echoed
 2555          again, so we do not set `reread'.  */
 2556       goto reread_first;
 2557     }
 2558 
 2559   /* if redisplay was requested */
 2560   if (commandflag >= 0)
 2561     {
 2562       int echo_current = EQ (echo_message_buffer, echo_area_buffer[0]);
 2563 
 2564         /* If there is pending input, process any events which are not
 2565            user-visible, such as X selection_request events.  */
 2566       if (input_pending
 2567           || detect_input_pending_run_timers (0))
 2568         swallow_events (0);             /* may clear input_pending */
 2569 
 2570       /* Redisplay if no pending input.  */
 2571       while (!input_pending)
 2572         {
 2573           if (help_echo_showing_p && !EQ (selected_window, minibuf_window))
 2574             redisplay_preserve_echo_area (5);
 2575           else
 2576             redisplay ();
 2577 
 2578           if (!input_pending)
 2579             /* Normal case: no input arrived during redisplay.  */
 2580             break;
 2581 
 2582           /* Input arrived and pre-empted redisplay.
 2583              Process any events which are not user-visible.  */
 2584           swallow_events (0);
 2585           /* If that cleared input_pending, try again to redisplay.  */
 2586         }
 2587 
 2588       /* Prevent the redisplay we just did
 2589          from messing up echoing of the input after the prompt.  */
 2590       if (commandflag == 0 && echo_current)
 2591         echo_message_buffer = echo_area_buffer[0];
 2592 
 2593     }
 2594 
 2595   /* Message turns off echoing unless more keystrokes turn it on again.
 2596 
 2597      The code in 20.x for the condition was
 2598 
 2599      1. echo_area_glyphs && *echo_area_glyphs
 2600      2. && echo_area_glyphs != current_kboard->echobuf
 2601      3. && ok_to_echo_at_next_pause != echo_area_glyphs
 2602 
 2603      (1) means there's a current message displayed
 2604 
 2605      (2) means it's not the message from echoing from the current
 2606      kboard.
 2607 
 2608      (3) There's only one place in 20.x where ok_to_echo_at_next_pause
 2609      is set to a non-null value.  This is done in read_char and it is
 2610      set to echo_area_glyphs after a call to echo_char.  That means
 2611      ok_to_echo_at_next_pause is either null or
 2612      current_kboard->echobuf with the appropriate current_kboard at
 2613      that time.
 2614 
 2615      So, condition (3) means in clear text ok_to_echo_at_next_pause
 2616      must be either null, or the current message isn't from echoing at
 2617      all, or it's from echoing from a different kboard than the
 2618      current one.  */
 2619 
 2620   if (/* There currently is something in the echo area.  */
 2621       !NILP (echo_area_buffer[0])
 2622       && (/* And it's either not from echoing.  */
 2623           !EQ (echo_area_buffer[0], echo_message_buffer)
 2624           /* Or it's an echo from a different kboard.  */
 2625           || echo_kboard != current_kboard
 2626           /* Or we explicitly allow overwriting whatever there is.  */
 2627           || ok_to_echo_at_next_pause == NULL))
 2628     cancel_echoing ();
 2629   else
 2630     echo_dash ();
 2631 
 2632   /* Try reading a character via menu prompting in the minibuf.
 2633      Try this before the sit-for, because the sit-for
 2634      would do the wrong thing if we are supposed to do
 2635      menu prompting. If EVENT_HAS_PARAMETERS then we are reading
 2636      after a mouse event so don't try a minibuf menu. */
 2637   c = Qnil;
 2638   if (nmaps > 0 && INTERACTIVE
 2639       && !NILP (prev_event) && ! EVENT_HAS_PARAMETERS (prev_event)
 2640       /* Don't bring up a menu if we already have another event.  */
 2641       && NILP (Vunread_command_events)
 2642       && unread_command_char < 0
 2643       && !detect_input_pending_run_timers (0))
 2644     {
 2645       c = read_char_minibuf_menu_prompt (commandflag, nmaps, maps);
 2646 
 2647       if (INTEGERP (c) && XINT (c) == -2)
 2648         return c;               /* wrong_kboard_jmpbuf */
 2649 
 2650       if (! NILP (c))
 2651         {
 2652           key_already_recorded = 1;
 2653           goto non_reread_1;
 2654         }
 2655     }
 2656 
 2657   /* Make a longjmp point for quits to use, but don't alter getcjmp just yet.
 2658      We will do that below, temporarily for short sections of code,
 2659      when appropriate.  local_getcjmp must be in effect
 2660      around any call to sit_for or kbd_buffer_get_event;
 2661      it *must not* be in effect when we call redisplay.  */
 2662 
 2663   jmpcount = SPECPDL_INDEX ();
 2664   if (_setjmp (local_getcjmp))
 2665     {
 2666       /* Handle quits while reading the keyboard.  */
 2667       /* We must have saved the outer value of getcjmp here,
 2668          so restore it now.  */
 2669       restore_getcjmp (save_jump);
 2670       unbind_to (jmpcount, Qnil);
 2671       XSETINT (c, quit_char);
 2672       internal_last_event_frame = selected_frame;
 2673       Vlast_event_frame = internal_last_event_frame;
 2674       /* If we report the quit char as an event,
 2675          don't do so more than once.  */
 2676       if (!NILP (Vinhibit_quit))
 2677         Vquit_flag = Qnil;
 2678 
 2679       {
 2680         KBOARD *kb = FRAME_KBOARD (XFRAME (selected_frame));
 2681         if (kb != current_kboard)
 2682           {
 2683             Lisp_Object link = kb->kbd_queue;
 2684             /* We shouldn't get here if we were in single-kboard mode!  */
 2685             if (single_kboard)
 2686               abort ();
 2687             if (CONSP (link))
 2688               {
 2689                 while (CONSP (XCDR (link)))
 2690                   link = XCDR (link);
 2691                 if (!NILP (XCDR (link)))
 2692                   abort ();
 2693               }
 2694             if (!CONSP (link))
 2695               kb->kbd_queue = Fcons (c, Qnil);
 2696             else
 2697               XSETCDR (link, Fcons (c, Qnil));
 2698             kb->kbd_queue_has_data = 1;
 2699             current_kboard = kb;
 2700             /* This is going to exit from read_char
 2701                so we had better get rid of this frame's stuff.  */
 2702             UNGCPRO;
 2703             return make_number (-2); /* wrong_kboard_jmpbuf */
 2704           }
 2705       }
 2706       goto non_reread;
 2707     }
 2708 
 2709   /* Start idle timers if no time limit is supplied.  We don't do it
 2710      if a time limit is supplied to avoid an infinite recursion in the
 2711      situation where an idle timer calls `sit-for'.  */
 2712 
 2713   if (!end_time)
 2714     timer_start_idle ();
 2715 
 2716   /* If in middle of key sequence and minibuffer not active,
 2717      start echoing if enough time elapses.  */
 2718 
 2719   if (minibuf_level == 0
 2720       && !end_time
 2721       && !current_kboard->immediate_echo
 2722       && this_command_key_count > 0
 2723       && ! noninteractive
 2724       && (FLOATP (Vecho_keystrokes) || INTEGERP (Vecho_keystrokes))
 2725       && NILP (Fzerop (Vecho_keystrokes))
 2726       && (/* No message.  */
 2727           NILP (echo_area_buffer[0])
 2728           /* Or empty message.  */
 2729           || (BUF_BEG (XBUFFER (echo_area_buffer[0]))
 2730               == BUF_Z (XBUFFER (echo_area_buffer[0])))
 2731           /* Or already echoing from same kboard.  */
 2732           || (echo_kboard && ok_to_echo_at_next_pause == echo_kboard)
 2733           /* Or not echoing before and echoing allowed.  */
 2734           || (!echo_kboard && ok_to_echo_at_next_pause)))
 2735     {
 2736       /* After a mouse event, start echoing right away.
 2737          This is because we are probably about to display a menu,
 2738          and we don't want to delay before doing so.  */
 2739       if (EVENT_HAS_PARAMETERS (prev_event))
 2740         echo_now ();
 2741       else
 2742         {
 2743           Lisp_Object tem0;
 2744 
 2745           save_getcjmp (save_jump);
 2746           restore_getcjmp (local_getcjmp);
 2747           tem0 = sit_for (Vecho_keystrokes, 1, 1);
 2748           restore_getcjmp (save_jump);
 2749           if (EQ (tem0, Qt)
 2750               && ! CONSP (Vunread_command_events))
 2751             echo_now ();
 2752         }
 2753     }
 2754 
 2755   /* Maybe auto save due to number of keystrokes.  */
 2756 
 2757   if (commandflag != 0
 2758       && auto_save_interval > 0
 2759       && num_nonmacro_input_events - last_auto_save > max (auto_save_interval, 20)
 2760       && !detect_input_pending_run_timers (0))
 2761     {
 2762       Fdo_auto_save (Qnil, Qnil);
 2763       /* Hooks can actually change some buffers in auto save.  */
 2764       redisplay ();
 2765     }
 2766 
 2767   /* Try reading using an X menu.
 2768      This is never confused with reading using the minibuf
 2769      because the recursive call of read_char in read_char_minibuf_menu_prompt
 2770      does not pass on any keymaps.  */
 2771 
 2772   if (nmaps > 0 && INTERACTIVE
 2773       && !NILP (prev_event)
 2774       && EVENT_HAS_PARAMETERS (prev_event)
 2775       && !EQ (XCAR (prev_event), Qmenu_bar)
 2776       && !EQ (XCAR (prev_event), Qtool_bar)
 2777       /* Don't bring up a menu if we already have another event.  */
 2778       && NILP (Vunread_command_events)
 2779       && unread_command_char < 0)
 2780     {
 2781       c = read_char_x_menu_prompt (nmaps, maps, prev_event, used_mouse_menu);
 2782 
 2783       /* Now that we have read an event, Emacs is not idle.  */
 2784       if (!end_time)
 2785         timer_stop_idle ();
 2786 
 2787       goto exit;
 2788     }
 2789 
 2790   /* Maybe autosave and/or garbage collect due to idleness.  */
 2791 
 2792   if (INTERACTIVE && NILP (c))
 2793     {
 2794       int delay_level, buffer_size;
 2795 
 2796       /* Slow down auto saves logarithmically in size of current buffer,
 2797          and garbage collect while we're at it.  */
 2798       if (! MINI_WINDOW_P (XWINDOW (selected_window)))
 2799         last_non_minibuf_size = Z - BEG;
 2800       buffer_size = (last_non_minibuf_size >> 8) + 1;
 2801       delay_level = 0;
 2802       while (buffer_size > 64)
 2803         delay_level++, buffer_size -= buffer_size >> 2;
 2804       if (delay_level < 4) delay_level = 4;
 2805       /* delay_level is 4 for files under around 50k, 7 at 100k,
 2806          9 at 200k, 11 at 300k, and 12 at 500k.  It is 15 at 1 meg.  */
 2807 
 2808       /* Auto save if enough time goes by without input.  */
 2809       if (commandflag != 0
 2810           && num_nonmacro_input_events > last_auto_save
 2811           && INTEGERP (Vauto_save_timeout)
 2812           && XINT (Vauto_save_timeout) > 0)
 2813         {
 2814           Lisp_Object tem0;
 2815           int timeout = delay_level * XFASTINT (Vauto_save_timeout) / 4;
 2816 
 2817           save_getcjmp (save_jump);
 2818           restore_getcjmp (local_getcjmp);
 2819           tem0 = sit_for (make_number (timeout), 1, 1);
 2820           restore_getcjmp (save_jump);
 2821 
 2822           if (EQ (tem0, Qt)
 2823               && ! CONSP (Vunread_command_events))
 2824             {
 2825               Fdo_auto_save (Qnil, Qnil);
 2826 
 2827               /* If we have auto-saved and there is still no input
 2828                  available, garbage collect if there has been enough
 2829                  consing going on to make it worthwhile.  */
 2830               if (!detect_input_pending_run_timers (0)
 2831                   && consing_since_gc > gc_cons_threshold / 2)
 2832                 Fgarbage_collect ();
 2833 
 2834               redisplay ();
 2835             }
 2836         }
 2837     }
 2838 
 2839   /* Notify the caller if an autosave hook, or a timer, sentinel or
 2840      filter in the sit_for calls above have changed the current
 2841      kboard.  This could happen if they use the minibuffer or start a
 2842      recursive edit, like the fancy splash screen in server.el's
 2843      filter.  If this longjmp wasn't here, read_key_sequence would
 2844      interpret the next key sequence using the wrong translation
 2845      tables and function keymaps.  */
 2846   if (NILP (c) && current_kboard != orig_kboard)
 2847     {
 2848       UNGCPRO;
 2849       return make_number (-2);  /* wrong_kboard_jmpbuf */
 2850     }
 2851 
 2852   /* If this has become non-nil here, it has been set by a timer
 2853      or sentinel or filter.  */
 2854   if (CONSP (Vunread_command_events))
 2855     {
 2856       c = XCAR (Vunread_command_events);
 2857       Vunread_command_events = XCDR (Vunread_command_events);
 2858     }
 2859 
 2860   /* Read something from current KBOARD's side queue, if possible.  */
 2861 
 2862   if (NILP (c))
 2863     {
 2864       if (current_kboard->kbd_queue_has_data)
 2865         {
 2866           if (!CONSP (current_kboard->kbd_queue))
 2867             abort ();
 2868           c = XCAR (current_kboard->kbd_queue);
 2869           current_kboard->kbd_queue
 2870             = XCDR (current_kboard->kbd_queue);
 2871           if (NILP (current_kboard->kbd_queue))
 2872             current_kboard->kbd_queue_has_data = 0;
 2873           input_pending = readable_events (0);
 2874           if (EVENT_HAS_PARAMETERS (c)
 2875               && EQ (EVENT_HEAD_KIND (EVENT_HEAD (c)), Qswitch_frame))
 2876             internal_last_event_frame = XCAR (XCDR (c));
 2877           Vlast_event_frame = internal_last_event_frame;
 2878         }
 2879     }
 2880 
 2881   /* If current_kboard's side queue is empty check the other kboards.
 2882      If one of them has data that we have not yet seen here,
 2883      switch to it and process the data waiting for it.
 2884 
 2885      Note: if the events queued up for another kboard
 2886      have already been seen here, and therefore are not a complete command,
 2887      the kbd_queue_has_data field is 0, so we skip that kboard here.
 2888      That's to avoid an infinite loop switching between kboards here.  */
 2889   if (NILP (c) && !single_kboard)
 2890     {
 2891       KBOARD *kb;
 2892       for (kb = all_kboards; kb; kb = kb->next_kboard)
 2893         if (kb->kbd_queue_has_data)
 2894           {
 2895             current_kboard = kb;
 2896             /* This is going to exit from read_char
 2897                so we had better get rid of this frame's stuff.  */
 2898             UNGCPRO;
 2899             return make_number (-2); /* wrong_kboard_jmpbuf */
 2900           }
 2901     }
 2902 
 2903  wrong_kboard:
 2904 
 2905   STOP_POLLING;
 2906 
 2907   /* Finally, we read from the main queue,
 2908      and if that gives us something we can't use yet, we put it on the
 2909      appropriate side queue and try again.  */
 2910 
 2911   if (NILP (c))
 2912     {
 2913       KBOARD *kb;
 2914 
 2915       if (end_time)
 2916         {
 2917           EMACS_TIME now;
 2918           EMACS_GET_TIME (now);
 2919           if (EMACS_TIME_GE (now, *end_time))
 2920             goto exit;
 2921         }
 2922 
 2923       /* Actually read a character, waiting if necessary.  */
 2924       save_getcjmp (save_jump);
 2925       restore_getcjmp (local_getcjmp);
 2926       if (!end_time)
 2927         timer_start_idle ();
 2928       c = kbd_buffer_get_event (&kb, used_mouse_menu, end_time);
 2929       restore_getcjmp (save_jump);
 2930 
 2931       if (! NILP (c) && (kb != current_kboard))
 2932         {
 2933           Lisp_Object link = kb->kbd_queue;
 2934           if (CONSP (link))
 2935             {
 2936               while (CONSP (XCDR (link)))
 2937                 link = XCDR (link);
 2938               if (!NILP (XCDR (link)))
 2939                 abort ();
 2940             }
 2941           if (!CONSP (link))
 2942             kb->kbd_queue = Fcons (c, Qnil);
 2943           else
 2944             XSETCDR (link, Fcons (c, Qnil));
 2945           kb->kbd_queue_has_data = 1;
 2946           c = Qnil;
 2947           if (single_kboard)
 2948             goto wrong_kboard;
 2949           current_kboard = kb;
 2950           /* This is going to exit from read_char
 2951              so we had better get rid of this frame's stuff.  */
 2952           UNGCPRO;
 2953           return make_number (-2);
 2954         }
 2955     }
 2956 
 2957   /* Terminate Emacs in batch mode if at eof.  */
 2958   if (noninteractive && INTEGERP (c) && XINT (c) < 0)
 2959     Fkill_emacs (make_number (1));
 2960 
 2961   if (INTEGERP (c))
 2962     {
 2963       /* Add in any extra modifiers, where appropriate.  */
 2964       if ((extra_keyboard_modifiers & CHAR_CTL)
 2965           || ((extra_keyboard_modifiers & 0177) < ' '
 2966               && (extra_keyboard_modifiers & 0177) != 0))
 2967         XSETINT (c, make_ctrl_char (XINT (c)));
 2968 
 2969       /* Transfer any other modifier bits directly from
 2970          extra_keyboard_modifiers to c.  Ignore the actual character code
 2971          in the low 16 bits of extra_keyboard_modifiers.  */
 2972       XSETINT (c, XINT (c) | (extra_keyboard_modifiers & ~0xff7f & ~CHAR_CTL));
 2973     }
 2974 
 2975  non_reread:
 2976 
 2977   if (!end_time)
 2978     timer_stop_idle ();
 2979   RESUME_POLLING;
 2980 
 2981   if (NILP (c))
 2982     {
 2983       if (commandflag >= 0
 2984           && !input_pending && !detect_input_pending_run_timers (0))
 2985         redisplay ();
 2986 
 2987       goto wrong_kboard;
 2988     }
 2989 
 2990  non_reread_1:
 2991 
 2992   /* Buffer switch events are only for internal wakeups
 2993      so don't show them to the user.
 2994      Also, don't record a key if we already did.  */
 2995   if (BUFFERP (c) || key_already_recorded)
 2996     goto exit;
 2997 
 2998   /* Process special events within read_char
 2999      and loop around to read another event.  */
 3000   save = Vquit_flag;
 3001   Vquit_flag = Qnil;
 3002   tem = access_keymap (get_keymap (Vspecial_event_map, 0, 1), c, 0, 0, 1);
 3003   Vquit_flag = save;
 3004 
 3005   if (!NILP (tem))
 3006     {
 3007       struct buffer *prev_buffer = current_buffer;
 3008 #if 0 /* This shouldn't be necessary anymore. --lorentey  */
 3009       int was_locked = single_kboard;
 3010       int count = SPECPDL_INDEX ();
 3011       record_single_kboard_state ();
 3012 #endif
 3013 
 3014       last_input_event = c;
 3015       Fcommand_execute (tem, Qnil, Fvector (1, &last_input_event), Qt);
 3016 
 3017       if (CONSP (c) && EQ (XCAR (c), Qselect_window) && !end_time)
 3018         /* We stopped being idle for this event; undo that.  This
 3019            prevents automatic window selection (under
 3020            mouse_autoselect_window from acting as a real input event, for
 3021            example banishing the mouse under mouse-avoidance-mode.  */
 3022         timer_resume_idle ();
 3023 
 3024 #if 0 /* This shouldn't be necessary anymore. --lorentey  */
 3025       /* Resume allowing input from any kboard, if that was true before.  */
 3026       if (!was_locked)
 3027         any_kboard_state ();
 3028       unbind_to (count, Qnil);
 3029 #endif
 3030 
 3031       if (current_buffer != prev_buffer)
 3032         {
 3033           /* The command may have changed the keymaps.  Pretend there
 3034              is input in another keyboard and return.  This will
 3035              recalculate keymaps.  */
 3036           c = make_number (-2);
 3037           goto exit;
 3038         }
 3039       else
 3040         goto retry;
 3041     }
 3042 
 3043   /* Handle things that only apply to characters.  */
 3044   if (INTEGERP (c))
 3045     {
 3046       /* If kbd_buffer_get_event gave us an EOF, return that.  */
 3047       if (XINT (c) == -1)
 3048         goto exit;
 3049 
 3050       if ((STRINGP (current_kboard->Vkeyboard_translate_table)
 3051            && SCHARS (current_kboard->Vkeyboard_translate_table) > (unsigned) XFASTINT (c))
 3052           || (VECTORP (current_kboard->Vkeyboard_translate_table)
 3053               && XVECTOR (current_kboard->Vkeyboard_translate_table)->size > (unsigned) XFASTINT (c))
 3054           || (CHAR_TABLE_P (current_kboard->Vkeyboard_translate_table)
 3055               && CHARACTERP (c)))
 3056         {
 3057           Lisp_Object d;
 3058           d = Faref (current_kboard->Vkeyboard_translate_table, c);
 3059           /* nil in keyboard-translate-table means no translation.  */
 3060           if (!NILP (d))
 3061             c = d;
 3062         }
 3063     }
 3064 
 3065   /* If this event is a mouse click in the menu bar,
 3066      return just menu-bar for now.  Modify the mouse click event
 3067      so we won't do this twice, then queue it up.  */
 3068   if (EVENT_HAS_PARAMETERS (c)
 3069       && CONSP (XCDR (c))
 3070       && CONSP (EVENT_START (c))
 3071       && CONSP (XCDR (EVENT_START (c))))
 3072     {
 3073       Lisp_Object posn;
 3074 
 3075       posn = POSN_POSN (EVENT_START (c));
 3076       /* Handle menu-bar events:
 3077          insert the dummy prefix event `menu-bar'.  */
 3078       if (EQ (posn, Qmenu_bar) || EQ (posn, Qtool_bar))
 3079         {
 3080           /* Change menu-bar to (menu-bar) as the event "position".  */
 3081           POSN_SET_POSN (EVENT_START (c), Fcons (posn, Qnil));
 3082 
 3083           also_record = c;
 3084           Vunread_command_events = Fcons (c, Vunread_command_events);
 3085           c = posn;
 3086         }
 3087     }
 3088 
 3089   /* Store these characters into recent_keys, the dribble file if any,
 3090      and the keyboard macro being defined, if any.  */
 3091   record_char (c);
 3092   if (! NILP (also_record))
 3093     record_char (also_record);
 3094 
 3095   /* Wipe the echo area.
 3096      But first, if we are about to use an input method,
 3097      save the echo area contents for it to refer to.  */
 3098   if (INTEGERP (c)
 3099       && ! NILP (Vinput_method_function)
 3100       && (unsigned) XINT (c) >= ' '
 3101       && (unsigned) XINT (c) != 127
 3102       && (unsigned) XINT (c) < 256)
 3103     {
 3104       previous_echo_area_message = Fcurrent_message ();
 3105       Vinput_method_previous_message = previous_echo_area_message;
 3106     }
 3107 
 3108   /* Now wipe the echo area, except for help events which do their
 3109      own stuff with the echo area.  */
 3110   if (!CONSP (c)
 3111       || (!(EQ (Qhelp_echo, XCAR (c)))
 3112           && !(EQ (Qswitch_frame, XCAR (c)))))
 3113     {
 3114       if (!NILP (echo_area_buffer[0]))
 3115         safe_run_hooks (Qecho_area_clear_hook);
 3116       clear_message (1, 0);
 3117     }
 3118 
 3119  reread_for_input_method:
 3120  from_macro:
 3121   /* Pass this to the input method, if appropriate.  */
 3122   if (INTEGERP (c)
 3123       && ! NILP (Vinput_method_function)
 3124       /* Don't run the input method within a key sequence,
 3125          after the first event of the key sequence.  */
 3126       && NILP (prev_event)
 3127       && (unsigned) XINT (c) >= ' '
 3128       && (unsigned) XINT (c) != 127
 3129       && (unsigned) XINT (c) < 256)
 3130     {
 3131       Lisp_Object keys;
 3132       int key_count, key_count_reset;
 3133       struct gcpro gcpro1;
 3134       int count = SPECPDL_INDEX ();
 3135 
 3136       /* Save the echo status.  */
 3137       int saved_immediate_echo = current_kboard->immediate_echo;
 3138       struct kboard *saved_ok_to_echo = ok_to_echo_at_next_pause;
 3139       Lisp_Object saved_echo_string = current_kboard->echo_string;
 3140       int saved_echo_after_prompt = current_kboard->echo_after_prompt;
 3141 
 3142 #if 0
 3143       if (before_command_restore_flag)
 3144         {
 3145           this_command_key_count = before_command_key_count_1;
 3146           if (this_command_key_count < this_single_command_key_start)
 3147             this_single_command_key_start = this_command_key_count;
 3148           echo_truncate (before_command_echo_length_1);
 3149           before_command_restore_flag = 0;
 3150         }
 3151 #endif
 3152 
 3153       /* Save the this_command_keys status.  */
 3154       key_count = this_command_key_count;
 3155       key_count_reset = this_command_key_count_reset;
 3156 
 3157       if (key_count > 0)
 3158         keys = Fcopy_sequence (this_command_keys);
 3159       else
 3160         keys = Qnil;
 3161       GCPRO1 (keys);
 3162 
 3163       /* Clear out this_command_keys.  */
 3164       this_command_key_count = 0;
 3165       this_command_key_count_reset = 0;
 3166 
 3167       /* Now wipe the echo area.  */
 3168       if (!NILP (echo_area_buffer[0]))
 3169         safe_run_hooks (Qecho_area_clear_hook);
 3170       clear_message (1, 0);
 3171       echo_truncate (0);
 3172 
 3173       /* If we are not reading a key sequence,
 3174          never use the echo area.  */
 3175       if (maps == 0)
 3176         {
 3177           specbind (Qinput_method_use_echo_area, Qt);
 3178         }
 3179 
 3180       /* Call the input method.  */
 3181       tem = call1 (Vinput_method_function, c);
 3182 
 3183       tem = unbind_to (count, tem);
 3184 
 3185       /* Restore the saved echoing state
 3186          and this_command_keys state.  */
 3187       this_command_key_count = key_count;
 3188       this_command_key_count_reset = key_count_reset;
 3189       if (key_count > 0)
 3190         this_command_keys = keys;
 3191 
 3192       cancel_echoing ();
 3193       ok_to_echo_at_next_pause = saved_ok_to_echo;
 3194       current_kboard->echo_string = saved_echo_string;
 3195       current_kboard->echo_after_prompt = saved_echo_after_prompt;
 3196       if (saved_immediate_echo)
 3197         echo_now ();
 3198 
 3199       UNGCPRO;
 3200 
 3201       /* The input method can return no events.  */
 3202       if (! CONSP (tem))
 3203         {
 3204           /* Bring back the previous message, if any.  */
 3205           if (! NILP (previous_echo_area_message))
 3206             message_with_string ("%s", previous_echo_area_message, 0);
 3207           goto retry;
 3208         }
 3209       /* It returned one event or more.  */
 3210       c = XCAR (tem);
 3211       Vunread_post_input_method_events
 3212         = nconc2 (XCDR (tem), Vunread_post_input_method_events);
 3213     }
 3214 
 3215  reread_first:
 3216 
 3217   /* Display help if not echoing.  */
 3218   if (CONSP (c) && EQ (XCAR (c), Qhelp_echo))
 3219     {
 3220       /* (help-echo FRAME HELP WINDOW OBJECT POS).  */
 3221       Lisp_Object help, object, position, window, tem;
 3222 
 3223       tem = Fcdr (XCDR (c));
 3224       help = Fcar (tem);
 3225       tem = Fcdr (tem);
 3226       window = Fcar (tem);
 3227       tem = Fcdr (tem);
 3228       object = Fcar (tem);
 3229       tem = Fcdr (tem);
 3230       position = Fcar (tem);
 3231 
 3232       show_help_echo (help, window, object, position, 0);
 3233 
 3234       /* We stopped being idle for this event; undo that.  */
 3235       if (!end_time)
 3236         timer_resume_idle ();
 3237       goto retry;
 3238     }
 3239 
 3240   if ((! reread || this_command_key_count == 0
 3241        || this_command_key_count_reset)
 3242       && !end_time)
 3243     {
 3244 
 3245       /* Don't echo mouse motion events.  */
 3246       if ((FLOATP (Vecho_keystrokes) || INTEGERP (Vecho_keystrokes))
 3247           && NILP (Fzerop (Vecho_keystrokes))
 3248           && ! (EVENT_HAS_PARAMETERS (c)
 3249                 && EQ (EVENT_HEAD_KIND (EVENT_HEAD (c)), Qmouse_movement)))
 3250         {
 3251           echo_char (c);
 3252           if (! NILP (also_record))
 3253             echo_char (also_record);
 3254           /* Once we reread a character, echoing can happen
 3255              the next time we pause to read a new one.  */
 3256           ok_to_echo_at_next_pause = current_kboard;
 3257         }
 3258 
 3259       /* Record this character as part of the current key.  */
 3260       add_command_key (c);
 3261       if (! NILP (also_record))
 3262         add_command_key (also_record);
 3263     }
 3264 
 3265   last_input_event = c;
 3266   num_input_events++;
 3267 
 3268   /* Process the help character specially if enabled */
 3269   if (!NILP (Vhelp_form) && help_char_p (c))
 3270     {
 3271       Lisp_Object tem0;
 3272       count = SPECPDL_INDEX ();
 3273 
 3274       help_form_saved_window_configs
 3275         = Fcons (Fcurrent_window_configuration (Qnil),
 3276                  help_form_saved_window_configs);
 3277       record_unwind_protect (read_char_help_form_unwind, Qnil);
 3278 
 3279       tem0 = Feval (Vhelp_form);
 3280       if (STRINGP (tem0))
 3281         internal_with_output_to_temp_buffer ("*Help*", print_help, tem0);
 3282 
 3283       cancel_echoing ();
 3284       do
 3285         {
 3286           c = read_char (0, 0, 0, Qnil, 0, NULL);
 3287           if (EVENT_HAS_PARAMETERS (c)
 3288               && EQ (EVENT_HEAD_KIND (EVENT_HEAD (c)), Qmouse_click))
 3289             XSETCAR (help_form_saved_window_configs, Qnil);
 3290         }
 3291       while (BUFFERP (c));
 3292       /* Remove the help from the frame */
 3293       unbind_to (count, Qnil);
 3294 
 3295       redisplay ();
 3296       if (EQ (c, make_number (040)))
 3297         {
 3298           cancel_echoing ();
 3299           do
 3300             c = read_char (0, 0, 0, Qnil, 0, NULL);
 3301           while (BUFFERP (c));
 3302         }
 3303     }
 3304 
 3305  exit:
 3306   RESUME_POLLING;
 3307   RETURN_UNGCPRO (c);
 3308 }
 3309 
 3310 /* Record a key that came from a mouse menu.
 3311    Record it for echoing, for this-command-keys, and so on.  */
 3312 
 3313 static void
 3314 record_menu_key (c)
 3315      Lisp_Object c;
 3316 {
 3317   /* Wipe the echo area.  */
 3318   clear_message (1, 0);
 3319 
 3320   record_char (c);
 3321 
 3322 #if 0
 3323   before_command_key_count = this_command_key_count;
 3324   before_command_echo_length = echo_length ();
 3325 #endif
 3326 
 3327   /* Don't echo mouse motion events.  */
 3328   if ((FLOATP (Vecho_keystrokes) || INTEGERP (Vecho_keystrokes))
 3329       && NILP (Fzerop (Vecho_keystrokes)))
 3330     {
 3331       echo_char (c);
 3332 
 3333       /* Once we reread a character, echoing can happen
 3334          the next time we pause to read a new one.  */
 3335       ok_to_echo_at_next_pause = 0;
 3336     }
 3337 
 3338   /* Record this character as part of the current key.  */
 3339   add_command_key (c);
 3340 
 3341   /* Re-reading in the middle of a command */
 3342   last_input_event = c;
 3343   num_input_events++;
 3344 }
 3345 
 3346 /* Return 1 if should recognize C as "the help character".  */
 3347 
 3348 int
 3349 help_char_p (c)
 3350      Lisp_Object c;
 3351 {
 3352   Lisp_Object tail;
 3353 
 3354   if (EQ (c, Vhelp_char))
 3355     return 1;
 3356   for (tail = Vhelp_event_list; CONSP (tail); tail = XCDR (tail))
 3357     if (EQ (c, XCAR (tail)))
 3358       return 1;
 3359   return 0;
 3360 }
 3361 
 3362 /* Record the input event C in various ways.  */
 3363 
 3364 static void
 3365 record_char (c)
 3366      Lisp_Object c;
 3367 {
 3368   int recorded = 0;
 3369 
 3370   if (CONSP (c) && (EQ (XCAR (c), Qhelp_echo) || EQ (XCAR (c), Qmouse_movement)))
 3371     {
 3372       /* To avoid filling recent_keys with help-echo and mouse-movement
 3373          events, we filter out repeated help-echo events, only store the
 3374          first and last in a series of mouse-movement events, and don't
 3375          store repeated help-echo events which are only separated by
 3376          mouse-movement events.  */
 3377 
 3378       Lisp_Object ev1, ev2, ev3;
 3379       int ix1, ix2, ix3;
 3380 
 3381       if ((ix1 = recent_keys_index - 1) < 0)
 3382         ix1 = NUM_RECENT_KEYS - 1;
 3383       ev1 = AREF (recent_keys, ix1);
 3384 
 3385       if ((ix2 = ix1 - 1) < 0)
 3386         ix2 = NUM_RECENT_KEYS - 1;
 3387       ev2 = AREF (recent_keys, ix2);
 3388 
 3389       if ((ix3 = ix2 - 1) < 0)
 3390         ix3 = NUM_RECENT_KEYS - 1;
 3391       ev3 = AREF (recent_keys, ix3);
 3392 
 3393       if (EQ (XCAR (c), Qhelp_echo))
 3394         {
 3395           /* Don't record `help-echo' in recent_keys unless it shows some help
 3396              message, and a different help than the previously recorded
 3397              event.  */
 3398           Lisp_Object help, last_help;
 3399 
 3400           help = Fcar_safe (Fcdr_safe (XCDR (c)));
 3401           if (!STRINGP (help))
 3402             recorded = 1;
 3403           else if (CONSP (ev1) && EQ (XCAR (ev1), Qhelp_echo)
 3404                    && (last_help = Fcar_safe (Fcdr_safe (XCDR (ev1))), EQ (last_help, help)))
 3405             recorded = 1;
 3406           else if (CONSP (ev1) && EQ (XCAR (ev1), Qmouse_movement)
 3407                    && CONSP (ev2) && EQ (XCAR (ev2), Qhelp_echo)
 3408                    && (last_help = Fcar_safe (Fcdr_safe (XCDR (ev2))), EQ (last_help, help)))
 3409             recorded = -1;
 3410           else if (CONSP (ev1) && EQ (XCAR (ev1), Qmouse_movement)
 3411                    && CONSP (ev2) && EQ (XCAR (ev2), Qmouse_movement)
 3412                    && CONSP (ev3) && EQ (XCAR (ev3), Qhelp_echo)
 3413                    && (last_help = Fcar_safe (Fcdr_safe (XCDR (ev3))), EQ (last_help, help)))
 3414             recorded = -2;
 3415         }
 3416       else if (EQ (XCAR (c), Qmouse_movement))
 3417         {
 3418           /* Only record one pair of `mouse-movement' on a window in recent_keys.
 3419              So additional mouse movement events replace the last element.  */
 3420           Lisp_Object last_window, window;
 3421 
 3422           window = Fcar_safe (Fcar_safe (XCDR (c)));
 3423           if (CONSP (ev1) && EQ (XCAR (ev1), Qmouse_movement)
 3424               && (last_window = Fcar_safe (Fcar_safe (XCDR (ev1))), EQ (last_window, window))
 3425               && CONSP (ev2) && EQ (XCAR (ev2), Qmouse_movement)
 3426               && (last_window = Fcar_safe (Fcar_safe (XCDR (ev2))), EQ (last_window, window)))
 3427             {
 3428               ASET (recent_keys, ix1, c);
 3429               recorded = 1;
 3430             }
 3431         }
 3432     }
 3433   else
 3434     store_kbd_macro_char (c);
 3435 
 3436   if (!recorded)
 3437     {
 3438       total_keys++;
 3439       ASET (recent_keys, recent_keys_index, c);
 3440       if (++recent_keys_index >= NUM_RECENT_KEYS)
 3441         recent_keys_index = 0;
 3442     }
 3443   else if (recorded < 0)
 3444     {
 3445       /* We need to remove one or two events from recent_keys.
 3446          To do this, we simply put nil at those events and move the
 3447          recent_keys_index backwards over those events.  Usually,
 3448          users will never see those nil events, as they will be
 3449          overwritten by the command keys entered to see recent_keys
 3450          (e.g. C-h l).  */
 3451 
 3452       while (recorded++ < 0 && total_keys > 0)
 3453         {
 3454           if (total_keys < NUM_RECENT_KEYS)
 3455             total_keys--;
 3456           if (--recent_keys_index < 0)
 3457             recent_keys_index = NUM_RECENT_KEYS - 1;
 3458           ASET (recent_keys, recent_keys_index, Qnil);
 3459         }
 3460     }
 3461 
 3462   num_nonmacro_input_events++;
 3463 
 3464   /* Write c to the dribble file.  If c is a lispy event, write
 3465      the event's symbol to the dribble file, in <brackets>.  Bleaugh.
 3466      If you, dear reader, have a better idea, you've got the source.  :-) */
 3467   if (dribble)
 3468     {
 3469       BLOCK_INPUT;
 3470       if (INTEGERP (c))
 3471         {
 3472           if (XUINT (c) < 0x100)
 3473             putc (XINT (c), dribble);
 3474           else
 3475             fprintf (dribble, " 0x%x", (int) XUINT (c));
 3476         }
 3477       else
 3478         {
 3479           Lisp_Object dribblee;
 3480 
 3481           /* If it's a structured event, take the event header.  */
 3482           dribblee = EVENT_HEAD (c);
 3483 
 3484           if (SYMBOLP (dribblee))
 3485             {
 3486               putc ('<', dribble);
 3487               fwrite (SDATA (SYMBOL_NAME (dribblee)), sizeof (char),
 3488                       SBYTES (SYMBOL_NAME (dribblee)),
 3489                       dribble);
 3490               putc ('>', dribble);
 3491             }
 3492         }
 3493 
 3494       fflush (dribble);
 3495       UNBLOCK_INPUT;
 3496     }
 3497 }
 3498 
 3499 Lisp_Object
 3500 print_help (object)
 3501      Lisp_Object object;
 3502 {
 3503   struct buffer *old = current_buffer;
 3504   Fprinc (object, Qnil);
 3505   set_buffer_internal (XBUFFER (Vstandard_output));
 3506   call0 (intern ("help-mode"));
 3507   set_buffer_internal (old);
 3508   return Qnil;
 3509 }
 3510 
 3511 /* Copy out or in the info on where C-g should throw to.
 3512    This is used when running Lisp code from within get_char,
 3513    in case get_char is called recursively.
 3514    See read_process_output.  */
 3515 
 3516 static void
 3517 save_getcjmp (temp)
 3518      jmp_buf temp;
 3519 {
 3520   bcopy (getcjmp, temp, sizeof getcjmp);
 3521 }
 3522 
 3523 static void
 3524 restore_getcjmp (temp)
 3525      jmp_buf temp;
 3526 {
 3527   bcopy (temp, getcjmp, sizeof getcjmp);
 3528 }
 3529 
 3530 /* Low level keyboard/mouse input.
 3531    kbd_buffer_store_event places events in kbd_buffer, and
 3532    kbd_buffer_get_event retrieves them.  */
 3533 
 3534 /* Return true if there are any events in the queue that read-char
 3535    would return.  If this returns false, a read-char would block.  */
 3536 static int
 3537 readable_events (flags)
 3538      int flags;
 3539 {
 3540 #ifdef HAVE_DBUS
 3541   /* Check whether a D-Bus message has arrived.  */
 3542   if (xd_pending_messages () > 0)
 3543     return 1;
 3544 #endif /* HAVE_DBUS */
 3545 
 3546   if (flags & READABLE_EVENTS_DO_TIMERS_NOW)
 3547     timer_check (1);
 3548 
 3549   /* If the buffer contains only FOCUS_IN_EVENT events, and
 3550      READABLE_EVENTS_FILTER_EVENTS is set, report it as empty.  */
 3551   if (kbd_fetch_ptr != kbd_store_ptr)
 3552     {
 3553       if (flags & (READABLE_EVENTS_FILTER_EVENTS
 3554 #ifdef USE_TOOLKIT_SCROLL_BARS
 3555                    | READABLE_EVENTS_IGNORE_SQUEEZABLES
 3556 #endif
 3557                    ))
 3558         {
 3559           struct input_event *event;
 3560 
 3561           event = ((kbd_fetch_ptr < kbd_buffer + KBD_BUFFER_SIZE)
 3562                    ? kbd_fetch_ptr
 3563                    : kbd_buffer);
 3564 
 3565           do
 3566             {
 3567               if (!(
 3568 #ifdef USE_TOOLKIT_SCROLL_BARS
 3569                     (flags & READABLE_EVENTS_FILTER_EVENTS) &&
 3570 #endif
 3571                     event->kind == FOCUS_IN_EVENT)
 3572 #ifdef USE_TOOLKIT_SCROLL_BARS
 3573                   && !((flags & READABLE_EVENTS_IGNORE_SQUEEZABLES)
 3574                        && event->kind == SCROLL_BAR_CLICK_EVENT
 3575                        && event->part == scroll_bar_handle
 3576                        && event->modifiers == 0)
 3577 #endif
 3578                   )
 3579                 return 1;
 3580               event++;
 3581               if (event == kbd_buffer + KBD_BUFFER_SIZE)
 3582                 event = kbd_buffer;
 3583             }
 3584           while (event != kbd_store_ptr);
 3585         }
 3586       else
 3587         return 1;
 3588     }
 3589 
 3590 #if defined (HAVE_MOUSE) || defined (HAVE_GPM)
 3591   if (!(flags & READABLE_EVENTS_IGNORE_SQUEEZABLES)
 3592       && !NILP (do_mouse_tracking) && some_mouse_moved ())
 3593     return 1;
 3594 #endif
 3595   if (single_kboard)
 3596     {
 3597       if (current_kboard->kbd_queue_has_data)
 3598         return 1;
 3599     }
 3600   else
 3601     {
 3602       KBOARD *kb;
 3603       for (kb = all_kboards; kb; kb = kb->next_kboard)
 3604         if (kb->kbd_queue_has_data)
 3605           return 1;
 3606     }
 3607   return 0;
 3608 }
 3609 
 3610 /* Set this for debugging, to have a way to get out */
 3611 int stop_character;
 3612 
 3613 static KBOARD *
 3614 event_to_kboard (event)
 3615      struct input_event *event;
 3616 {
 3617   Lisp_Object frame;
 3618   frame = event->frame_or_window;
 3619   if (CONSP (frame))
 3620     frame = XCAR (frame);
 3621   else if (WINDOWP (frame))
 3622     frame = WINDOW_FRAME (XWINDOW (frame));
 3623 
 3624   /* There are still some events that don't set this field.
 3625      For now, just ignore the problem.
 3626      Also ignore dead frames here.  */
 3627   if (!FRAMEP (frame) || !FRAME_LIVE_P (XFRAME (frame)))
 3628     return 0;
 3629   else
 3630     return FRAME_KBOARD (XFRAME (frame));
 3631 }
 3632 
 3633 
 3634 Lisp_Object Vthrow_on_input;
 3635 
 3636 /* Store an event obtained at interrupt level into kbd_buffer, fifo */
 3637 
 3638 void
 3639 kbd_buffer_store_event (event)
 3640      register struct input_event *event;
 3641 {
 3642   kbd_buffer_store_event_hold (event, 0);
 3643 }
 3644 
 3645 /* Store EVENT obtained at interrupt level into kbd_buffer, fifo.
 3646 
 3647    If HOLD_QUIT is 0, just stuff EVENT into the fifo.
 3648    Else, if HOLD_QUIT.kind != NO_EVENT, discard EVENT.
 3649    Else, if EVENT is a quit event, store the quit event
 3650    in HOLD_QUIT, and return (thus ignoring further events).
 3651 
 3652    This is used in read_avail_input to postpone the processing
 3653    of the quit event until all subsequent input events have been
 3654    parsed (and discarded).
 3655  */
 3656 
 3657 void
 3658 kbd_buffer_store_event_hold (event, hold_quit)
 3659      register struct input_event *event;
 3660      struct input_event *hold_quit;
 3661 {
 3662   if (event->kind == NO_EVENT)
 3663     abort ();
 3664 
 3665   if (hold_quit && hold_quit->kind != NO_EVENT)
 3666     return;
 3667 
 3668   if (event->kind == ASCII_KEYSTROKE_EVENT)
 3669     {
 3670       register int c = event->code & 0377;
 3671 
 3672       if (event->modifiers & ctrl_modifier)
 3673         c = make_ctrl_char (c);
 3674 
 3675       c |= (event->modifiers
 3676             & (meta_modifier | alt_modifier
 3677                | hyper_modifier | super_modifier));
 3678 
 3679       if (c == quit_char)
 3680         {
 3681           KBOARD *kb = FRAME_KBOARD (XFRAME (event->frame_or_window));
 3682           struct input_event *sp;
 3683 
 3684           if (single_kboard && kb != current_kboard)
 3685             {
 3686               kb->kbd_queue
 3687                 = Fcons (make_lispy_switch_frame (event->frame_or_window),
 3688                          Fcons (make_number (c), Qnil));
 3689               kb->kbd_queue_has_data = 1;
 3690               for (sp = kbd_fetch_ptr; sp != kbd_store_ptr; sp++)
 3691                 {
 3692                   if (sp == kbd_buffer + KBD_BUFFER_SIZE)
 3693                     sp = kbd_buffer;
 3694 
 3695                   if (event_to_kboard (sp) == kb)
 3696                     {
 3697                       sp->kind = NO_EVENT;
 3698                       sp->frame_or_window = Qnil;
 3699                       sp->arg = Qnil;
 3700                     }
 3701                 }
 3702               return;
 3703             }
 3704 
 3705           if (hold_quit)
 3706             {
 3707               bcopy (event, (char *) hold_quit, sizeof (*event));
 3708               return;
 3709             }
 3710 
 3711           /* If this results in a quit_char being returned to Emacs as
 3712              input, set Vlast_event_frame properly.  If this doesn't
 3713              get returned to Emacs as an event, the next event read
 3714              will set Vlast_event_frame again, so this is safe to do.  */
 3715           {
 3716             Lisp_Object focus;
 3717 
 3718             focus = FRAME_FOCUS_FRAME (XFRAME (event->frame_or_window));
 3719             if (NILP (focus))
 3720               focus = event->frame_or_window;
 3721             internal_last_event_frame = focus;
 3722             Vlast_event_frame = focus;
 3723           }
 3724 
 3725           last_event_timestamp = event->timestamp;
 3726           handle_interrupt ();
 3727           return;
 3728         }
 3729 
 3730       if (c && c == stop_character)
 3731         {
 3732           sys_suspend ();
 3733           return;
 3734         }
 3735     }
 3736   /* Don't insert two BUFFER_SWITCH_EVENT's in a row.
 3737      Just ignore the second one.  */
 3738   else if (event->kind == BUFFER_SWITCH_EVENT
 3739            && kbd_fetch_ptr != kbd_store_ptr
 3740            && ((kbd_store_ptr == kbd_buffer
 3741                 ? kbd_buffer + KBD_BUFFER_SIZE - 1
 3742                 : kbd_store_ptr - 1)->kind) == BUFFER_SWITCH_EVENT)
 3743     return;
 3744 
 3745   if (kbd_store_ptr - kbd_buffer == KBD_BUFFER_SIZE)
 3746     kbd_store_ptr = kbd_buffer;
 3747 
 3748   /* Don't let the very last slot in the buffer become full,
 3749      since that would make the two pointers equal,
 3750      and that is indistinguishable from an empty buffer.
 3751      Discard the event if it would fill the last slot.  */
 3752   if (kbd_fetch_ptr - 1 != kbd_store_ptr)
 3753     {
 3754       *kbd_store_ptr = *event;
 3755       ++kbd_store_ptr;
 3756     }
 3757 
 3758   /* If we're inside while-no-input, and this event qualifies
 3759      as input, set quit-flag to cause an interrupt.  */
 3760   if (!NILP (Vthrow_on_input)
 3761       && event->kind != FOCUS_IN_EVENT
 3762       && event->kind != HELP_EVENT
 3763       && event->kind != DEICONIFY_EVENT)
 3764     {
 3765       Vquit_flag = Vthrow_on_input;
 3766       /* If we're inside a function that wants immediate quits,
 3767          do it now.  */
 3768       if (immediate_quit && NILP (Vinhibit_quit))
 3769         {
 3770           immediate_quit = 0;
 3771           sigfree ();
 3772           QUIT;
 3773         }
 3774     }
 3775 }
 3776 
 3777 
 3778 /* Put an input event back in the head of the event queue.  */
 3779 
 3780 void
 3781 kbd_buffer_unget_event (event)
 3782      register struct input_event *event;
 3783 {
 3784   if (kbd_fetch_ptr == kbd_buffer)
 3785     kbd_fetch_ptr = kbd_buffer + KBD_BUFFER_SIZE;
 3786 
 3787   /* Don't let the very last slot in the buffer become full,  */
 3788   if (kbd_fetch_ptr - 1 != kbd_store_ptr)
 3789     {
 3790       --kbd_fetch_ptr;
 3791       *kbd_fetch_ptr = *event;
 3792     }
 3793 }
 3794 
 3795 
 3796 /* Generate HELP_EVENT input_events in BUFP which has room for
 3797    SIZE events.  If there's not enough room in BUFP, ignore this
 3798    event.
 3799 
 3800    HELP is the help form.
 3801 
 3802    FRAME is the frame on which the help is generated.  OBJECT is the
 3803    Lisp object where the help was found (a buffer, a string, an
 3804    overlay, or nil if neither from a string nor from a buffer.  POS is
 3805    the position within OBJECT where the help was found.
 3806 
 3807    Value is the number of input_events generated.  */
 3808 
 3809 void
 3810 gen_help_event (help, frame, window, object, pos)
 3811      Lisp_Object help, frame, object, window;
 3812      int pos;
 3813 {
 3814   struct input_event event;
 3815 
 3816   EVENT_INIT (event);
 3817 
 3818   event.kind = HELP_EVENT;
 3819   event.frame_or_window = frame;
 3820   event.arg = object;
 3821   event.x = WINDOWP (window) ? window : frame;
 3822   event.y = help;
 3823   event.code = pos;
 3824   kbd_buffer_store_event (&event);
 3825 }
 3826 
 3827 
 3828 /* Store HELP_EVENTs for HELP on FRAME in the input queue.  */
 3829 
 3830 void
 3831 kbd_buffer_store_help_event (frame, help)
 3832      Lisp_Object frame, help;
 3833 {
 3834   struct input_event event;
 3835 
 3836   event.kind = HELP_EVENT;
 3837   event.frame_or_window = frame;
 3838   event.arg = Qnil;
 3839   event.x = Qnil;
 3840   event.y = help;
 3841   event.code = 0;
 3842   kbd_buffer_store_event (&event);
 3843 }
 3844 
 3845 
 3846 /* Discard any mouse events in the event buffer by setting them to
 3847    NO_EVENT.  */
 3848 void
 3849 discard_mouse_events ()
 3850 {
 3851   struct input_event *sp;
 3852   for (sp = kbd_fetch_ptr; sp != kbd_store_ptr; sp++)
 3853     {
 3854       if (sp == kbd_buffer + KBD_BUFFER_SIZE)
 3855         sp = kbd_buffer;
 3856 
 3857       if (sp->kind == MOUSE_CLICK_EVENT
 3858           || sp->kind == WHEEL_EVENT
 3859           || sp->kind == HORIZ_WHEEL_EVENT
 3860 #ifdef HAVE_GPM
 3861           || sp->kind == GPM_CLICK_EVENT
 3862 #endif
 3863           || sp->kind == SCROLL_BAR_CLICK_EVENT)
 3864         {
 3865           sp->kind = NO_EVENT;
 3866         }
 3867     }
 3868 }
 3869 
 3870 
 3871 /* Return non-zero if there are any real events waiting in the event
 3872    buffer, not counting `NO_EVENT's.
 3873 
 3874    If DISCARD is non-zero, discard NO_EVENT events at the front of
 3875    the input queue, possibly leaving the input queue empty if there
 3876    are no real input events.  */
 3877 
 3878 int
 3879 kbd_buffer_events_waiting (discard)
 3880      int discard;
 3881 {
 3882   struct input_event *sp;
 3883 
 3884   for (sp = kbd_fetch_ptr;
 3885        sp != kbd_store_ptr && sp->kind == NO_EVENT;
 3886        ++sp)
 3887     {
 3888       if (sp == kbd_buffer + KBD_BUFFER_SIZE)
 3889         sp = kbd_buffer;
 3890     }
 3891 
 3892   if (discard)
 3893     kbd_fetch_ptr = sp;
 3894 
 3895   return sp != kbd_store_ptr && sp->kind != NO_EVENT;
 3896 }
 3897 
 3898 
 3899 /* Clear input event EVENT.  */
 3900 
 3901 static INLINE void
 3902 clear_event (event)
 3903      struct input_event *event;
 3904 {
 3905   event->kind = NO_EVENT;
 3906 }
 3907 
 3908 
 3909 /* Read one event from the event buffer, waiting if necessary.
 3910    The value is a Lisp object representing the event.
 3911    The value is nil for an event that should be ignored,
 3912    or that was handled here.
 3913    We always read and discard one event.  */
 3914 
 3915 static Lisp_Object
 3916 kbd_buffer_get_event (kbp, used_mouse_menu, end_time)
 3917      KBOARD **kbp;
 3918      int *used_mouse_menu;
 3919      EMACS_TIME *end_time;
 3920 {
 3921   register int c;
 3922   Lisp_Object obj;
 3923 
 3924   if (noninteractive
 3925       /* In case we are running as a daemon, only do this before
 3926          detaching from the terminal.  */
 3927       || (IS_DAEMON && daemon_pipe[1] >= 0))
 3928     {
 3929       c = getchar ();
 3930       XSETINT (obj, c);
 3931       *kbp = current_kboard;
 3932       return obj;
 3933     }
 3934 
 3935   /* Wait until there is input available.  */
 3936   for (;;)
 3937     {
 3938       /* Break loop if there's an unread command event.  Needed in
 3939          moused window autoselection which uses a timer to insert such
 3940          events.  */
 3941       if (CONSP (Vunread_command_events))
 3942         break;
 3943 
 3944       if (kbd_fetch_ptr != kbd_store_ptr)
 3945         break;
 3946 #if defined (HAVE_MOUSE) || defined (HAVE_GPM)
 3947       if (!NILP (do_mouse_tracking) && some_mouse_moved ())
 3948         break;
 3949 #endif
 3950 
 3951       /* If the quit flag is set, then read_char will return
 3952          quit_char, so that counts as "available input."  */
 3953       if (!NILP (Vquit_flag))
 3954         quit_throw_to_read_char ();
 3955 
 3956       /* One way or another, wait until input is available; then, if
 3957          interrupt handlers have not read it, read it now.  */
 3958 
 3959 /* Note SIGIO has been undef'd if FIONREAD is missing.  */
 3960 #ifdef SIGIO
 3961       gobble_input (0);
 3962 #endif /* SIGIO */
 3963       if (kbd_fetch_ptr != kbd_store_ptr)
 3964         break;
 3965 #if defined (HAVE_MOUSE) || defined (HAVE_GPM)
 3966       if (!NILP (do_mouse_tracking) && some_mouse_moved ())
 3967         break;
 3968 #endif
 3969       if (end_time)
 3970         {
 3971           EMACS_TIME duration;
 3972           EMACS_GET_TIME (duration);
 3973           if (EMACS_TIME_GE (duration, *end_time))
 3974             return Qnil;        /* finished waiting */
 3975           else
 3976             {
 3977               EMACS_SUB_TIME (duration, *end_time, duration);
 3978               wait_reading_process_output (EMACS_SECS (duration),
 3979                                            EMACS_USECS (duration),
 3980                                            -1, 1, Qnil, NULL, 0);
 3981             }
 3982         }
 3983       else
 3984         wait_reading_process_output (0, 0, -1, 1, Qnil, NULL, 0);
 3985 
 3986       if (!interrupt_input && kbd_fetch_ptr == kbd_store_ptr)
 3987         /* Pass 1 for EXPECT since we just waited to have input.  */
 3988         read_avail_input (1);
 3989     }
 3990 
 3991   if (CONSP (Vunread_command_events))
 3992     {
 3993       Lisp_Object first;
 3994       first = XCAR (Vunread_command_events);
 3995       Vunread_command_events = XCDR (Vunread_command_events);
 3996       *kbp = current_kboard;
 3997       return first;
 3998     }
 3999 
 4000   /* At this point, we know that there is a readable event available
 4001      somewhere.  If the event queue is empty, then there must be a
 4002      mouse movement enabled and available.  */
 4003   if (kbd_fetch_ptr != kbd_store_ptr)
 4004     {
 4005       struct input_event *event;
 4006 
 4007       event = ((kbd_fetch_ptr < kbd_buffer + KBD_BUFFER_SIZE)
 4008                ? kbd_fetch_ptr
 4009                : kbd_buffer);
 4010 
 4011       last_event_timestamp = event->timestamp;
 4012 
 4013       *kbp = event_to_kboard (event);
 4014       if (*kbp == 0)
 4015         *kbp = current_kboard;  /* Better than returning null ptr?  */
 4016 
 4017       obj = Qnil;
 4018 
 4019       /* These two kinds of events get special handling
 4020          and don't actually appear to the command loop.
 4021          We return nil for them.  */
 4022       if (event->kind == SELECTION_REQUEST_EVENT
 4023           || event->kind == SELECTION_CLEAR_EVENT)
 4024         {
 4025 #ifdef HAVE_X11
 4026           struct input_event copy;
 4027 
 4028           /* Remove it from the buffer before processing it,
 4029              since otherwise swallow_events will see it
 4030              and process it again.  */
 4031           copy = *event;
 4032           kbd_fetch_ptr = event + 1;
 4033           input_pending = readable_events (0);
 4034           x_handle_selection_event (&copy);
 4035 #else
 4036           /* We're getting selection request events, but we don't have
 4037              a window system.  */
 4038           abort ();
 4039 #endif
 4040         }
 4041 
 4042 #if defined (HAVE_NS)
 4043       else if (event->kind == NS_TEXT_EVENT)
 4044         {
 4045           if (event->code == KEY_NS_PUT_WORKING_TEXT)
 4046             obj = Fcons (intern ("ns-put-working-text"), Qnil);
 4047           else
 4048             obj = Fcons (intern ("ns-unput-working-text"), Qnil);
 4049           kbd_fetch_ptr = event + 1;
 4050           if (used_mouse_menu)
 4051             *used_mouse_menu = 1;
 4052         }
 4053 #endif
 4054 
 4055 #if defined (HAVE_X11) || defined (HAVE_NTGUI) \
 4056     || defined (HAVE_NS)
 4057       else if (event->kind == DELETE_WINDOW_EVENT)
 4058         {
 4059           /* Make an event (delete-frame (FRAME)).  */
 4060           obj = Fcons (event->frame_or_window, Qnil);
 4061           obj = Fcons (Qdelete_frame, Fcons (obj, Qnil));
 4062           kbd_fetch_ptr = event + 1;
 4063         }
 4064 #endif
 4065 #if defined (HAVE_X11) || defined (HAVE_NTGUI) \
 4066     || defined (HAVE_NS)
 4067       else if (event->kind == ICONIFY_EVENT)
 4068         {
 4069           /* Make an event (iconify-frame (FRAME)).  */
 4070           obj = Fcons (event->frame_or_window, Qnil);
 4071           obj = Fcons (Qiconify_frame, Fcons (obj, Qnil));
 4072           kbd_fetch_ptr = event + 1;
 4073         }
 4074       else if (event->kind == DEICONIFY_EVENT)
 4075         {
 4076           /* Make an event (make-frame-visible (FRAME)).  */
 4077           obj = Fcons (event->frame_or_window, Qnil);
 4078           obj = Fcons (Qmake_frame_visible, Fcons (obj, Qnil));
 4079           kbd_fetch_ptr = event + 1;
 4080         }
 4081 #endif
 4082       else if (event->kind == BUFFER_SWITCH_EVENT)
 4083         {
 4084           /* The value doesn't matter here; only the type is tested.  */
 4085           XSETBUFFER (obj, current_buffer);
 4086           kbd_fetch_ptr = event + 1;
 4087         }
 4088 #if defined (USE_X_TOOLKIT) || defined (HAVE_NTGUI) \
 4089     || defined(HAVE_NS) || defined (USE_GTK)
 4090       else if (event->kind == MENU_BAR_ACTIVATE_EVENT)
 4091         {
 4092           kbd_fetch_ptr = event + 1;
 4093           input_pending = readable_events (0);
 4094           if (FRAME_LIVE_P (XFRAME (event->frame_or_window)))
 4095             x_activate_menubar (XFRAME (event->frame_or_window));
 4096         }
 4097 #endif
 4098 #if defined (WINDOWSNT)
 4099       else if (event->kind == LANGUAGE_CHANGE_EVENT)
 4100         {
 4101           /* Make an event (language-change (FRAME CHARSET LCID)).  */
 4102           obj = Fcons (event->frame_or_window, Qnil);
 4103           obj = Fcons (Qlanguage_change, Fcons (obj, Qnil));
 4104           kbd_fetch_ptr = event + 1;
 4105         }
 4106 #endif
 4107       else if (event->kind == SAVE_SESSION_EVENT)
 4108         {
 4109           obj = Fcons (Qsave_session, Qnil);
 4110           kbd_fetch_ptr = event + 1;
 4111         }
 4112       /* Just discard these, by returning nil.
 4113          With MULTI_KBOARD, these events are used as placeholders
 4114          when we need to randomly delete events from the queue.
 4115          (They shouldn't otherwise be found in the buffer,
 4116          but on some machines it appears they do show up
 4117          even without MULTI_KBOARD.)  */
 4118       /* On Windows NT/9X, NO_EVENT is used to delete extraneous
 4119          mouse events during a popup-menu call.  */
 4120       else if (event->kind == NO_EVENT)
 4121         kbd_fetch_ptr = event + 1;
 4122       else if (event->kind == HELP_EVENT)
 4123         {
 4124           Lisp_Object object, position, help, frame, window;
 4125 
 4126           frame = event->frame_or_window;
 4127           object = event->arg;
 4128           position = make_number (event->code);
 4129           window = event->x;
 4130           help = event->y;
 4131           clear_event (event);
 4132 
 4133           kbd_fetch_ptr = event + 1;
 4134           if (!WINDOWP (window))
 4135             window = Qnil;
 4136           obj = Fcons (Qhelp_echo,
 4137                        list5 (frame, help, window, object, position));
 4138         }
 4139       else if (event->kind == FOCUS_IN_EVENT)
 4140         {
 4141           /* Notification of a FocusIn event.  The frame receiving the
 4142              focus is in event->frame_or_window.  Generate a
 4143              switch-frame event if necessary.  */
 4144           Lisp_Object frame, focus;
 4145 
 4146           frame = event->frame_or_window;
 4147           focus = FRAME_FOCUS_FRAME (XFRAME (frame));
 4148           if (FRAMEP (focus))
 4149             frame = focus;
 4150 
 4151           if (!EQ (frame, internal_last_event_frame)
 4152               && !EQ (frame, selected_frame))
 4153             obj = make_lispy_switch_frame (frame);
 4154           internal_last_event_frame = frame;
 4155           kbd_fetch_ptr = event + 1;
 4156         }
 4157 #ifdef HAVE_DBUS
 4158       else if (event->kind == DBUS_EVENT)
 4159         {
 4160           obj = make_lispy_event (event);
 4161           kbd_fetch_ptr = event + 1;
 4162         }
 4163 #endif
 4164       else if (event->kind == CONFIG_CHANGED_EVENT)
 4165         {
 4166           obj = make_lispy_event (event);
 4167           kbd_fetch_ptr = event + 1;
 4168         }
 4169       else
 4170         {
 4171           /* If this event is on a different frame, return a switch-frame this
 4172              time, and leave the event in the queue for next time.  */
 4173           Lisp_Object frame;
 4174           Lisp_Object focus;
 4175 
 4176           frame = event->frame_or_window;
 4177           if (CONSP (frame))
 4178             frame = XCAR (frame);
 4179           else if (WINDOWP (frame))
 4180             frame = WINDOW_FRAME (XWINDOW (frame));
 4181 
 4182           focus = FRAME_FOCUS_FRAME (XFRAME (frame));
 4183           if (! NILP (focus))
 4184             frame = focus;
 4185 
 4186           if (! EQ (frame, internal_last_event_frame)
 4187               && !EQ (frame, selected_frame))
 4188             obj = make_lispy_switch_frame (frame);
 4189           internal_last_event_frame = frame;
 4190 
 4191           /* If we didn't decide to make a switch-frame event, go ahead
 4192              and build a real event from the queue entry.  */
 4193 
 4194           if (NILP (obj))
 4195             {
 4196               obj = make_lispy_event (event);
 4197 
 4198 #if defined (USE_X_TOOLKIT) || defined (HAVE_NTGUI) \
 4199     || defined(HAVE_NS) || defined (USE_GTK)
 4200               /* If this was a menu selection, then set the flag to inhibit
 4201                  writing to last_nonmenu_event.  Don't do this if the event
 4202                  we're returning is (menu-bar), though; that indicates the
 4203                  beginning of the menu sequence, and we might as well leave
 4204                  that as the `event with parameters' for this selection.  */
 4205               if (used_mouse_menu
 4206                   && !EQ (event->frame_or_window, event->arg)
 4207                   && (event->kind == MENU_BAR_EVENT
 4208                       || event->kind == TOOL_BAR_EVENT))
 4209                 *used_mouse_menu = 1;
 4210 #endif
 4211 #ifdef HAVE_NS
 4212               /* certain system events are non-key events */
 4213               if (used_mouse_menu
 4214                   && event->kind == NS_NONKEY_EVENT)
 4215                 *used_mouse_menu = 1;
 4216 #endif
 4217 
 4218               /* Wipe out this event, to catch bugs.  */
 4219               clear_event (event);
 4220               kbd_fetch_ptr = event + 1;
 4221             }
 4222         }
 4223     }
 4224 #if defined (HAVE_MOUSE) || defined (HAVE_GPM)
 4225   /* Try generating a mouse motion event.  */
 4226   else if (!NILP (do_mouse_tracking) && some_mouse_moved ())
 4227     {
 4228       FRAME_PTR f = some_mouse_moved ();
 4229       Lisp_Object bar_window;
 4230       enum scroll_bar_part part;
 4231       Lisp_Object x, y;
 4232       unsigned long time;
 4233 
 4234       *kbp = current_kboard;
 4235       /* Note that this uses F to determine which terminal to look at.
 4236          If there is no valid info, it does not store anything
 4237          so x remains nil.  */
 4238       x = Qnil;
 4239 
 4240       /* XXX Can f or mouse_position_hook be NULL here? */
 4241       if (f && FRAME_TERMINAL (f)->mouse_position_hook)
 4242         (*FRAME_TERMINAL (f)->mouse_position_hook) (&f, 0, &bar_window,
 4243                                                     &part, &x, &y, &time);
 4244 
 4245       obj = Qnil;
 4246 
 4247       /* Decide if we should generate a switch-frame event.  Don't
 4248          generate switch-frame events for motion outside of all Emacs
 4249          frames.  */
 4250       if (!NILP (x) && f)
 4251         {
 4252           Lisp_Object frame;
 4253 
 4254           frame = FRAME_FOCUS_FRAME (f);
 4255           if (NILP (frame))
 4256             XSETFRAME (frame, f);
 4257 
 4258           if (! EQ (frame, internal_last_event_frame)
 4259               && !EQ (frame, selected_frame))
 4260             obj = make_lispy_switch_frame (frame);
 4261           internal_last_event_frame = frame;
 4262         }
 4263 
 4264       /* If we didn't decide to make a switch-frame event, go ahead and
 4265          return a mouse-motion event.  */
 4266       if (!NILP (x) && NILP (obj))
 4267         obj = make_lispy_movement (f, bar_window, part, x, y, time);
 4268     }
 4269 #endif  /* HAVE_MOUSE || HAVE GPM */
 4270   else
 4271     /* We were promised by the above while loop that there was
 4272        something for us to read!  */
 4273     abort ();
 4274 
 4275   input_pending = readable_events (0);
 4276 
 4277   Vlast_event_frame = internal_last_event_frame;
 4278 
 4279   return (obj);
 4280 }
 4281 
 4282 /* Process any events that are not user-visible,
 4283    then return, without reading any user-visible events.  */
 4284 
 4285 void
 4286 swallow_events (do_display)
 4287      int do_display;
 4288 {
 4289   int old_timers_run;
 4290 
 4291   while (kbd_fetch_ptr != kbd_store_ptr)
 4292     {
 4293       struct input_event *event;
 4294 
 4295       event = ((kbd_fetch_ptr < kbd_buffer + KBD_BUFFER_SIZE)
 4296                ? kbd_fetch_ptr
 4297                : kbd_buffer);
 4298 
 4299       last_event_timestamp = event->timestamp;
 4300 
 4301       /* These two kinds of events get special handling
 4302          and don't actually appear to the command loop.  */
 4303       if (event->kind == SELECTION_REQUEST_EVENT
 4304           || event->kind == SELECTION_CLEAR_EVENT)
 4305         {
 4306 #ifdef HAVE_X11
 4307           struct input_event copy;
 4308 
 4309           /* Remove it from the buffer before processing it,
 4310              since otherwise swallow_events called recursively could see it
 4311              and process it again.  */
 4312           copy = *event;
 4313           kbd_fetch_ptr = event + 1;
 4314           input_pending = readable_events (0);
 4315           x_handle_selection_event (&copy);
 4316 #else
 4317           /* We're getting selection request events, but we don't have
 4318              a window system.  */
 4319           abort ();
 4320 #endif
 4321         }
 4322       else
 4323         break;
 4324     }
 4325 
 4326   old_timers_run = timers_run;
 4327   get_input_pending (&input_pending, READABLE_EVENTS_DO_TIMERS_NOW);
 4328 
 4329   if (timers_run != old_timers_run && do_display)
 4330     redisplay_preserve_echo_area (7);
 4331 }
 4332 
 4333 /* Record the start of when Emacs is idle,
 4334    for the sake of running idle-time timers.  */
 4335 
 4336 static void
 4337 timer_start_idle ()
 4338 {
 4339   Lisp_Object timers;
 4340 
 4341   /* If we are already in the idle state, do nothing.  */
 4342   if (! EMACS_TIME_NEG_P (timer_idleness_start_time))
 4343     return;
 4344 
 4345   EMACS_GET_TIME (timer_idleness_start_time);
 4346 
 4347   timer_last_idleness_start_time = timer_idleness_start_time;
 4348 
 4349   /* Mark all idle-time timers as once again candidates for running.  */
 4350   for (timers = Vtimer_idle_list; CONSP (timers); timers = XCDR (timers))
 4351     {
 4352       Lisp_Object timer;
 4353 
 4354       timer = XCAR (timers);
 4355 
 4356       if (!VECTORP (timer) || XVECTOR (timer)->size != 8)
 4357         continue;
 4358       XVECTOR (timer)->contents[0] = Qnil;
 4359     }
 4360 }
 4361 
 4362 /* Record that Emacs is no longer idle, so stop running idle-time timers.  */
 4363 
 4364 static void
 4365 timer_stop_idle ()
 4366 {
 4367   EMACS_SET_SECS_USECS (timer_idleness_start_time, -1, -1);
 4368 }
 4369 
 4370 /* Resume idle timer from last idle start time.  */
 4371 
 4372 static void
 4373 timer_resume_idle ()
 4374 {
 4375   if (! EMACS_TIME_NEG_P (timer_idleness_start_time))
 4376     return;
 4377 
 4378   timer_idleness_start_time = timer_last_idleness_start_time;
 4379 }
 4380 
 4381 /* This is only for debugging.  */
 4382 struct input_event last_timer_event;
 4383 
 4384 /* List of elisp functions to call, delayed because they were generated in
 4385    a context where Elisp could not be safely run (e.g. redisplay, signal,
 4386    ...).  Each element has the form (FUN . ARGS).  */
 4387 Lisp_Object pending_funcalls;
 4388 
 4389 extern Lisp_Object Qapply;
 4390 
 4391 /* Check whether a timer has fired.  To prevent larger problems we simply
 4392    disregard elements that are not proper timers.  Do not make a circular
 4393    timer list for the time being.
 4394 
 4395    Returns the time to wait until the next timer fires.  If a
 4396    timer is triggering now, return zero.
 4397    If no timer is active, return -1.
 4398 
 4399    If a timer is ripe, we run it, with quitting turned off.
 4400    In that case we return 0 to indicate that a new timer_check_2 call
 4401    should be done.  */
 4402 
 4403 static EMACS_TIME
 4404 timer_check_2 ()
 4405 {
 4406   EMACS_TIME nexttime;
 4407   EMACS_TIME now, idleness_now;
 4408   Lisp_Object timers, idle_timers, chosen_timer;
 4409   struct gcpro gcpro1, gcpro2, gcpro3;
 4410 
 4411   EMACS_SET_SECS (nexttime, -1);
 4412   EMACS_SET_USECS (nexttime, -1);
 4413 
 4414   /* Always consider the ordinary timers.  */
 4415   timers = Vtimer_list;
 4416   /* Consider the idle timers only if Emacs is idle.  */
 4417   if (! EMACS_TIME_NEG_P (timer_idleness_start_time))
 4418     idle_timers = Vtimer_idle_list;
 4419   else
 4420     idle_timers = Qnil;
 4421   chosen_timer = Qnil;
 4422   GCPRO3 (timers, idle_timers, chosen_timer);
 4423 
 4424   /* First run the code that was delayed.  */
 4425   while (CONSP (pending_funcalls))
 4426     {
 4427       Lisp_Object funcall = XCAR (pending_funcalls);
 4428       pending_funcalls = XCDR (pending_funcalls);
 4429       safe_call2 (Qapply, XCAR (funcall), XCDR (funcall));
 4430     }
 4431 
 4432   if (CONSP (timers) || CONSP (idle_timers))
 4433     {
 4434       EMACS_GET_TIME (now);
 4435       if (! EMACS_TIME_NEG_P (timer_idleness_start_time))
 4436         EMACS_SUB_TIME (idleness_now, now, timer_idleness_start_time);
 4437     }
 4438 
 4439   while (CONSP (timers) || CONSP (idle_timers))
 4440     {
 4441       Lisp_Object *vector;
 4442       Lisp_Object timer = Qnil, idle_timer = Qnil;
 4443       EMACS_TIME timer_time, idle_timer_time;
 4444       EMACS_TIME difference, timer_difference, idle_timer_difference;
 4445 
 4446       /* Skip past invalid timers and timers already handled.  */
 4447       if (!NILP (timers))
 4448         {
 4449           timer = XCAR (timers);
 4450           if (!VECTORP (timer) || XVECTOR (timer)->size != 8)
 4451             {
 4452               timers = XCDR (timers);
 4453               continue;
 4454             }
 4455           vector = XVECTOR (timer)->contents;
 4456 
 4457           if (!INTEGERP (vector[1]) || !INTEGERP (vector[2])
 4458               || !INTEGERP (vector[3])
 4459               || ! NILP (vector[0]))
 4460             {
 4461               timers = XCDR (timers);
 4462               continue;
 4463             }
 4464         }
 4465       if (!NILP (idle_timers))
 4466         {
 4467           timer = XCAR (idle_timers);
 4468           if (!VECTORP (timer) || XVECTOR (timer)->size != 8)
 4469             {
 4470               idle_timers = XCDR (idle_timers);
 4471               continue;
 4472             }
 4473           vector = XVECTOR (timer)->contents;
 4474 
 4475           if (!INTEGERP (vector[1]) || !INTEGERP (vector[2])
 4476               || !INTEGERP (vector[3])
 4477               || ! NILP (vector[0]))
 4478             {
 4479               idle_timers = XCDR (idle_timers);
 4480               continue;
 4481             }
 4482         }
 4483 
 4484       /* Set TIMER, TIMER_TIME and TIMER_DIFFERENCE
 4485          based on the next ordinary timer.
 4486          TIMER_DIFFERENCE is the distance in time from NOW to when
 4487          this timer becomes ripe (negative if it's already ripe).  */
 4488       if (!NILP (timers))
 4489         {
 4490           timer = XCAR (timers);
 4491           vector = XVECTOR (timer)->contents;
 4492           EMACS_SET_SECS (timer_time,
 4493                           (XINT (vector[1]) << 16) | (XINT (vector[2])));
 4494           EMACS_SET_USECS (timer_time, XINT (vector[3]));
 4495           EMACS_SUB_TIME (timer_difference, timer_time, now);
 4496         }
 4497 
 4498       /* Set IDLE_TIMER, IDLE_TIMER_TIME and IDLE_TIMER_DIFFERENCE
 4499          based on the next idle timer.  */
 4500       if (!NILP (idle_timers))
 4501         {
 4502           idle_timer = XCAR (idle_timers);
 4503           vector = XVECTOR (idle_timer)->contents;
 4504           EMACS_SET_SECS (idle_timer_time,
 4505                           (XINT (vector[1]) << 16) | (XINT (vector[2])));
 4506           EMACS_SET_USECS (idle_timer_time, XINT (vector[3]));
 4507           EMACS_SUB_TIME (idle_timer_difference, idle_timer_time, idleness_now);
 4508         }
 4509 
 4510       /* Decide which timer is the next timer,
 4511          and set CHOSEN_TIMER, VECTOR and DIFFERENCE accordingly.
 4512          Also step down the list where we found that timer.  */
 4513 
 4514       if (! NILP (timers) && ! NILP (idle_timers))
 4515         {
 4516           EMACS_TIME temp;
 4517           EMACS_SUB_TIME (temp, timer_difference, idle_timer_difference);
 4518           if (EMACS_TIME_NEG_P (temp))
 4519             {
 4520               chosen_timer = timer;
 4521               timers = XCDR (timers);
 4522               difference = timer_difference;
 4523             }
 4524           else
 4525             {
 4526               chosen_timer = idle_timer;
 4527               idle_timers = XCDR (idle_timers);
 4528               difference = idle_timer_difference;
 4529             }
 4530         }
 4531       else if (! NILP (timers))
 4532         {
 4533           chosen_timer = timer;
 4534           timers = XCDR (timers);
 4535           difference = timer_difference;
 4536         }
 4537       else
 4538         {
 4539           chosen_timer = idle_timer;
 4540           idle_timers = XCDR (idle_timers);
 4541           difference = idle_timer_difference;
 4542         }
 4543       vector = XVECTOR (chosen_timer)->contents;
 4544 
 4545       /* If timer is ripe, run it if it hasn't been run.  */
 4546       if (EMACS_TIME_NEG_P (difference)
 4547           || (EMACS_SECS (difference) == 0
 4548               && EMACS_USECS (difference) == 0))
 4549         {
 4550           if (NILP (vector[0]))
 4551             {
 4552               int count = SPECPDL_INDEX ();
 4553               Lisp_Object old_deactivate_mark = Vdeactivate_mark;
 4554 
 4555               /* Mark the timer as triggered to prevent problems if the lisp
 4556                  code fails to reschedule it right.  */
 4557               vector[0] = Qt;
 4558 
 4559               specbind (Qinhibit_quit, Qt);
 4560 
 4561               call1 (Qtimer_event_handler, chosen_timer);
 4562               Vdeactivate_mark = old_deactivate_mark;
 4563               timers_run++;
 4564               unbind_to (count, Qnil);
 4565 
 4566               /* Since we have handled the event,
 4567                  we don't need to tell the caller to wake up and do it.  */
 4568               /* But the caller must still wait for the next timer, so
 4569                  return 0 to indicate that.  */
 4570             }
 4571 
 4572           EMACS_SET_SECS (nexttime, 0);
 4573           EMACS_SET_USECS (nexttime, 0);
 4574         }
 4575       else
 4576         /* When we encounter a timer that is still waiting,
 4577            return the amount of time to wait before it is ripe.  */
 4578         {
 4579           UNGCPRO;
 4580           return difference;
 4581         }
 4582     }
 4583 
 4584   /* No timers are pending in the future.  */
 4585   /* Return 0 if we generated an event, and -1 if not.  */
 4586   UNGCPRO;
 4587   return nexttime;
 4588 }
 4589 
 4590 
 4591 /* Check whether a timer has fired.  To prevent larger problems we simply
 4592    disregard elements that are not proper timers.  Do not make a circular
 4593    timer list for the time being.
 4594 
 4595    Returns the time to wait until the next timer fires.
 4596    If no timer is active, return -1.
 4597 
 4598    As long as any timer is ripe, we run it.
 4599 
 4600    DO_IT_NOW is now ignored.  It used to mean that we should
 4601    run the timer directly instead of queueing a timer-event.
 4602    Now we always run timers directly.  */
 4603 
 4604 EMACS_TIME
 4605 timer_check (do_it_now)
 4606      int do_it_now;
 4607 {
 4608   EMACS_TIME nexttime;
 4609 
 4610   do 
 4611     {
 4612       nexttime = timer_check_2 ();
 4613     }
 4614   while (EMACS_SECS (nexttime) == 0 && EMACS_USECS (nexttime) == 0);
 4615 
 4616   return nexttime;
 4617 }
 4618 
 4619 DEFUN ("current-idle-time", Fcurrent_idle_time, Scurrent_idle_time, 0, 0, 0,
 4620        doc: /* Return the current length of Emacs idleness, or nil.
 4621 The value when Emacs is idle is a list of three integers.  The first has
 4622 the most significant 16 bits of the seconds, while the second has the least
 4623 significant 16 bits.  The third integer gives the microsecond count.
 4624 
 4625 The value when Emacs is not idle is nil.
 4626 
 4627 The microsecond count is zero on systems that do not provide
 4628 resolution finer than a second.  */)
 4629   ()
 4630 {
 4631   if (! EMACS_TIME_NEG_P (timer_idleness_start_time))
 4632     {
 4633       EMACS_TIME now, idleness_now;
 4634 
 4635       EMACS_GET_TIME (now);
 4636       EMACS_SUB_TIME (idleness_now, now, timer_idleness_start_time);
 4637 
 4638       return list3 (make_number ((EMACS_SECS (idleness_now) >> 16) & 0xffff),
 4639                     make_number ((EMACS_SECS (idleness_now) >> 0)  & 0xffff),
 4640                     make_number (EMACS_USECS (idleness_now)));
 4641     }
 4642 
 4643   return Qnil;
 4644 }
 4645 
 4646 /* Caches for modify_event_symbol.  */
 4647 static Lisp_Object accent_key_syms;
 4648 static Lisp_Object func_key_syms;
 4649 static Lisp_Object mouse_syms;
 4650 static Lisp_Object wheel_syms;
 4651 static Lisp_Object drag_n_drop_syms;
 4652 
 4653 /* This is a list of keysym codes for special "accent" characters.
 4654    It parallels lispy_accent_keys.  */
 4655 
 4656 static const int lispy_accent_codes[] =
 4657 {
 4658 #ifdef XK_dead_circumflex
 4659   XK_dead_circumflex,
 4660 #else
 4661   0,
 4662 #endif
 4663 #ifdef XK_dead_grave
 4664   XK_dead_grave,
 4665 #else
 4666   0,
 4667 #endif
 4668 #ifdef XK_dead_tilde
 4669   XK_dead_tilde,
 4670 #else
 4671   0,
 4672 #endif
 4673 #ifdef XK_dead_diaeresis
 4674   XK_dead_diaeresis,
 4675 #else
 4676   0,
 4677 #endif
 4678 #ifdef XK_dead_macron
 4679   XK_dead_macron,
 4680 #else
 4681   0,
 4682 #endif
 4683 #ifdef XK_dead_degree
 4684   XK_dead_degree,
 4685 #else
 4686   0,
 4687 #endif
 4688 #ifdef XK_dead_acute
 4689   XK_dead_acute,
 4690 #else
 4691   0,
 4692 #endif
 4693 #ifdef XK_dead_cedilla
 4694   XK_dead_cedilla,
 4695 #else
 4696   0,
 4697 #endif
 4698 #ifdef XK_dead_breve
 4699   XK_dead_breve,
 4700 #else
 4701   0,
 4702 #endif
 4703 #ifdef XK_dead_ogonek
 4704   XK_dead_ogonek,
 4705 #else
 4706   0,
 4707 #endif
 4708 #ifdef XK_dead_caron
 4709   XK_dead_caron,
 4710 #else
 4711   0,
 4712 #endif
 4713 #ifdef XK_dead_doubleacute
 4714   XK_dead_doubleacute,
 4715 #else
 4716   0,
 4717 #endif
 4718 #ifdef XK_dead_abovedot
 4719   XK_dead_abovedot,
 4720 #else
 4721   0,
 4722 #endif
 4723 #ifdef XK_dead_abovering
 4724   XK_dead_abovering,
 4725 #else
 4726   0,
 4727 #endif
 4728 #ifdef XK_dead_iota
 4729   XK_dead_iota,
 4730 #else
 4731   0,
 4732 #endif
 4733 #ifdef XK_dead_belowdot
 4734   XK_dead_belowdot,
 4735 #else
 4736   0,
 4737 #endif
 4738 #ifdef XK_dead_voiced_sound
 4739   XK_dead_voiced_sound,
 4740 #else
 4741   0,
 4742 #endif
 4743 #ifdef XK_dead_semivoiced_sound
 4744   XK_dead_semivoiced_sound,
 4745 #else
 4746   0,
 4747 #endif
 4748 #ifdef XK_dead_hook
 4749   XK_dead_hook,
 4750 #else
 4751   0,
 4752 #endif
 4753 #ifdef XK_dead_horn
 4754   XK_dead_horn,
 4755 #else
 4756   0,
 4757 #endif
 4758 };
 4759 
 4760 /* This is a list of Lisp names for special "accent" characters.
 4761    It parallels lispy_accent_codes.  */
 4762 
 4763 static char *lispy_accent_keys[] =
 4764 {
 4765   "dead-circumflex",
 4766   "dead-grave",
 4767   "dead-tilde",
 4768   "dead-diaeresis",
 4769   "dead-macron",
 4770   "dead-degree",
 4771   "dead-acute",
 4772   "dead-cedilla",
 4773   "dead-breve",
 4774   "dead-ogonek",
 4775   "dead-caron",
 4776   "dead-doubleacute",
 4777   "dead-abovedot",
 4778   "dead-abovering",
 4779   "dead-iota",
 4780   "dead-belowdot",
 4781   "dead-voiced-sound",
 4782   "dead-semivoiced-sound",
 4783   "dead-hook",
 4784   "dead-horn",
 4785 };
 4786 
 4787 #ifdef HAVE_NTGUI
 4788 #define FUNCTION_KEY_OFFSET 0x0
 4789 
 4790 char *lispy_function_keys[] =
 4791   {
 4792     0,                /* 0                      */
 4793 
 4794     0,                /* VK_LBUTTON        0x01 */
 4795     0,                /* VK_RBUTTON        0x02 */
 4796     "cancel",         /* VK_CANCEL         0x03 */
 4797     0,                /* VK_MBUTTON        0x04 */
 4798 
 4799     0, 0, 0,          /*    0x05 .. 0x07        */
 4800 
 4801     "backspace",      /* VK_BACK           0x08 */
 4802     "tab",            /* VK_TAB            0x09 */
 4803 
 4804     0, 0,             /*    0x0A .. 0x0B        */
 4805 
 4806     "clear",          /* VK_CLEAR          0x0C */
 4807     "return",         /* VK_RETURN         0x0D */
 4808 
 4809     0, 0,             /*    0x0E .. 0x0F        */
 4810 
 4811     0,                /* VK_SHIFT          0x10 */
 4812     0,                /* VK_CONTROL        0x11 */
 4813     0,                /* VK_MENU           0x12 */
 4814     "pause",          /* VK_PAUSE          0x13 */
 4815     "capslock",       /* VK_CAPITAL        0x14 */
 4816     "kana",           /* VK_KANA/VK_HANGUL 0x15 */
 4817     0,                /*    0x16                */
 4818     "junja",          /* VK_JUNJA          0x17 */
 4819     "final",          /* VK_FINAL          0x18 */
 4820     "kanji",          /* VK_KANJI/VK_HANJA 0x19 */
 4821     0,                /*    0x1A                */
 4822     "escape",         /* VK_ESCAPE         0x1B */
 4823     "convert",        /* VK_CONVERT        0x1C */
 4824     "non-convert",    /* VK_NONCONVERT     0x1D */
 4825     "accept",         /* VK_ACCEPT         0x1E */
 4826     "mode-change",    /* VK_MODECHANGE     0x1F */
 4827     0,                /* VK_SPACE          0x20 */
 4828     "prior",          /* VK_PRIOR          0x21 */
 4829     "next",           /* VK_NEXT           0x22 */
 4830     "end",            /* VK_END            0x23 */
 4831     "home",           /* VK_HOME           0x24 */
 4832     "left",           /* VK_LEFT           0x25 */
 4833     "up",             /* VK_UP             0x26 */
 4834     "right",          /* VK_RIGHT          0x27 */
 4835     "down",           /* VK_DOWN           0x28 */
 4836     "select",         /* VK_SELECT         0x29 */
 4837     "print",          /* VK_PRINT          0x2A */
 4838     "execute",        /* VK_EXECUTE        0x2B */
 4839     "snapshot",       /* VK_SNAPSHOT       0x2C */
 4840     "insert",         /* VK_INSERT         0x2D */
 4841     "delete",         /* VK_DELETE         0x2E */
 4842     "help",           /* VK_HELP           0x2F */
 4843 
 4844     /* VK_0 thru VK_9 are the same as ASCII '0' thru '9' (0x30 - 0x39) */
 4845 
 4846     0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
 4847 
 4848     0, 0, 0, 0, 0, 0, 0, /* 0x3A .. 0x40       */
 4849 
 4850     /* VK_A thru VK_Z are the same as ASCII 'A' thru 'Z' (0x41 - 0x5A) */
 4851 
 4852     0, 0, 0, 0, 0, 0, 0, 0, 0,
 4853     0, 0, 0, 0, 0, 0, 0, 0, 0,
 4854     0, 0, 0, 0, 0, 0, 0, 0,
 4855 
 4856     "lwindow",       /* VK_LWIN           0x5B */
 4857     "rwindow",       /* VK_RWIN           0x5C */
 4858     "apps",          /* VK_APPS           0x5D */
 4859     0,               /*    0x5E                */
 4860     "sleep",
 4861     "kp-0",          /* VK_NUMPAD0        0x60 */
 4862     "kp-1",          /* VK_NUMPAD1        0x61 */
 4863     "kp-2",          /* VK_NUMPAD2        0x62 */
 4864     "kp-3",          /* VK_NUMPAD3        0x63 */
 4865     "kp-4",          /* VK_NUMPAD4        0x64 */
 4866     "kp-5",          /* VK_NUMPAD5        0x65 */
 4867     "kp-6",          /* VK_NUMPAD6        0x66 */
 4868     "kp-7",          /* VK_NUMPAD7        0x67 */
 4869     "kp-8",          /* VK_NUMPAD8        0x68 */
 4870     "kp-9",          /* VK_NUMPAD9        0x69 */
 4871     "kp-multiply",   /* VK_MULTIPLY       0x6A */
 4872     "kp-add",        /* VK_ADD            0x6B */
 4873     "kp-separator",  /* VK_SEPARATOR      0x6C */
 4874     "kp-subtract",   /* VK_SUBTRACT       0x6D */
 4875     "kp-decimal",    /* VK_DECIMAL        0x6E */
 4876     "kp-divide",     /* VK_DIVIDE         0x6F */
 4877     "f1",            /* VK_F1             0x70 */
 4878     "f2",            /* VK_F2             0x71 */
 4879     "f3",            /* VK_F3             0x72 */
 4880     "f4",            /* VK_F4             0x73 */
 4881     "f5",            /* VK_F5             0x74 */
 4882     "f6",            /* VK_F6             0x75 */
 4883     "f7",            /* VK_F7             0x76 */
 4884     "f8",            /* VK_F8             0x77 */
 4885     "f9",            /* VK_F9             0x78 */
 4886     "f10",           /* VK_F10            0x79 */
 4887     "f11",           /* VK_F11            0x7A */
 4888     "f12",           /* VK_F12            0x7B */
 4889     "f13",           /* VK_F13            0x7C */
 4890     "f14",           /* VK_F14            0x7D */
 4891     "f15",           /* VK_F15            0x7E */
 4892     "f16",           /* VK_F16            0x7F */
 4893     "f17",           /* VK_F17            0x80 */
 4894     "f18",           /* VK_F18            0x81 */
 4895     "f19",           /* VK_F19            0x82 */
 4896     "f20",           /* VK_F20            0x83 */
 4897     "f21",           /* VK_F21            0x84 */
 4898     "f22",           /* VK_F22            0x85 */
 4899     "f23",           /* VK_F23            0x86 */
 4900     "f24",           /* VK_F24            0x87 */
 4901 
 4902     0, 0, 0, 0,      /*    0x88 .. 0x8B        */
 4903     0, 0, 0, 0,      /*    0x8C .. 0x8F        */
 4904 
 4905     "kp-numlock",    /* VK_NUMLOCK        0x90 */
 4906     "scroll",        /* VK_SCROLL         0x91 */
 4907     /* Not sure where the following block comes from.
 4908        Windows headers have NEC and Fujitsu specific keys in
 4909        this block, but nothing generic.  */
 4910     "kp-space",      /* VK_NUMPAD_CLEAR   0x92 */
 4911     "kp-enter",      /* VK_NUMPAD_ENTER   0x93 */
 4912     "kp-prior",      /* VK_NUMPAD_PRIOR   0x94 */
 4913     "kp-next",       /* VK_NUMPAD_NEXT    0x95 */
 4914     "kp-end",        /* VK_NUMPAD_END     0x96 */
 4915     "kp-home",       /* VK_NUMPAD_HOME    0x97 */
 4916     "kp-left",       /* VK_NUMPAD_LEFT    0x98 */
 4917     "kp-up",         /* VK_NUMPAD_UP      0x99 */
 4918     "kp-right",      /* VK_NUMPAD_RIGHT   0x9A */
 4919     "kp-down",       /* VK_NUMPAD_DOWN    0x9B */
 4920     "kp-insert",     /* VK_NUMPAD_INSERT  0x9C */
 4921     "kp-delete",     /* VK_NUMPAD_DELETE  0x9D */
 4922 
 4923     0, 0,            /*    0x9E .. 0x9F        */
 4924 
 4925     /*
 4926      * VK_L* & VK_R* - left and right Alt, Ctrl and Shift virtual keys.
 4927      * Used only as parameters to GetAsyncKeyState and GetKeyState.
 4928      * No other API or message will distinguish left and right keys this way.
 4929      * 0xA0 .. 0xA5
 4930      */
 4931     0, 0, 0, 0, 0, 0,
 4932 
 4933     /* Multimedia keys. These are handled as WM_APPCOMMAND, which allows us
 4934        to enable them selectively, and gives access to a few more functions.
 4935        See lispy_multimedia_keys below.  */
 4936     0, 0, 0, 0, 0, 0, 0, /* 0xA6 .. 0xAC        Browser */
 4937     0, 0, 0,             /* 0xAD .. 0xAF         Volume */
 4938     0, 0, 0, 0,          /* 0xB0 .. 0xB3          Media */
 4939     0, 0, 0, 0,          /* 0xB4 .. 0xB7           Apps */
 4940 
 4941     /* 0xB8 .. 0xC0 "OEM" keys - all seem to be punctuation.  */
 4942     0, 0, 0, 0, 0, 0, 0, 0, 0,
 4943 
 4944     /* 0xC1 - 0xDA unallocated, 0xDB-0xDF more OEM keys */
 4945     0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
 4946     0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
 4947 
 4948     0,               /* 0xE0                   */
 4949     "ax",            /* VK_OEM_AX         0xE1 */
 4950     0,               /* VK_OEM_102        0xE2 */
 4951     "ico-help",      /* VK_ICO_HELP       0xE3 */
 4952     "ico-00",        /* VK_ICO_00         0xE4 */
 4953     0,               /* VK_PROCESSKEY     0xE5 */
 4954     "ico-clear",     /* VK_ICO_CLEAR      0xE6 */
 4955     "packet",        /* VK_PACKET         0xE7 */
 4956     0,               /*                   0xE8 */
 4957     "reset",         /* VK_OEM_RESET      0xE9 */
 4958     "jump",          /* VK_OEM_JUMP       0xEA */
 4959     "oem-pa1",       /* VK_OEM_PA1        0xEB */
 4960     "oem-pa2",       /* VK_OEM_PA2        0xEC */
 4961     "oem-pa3",       /* VK_OEM_PA3        0xED */
 4962     "wsctrl",        /* VK_OEM_WSCTRL     0xEE */
 4963     "cusel",         /* VK_OEM_CUSEL      0xEF */
 4964     "oem-attn",      /* VK_OEM_ATTN       0xF0 */
 4965     "finish",        /* VK_OEM_FINISH     0xF1 */
 4966     "copy",          /* VK_OEM_COPY       0xF2 */
 4967     "auto",          /* VK_OEM_AUTO       0xF3 */
 4968     "enlw",          /* VK_OEM_ENLW       0xF4 */
 4969     "backtab",       /* VK_OEM_BACKTAB    0xF5 */
 4970     "attn",          /* VK_ATTN           0xF6 */
 4971     "crsel",         /* VK_CRSEL          0xF7 */
 4972     "exsel",         /* VK_EXSEL          0xF8 */
 4973     "ereof",         /* VK_EREOF          0xF9 */
 4974     "play",          /* VK_PLAY           0xFA */
 4975     "zoom",          /* VK_ZOOM           0xFB */
 4976     "noname",        /* VK_NONAME         0xFC */
 4977     "pa1",           /* VK_PA1            0xFD */
 4978     "oem_clear",     /* VK_OEM_CLEAR      0xFE */
 4979     0 /* 0xFF */
 4980   };
 4981 
 4982 /* Some of these duplicate the "Media keys" on newer keyboards,
 4983    but they are delivered to the application in a different way.  */
 4984 static char *lispy_multimedia_keys[] =
 4985   {
 4986     0,
 4987     "browser-back",
 4988     "browser-forward",
 4989     "browser-refresh",
 4990     "browser-stop",
 4991     "browser-search",
 4992     "browser-favorites",
 4993     "browser-home",
 4994     "volume-mute",
 4995     "volume-down",
 4996     "volume-up",
 4997     "media-next",
 4998     "media-previous",
 4999     "media-stop",
 5000     "media-play-pause",
 5001     "mail",
 5002     "media-select",
 5003     "app-1",
 5004     "app-2",
 5005     "bass-down",
 5006     "bass-boost",
 5007     "bass-up",
 5008     "treble-down",
 5009     "treble-up",
 5010     "mic-volume-mute",
 5011     "mic-volume-down",
 5012     "mic-volume-up",
 5013     "help",
 5014     "find",
 5015     "new",
 5016     "open",
 5017     "close",
 5018     "save",
 5019     "print",
 5020     "undo",
 5021     "redo",
 5022     "copy",
 5023     "cut",
 5024     "paste",
 5025     "mail-reply",
 5026     "mail-forward",
 5027     "mail-send",
 5028     "spell-check",
 5029     "toggle-dictate-command",
 5030     "mic-toggle",
 5031     "correction-list",
 5032     "media-play",
 5033     "media-pause",
 5034     "media-record",
 5035     "media-fast-forward",
 5036     "media-rewind",
 5037     "media-channel-up",
 5038     "media-channel-down"
 5039   };
 5040 
 5041 #else /* not HAVE_NTGUI */
 5042 
 5043 /* This should be dealt with in XTread_socket now, and that doesn't
 5044    depend on the client system having the Kana syms defined.  See also
 5045    the XK_kana_A case below.  */
 5046 #if 0
 5047 #ifdef XK_kana_A
 5048 static char *lispy_kana_keys[] =
 5049   {
 5050     /* X Keysym value */
 5051     0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,    /* 0x400 .. 0x40f */
 5052     0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,    /* 0x410 .. 0x41f */
 5053     0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,    /* 0x420 .. 0x42f */
 5054     0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,    /* 0x430 .. 0x43f */
 5055     0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,    /* 0x440 .. 0x44f */
 5056     0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,    /* 0x450 .. 0x45f */
 5057     0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,    /* 0x460 .. 0x46f */
 5058     0,0,0,0,0,0,0,0,0,0,0,0,0,0,"overline",0,
 5059     0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,    /* 0x480 .. 0x48f */
 5060     0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,    /* 0x490 .. 0x49f */
 5061     0, "kana-fullstop", "kana-openingbracket", "kana-closingbracket",
 5062     "kana-comma", "kana-conjunctive", "kana-WO", "kana-a",
 5063     "kana-i", "kana-u", "kana-e", "kana-o",
 5064     "kana-ya", "kana-yu", "kana-yo", "kana-tsu",
 5065     "prolongedsound", "kana-A", "kana-I", "kana-U",
 5066     "kana-E", "kana-O", "kana-KA", "kana-KI",
 5067     "kana-KU", "kana-KE", "kana-KO", "kana-SA",
 5068     "kana-SHI", "kana-SU", "kana-SE", "kana-SO",
 5069     "kana-TA", "kana-CHI", "kana-TSU", "kana-TE",
 5070     "kana-TO", "kana-NA", "kana-NI", "kana-NU",
 5071     "kana-NE", "kana-NO", "kana-HA", "kana-HI",
 5072     "kana-FU", "kana-HE", "kana-HO", "kana-MA",
 5073     "kana-MI", "kana-MU", "kana-ME", "kana-MO",
 5074     "kana-YA", "kana-YU", "kana-YO", "kana-RA",
 5075     "kana-RI", "kana-RU", "kana-RE", "kana-RO",
 5076     "kana-WA", "kana-N", "voicedsound", "semivoicedsound",
 5077     0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,    /* 0x4e0 .. 0x4ef */
 5078     0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,    /* 0x4f0 .. 0x4ff */
 5079   };
 5080 #endif /* XK_kana_A */
 5081 #endif /* 0 */
 5082 
 5083 #define FUNCTION_KEY_OFFSET 0xff00
 5084 
 5085 /* You'll notice that this table is arranged to be conveniently
 5086    indexed by X Windows keysym values.  */
 5087 static char *lispy_function_keys[] =
 5088   {
 5089     /* X Keysym value */
 5090 
 5091     0, 0, 0, 0, 0, 0, 0, 0,                           /* 0xff00...0f */
 5092     "backspace", "tab", "linefeed", "clear",
 5093     0, "return", 0, 0,
 5094     0, 0, 0, "pause",                                 /* 0xff10...1f */
 5095     0, 0, 0, 0, 0, 0, 0, "escape",
 5096     0, 0, 0, 0,
 5097     0, "kanji", "muhenkan", "henkan",                 /* 0xff20...2f */
 5098     "romaji", "hiragana", "katakana", "hiragana-katakana",
 5099     "zenkaku", "hankaku", "zenkaku-hankaku", "touroku",
 5100     "massyo", "kana-lock", "kana-shift", "eisu-shift",
 5101     "eisu-toggle",                                    /* 0xff30...3f */
 5102        0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
 5103     0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,   /* 0xff40...4f */
 5104 
 5105     "home", "left", "up", "right", /* 0xff50 */ /* IsCursorKey */
 5106     "down", "prior", "next", "end",
 5107     "begin", 0, 0, 0, 0, 0, 0, 0,
 5108     "select",                   /* 0xff60 */    /* IsMiscFunctionKey */
 5109     "print",
 5110     "execute",
 5111     "insert",
 5112     0,          /* 0xff64 */
 5113     "undo",
 5114     "redo",
 5115     "menu",
 5116     "find",
 5117     "cancel",
 5118     "help",
 5119     "break",                    /* 0xff6b */
 5120 
 5121     0, 0, 0, 0,
 5122     0, 0, 0, 0, "backtab", 0, 0, 0,             /* 0xff70... */
 5123     0, 0, 0, 0, 0, 0, 0, "kp-numlock",          /* 0xff78... */
 5124     "kp-space",                 /* 0xff80 */    /* IsKeypadKey */
 5125     0, 0, 0, 0, 0, 0, 0, 0,
 5126     "kp-tab",                   /* 0xff89 */
 5127     0, 0, 0,
 5128     "kp-enter",                 /* 0xff8d */
 5129     0, 0, 0,
 5130     "kp-f1",                    /* 0xff91 */
 5131     "kp-f2",
 5132     "kp-f3",
 5133     "kp-f4",
 5134     "kp-home",                  /* 0xff95 */
 5135     "kp-left",
 5136     "kp-up",
 5137     "kp-right",
 5138     "kp-down",
 5139     "kp-prior",                 /* kp-page-up */
 5140     "kp-next",                  /* kp-page-down */
 5141     "kp-end",
 5142     "kp-begin",
 5143     "kp-insert",
 5144     "kp-delete",
 5145     0,                          /* 0xffa0 */
 5146     0, 0, 0, 0, 0, 0, 0, 0, 0,
 5147     "kp-multiply",              /* 0xffaa */
 5148     "kp-add",
 5149     "kp-separator",
 5150     "kp-subtract",
 5151     "kp-decimal",
 5152     "kp-divide",                /* 0xffaf */
 5153     "kp-0",                     /* 0xffb0 */
 5154     "kp-1",     "kp-2", "kp-3", "kp-4", "kp-5", "kp-6", "kp-7", "kp-8", "kp-9",
 5155     0,          /* 0xffba */
 5156     0, 0,
 5157     "kp-equal",                 /* 0xffbd */
 5158     "f1",                       /* 0xffbe */    /* IsFunctionKey */
 5159     "f2",
 5160     "f3", "f4", "f5", "f6", "f7", "f8", "f9", "f10", /* 0xffc0 */
 5161     "f11", "f12", "f13", "f14", "f15", "f16", "f17", "f18",
 5162     "f19", "f20", "f21", "f22", "f23", "f24", "f25", "f26", /* 0xffd0 */
 5163     "f27", "f28", "f29", "f30", "f31", "f32", "f33", "f34",
 5164     "f35", 0, 0, 0, 0, 0, 0, 0, /* 0xffe0 */
 5165     0, 0, 0, 0, 0, 0, 0, 0,
 5166     0, 0, 0, 0, 0, 0, 0, 0,     /* 0xfff0 */
 5167     0, 0, 0, 0, 0, 0, 0, "delete"
 5168   };
 5169 
 5170 /* ISO 9995 Function and Modifier Keys; the first byte is 0xFE.  */
 5171 #define ISO_FUNCTION_KEY_OFFSET 0xfe00
 5172 
 5173 static char *iso_lispy_function_keys[] =
 5174   {
 5175     0, 0, 0, 0, 0, 0, 0, 0,     /* 0xfe00 */
 5176     0, 0, 0, 0, 0, 0, 0, 0,     /* 0xfe08 */
 5177     0, 0, 0, 0, 0, 0, 0, 0,     /* 0xfe10 */
 5178     0, 0, 0, 0, 0, 0, 0, 0,     /* 0xfe18 */
 5179     "iso-lefttab",              /* 0xfe20 */
 5180     "iso-move-line-up", "iso-move-line-down",
 5181     "iso-partial-line-up", "iso-partial-line-down",
 5182     "iso-partial-space-left", "iso-partial-space-right",
 5183     "iso-set-margin-left", "iso-set-margin-right", /* 0xffe27, 28 */
 5184     "iso-release-margin-left", "iso-release-margin-right",
 5185     "iso-release-both-margins",
 5186     "iso-fast-cursor-left", "iso-fast-cursor-right",
 5187     "iso-fast-cursor-up", "iso-fast-cursor-down",
 5188     "iso-continuous-underline", "iso-discontinuous-underline", /* 0xfe30, 31 */
 5189     "iso-emphasize", "iso-center-object", "iso-enter", /* ... 0xfe34 */
 5190   };
 5191 
 5192 #endif /* not HAVE_NTGUI */
 5193 
 5194 Lisp_Object Vlispy_mouse_stem;
 5195 
 5196 static char *lispy_wheel_names[] =
 5197 {
 5198   "wheel-up", "wheel-down", "wheel-left", "wheel-right"
 5199 };
 5200 
 5201 /* drag-n-drop events are generated when a set of selected files are
 5202    dragged from another application and dropped onto an Emacs window.  */
 5203 static char *lispy_drag_n_drop_names[] =
 5204 {
 5205   "drag-n-drop"
 5206 };
 5207 
 5208 /* Scroll bar parts.  */
 5209 Lisp_Object Qabove_handle, Qhandle, Qbelow_handle;
 5210 Lisp_Object Qup, Qdown, Qbottom, Qend_scroll;
 5211 Lisp_Object Qtop, Qratio;
 5212 
 5213 /* An array of scroll bar parts, indexed by an enum scroll_bar_part value.  */
 5214 Lisp_Object *scroll_bar_parts[] = {
 5215   &Qabove_handle, &Qhandle, &Qbelow_handle,
 5216   &Qup, &Qdown, &Qtop, &Qbottom, &Qend_scroll, &Qratio
 5217 };
 5218 
 5219 /* A vector, indexed by button number, giving the down-going location
 5220    of currently depressed buttons, both scroll bar and non-scroll bar.
 5221 
 5222    The elements have the form
 5223      (BUTTON-NUMBER MODIFIER-MASK . REST)
 5224    where REST is the cdr of a position as it would be reported in the event.
 5225 
 5226    The make_lispy_event function stores positions here to tell the
 5227    difference between click and drag events, and to store the starting
 5228    location to be included in drag events.  */
 5229 
 5230 static Lisp_Object button_down_location;
 5231 
 5232 /* Information about the most recent up-going button event:  Which
 5233    button, what location, and what time. */
 5234 
 5235 static int last_mouse_button;
 5236 static int last_mouse_x;
 5237 static int last_mouse_y;
 5238 static unsigned long button_down_time;
 5239 
 5240 /* The maximum time between clicks to make a double-click, or Qnil to
 5241    disable double-click detection, or Qt for no time limit.  */
 5242 
 5243 Lisp_Object Vdouble_click_time;
 5244 
 5245 /* Maximum number of pixels the mouse may be moved between clicks
 5246    to make a double-click.  */
 5247 
 5248 EMACS_INT double_click_fuzz;
 5249 
 5250 /* The number of clicks in this multiple-click. */
 5251 
 5252 int double_click_count;
 5253 
 5254 /* Return position of a mouse click or wheel event */
 5255 
 5256 static Lisp_Object
 5257 make_lispy_position (f, x, y, time)
 5258      struct frame *f;
 5259      Lisp_Object *x, *y;
 5260      unsigned long time;
 5261 {
 5262   Lisp_Object window;
 5263   enum window_part part;
 5264   Lisp_Object posn = Qnil;
 5265   Lisp_Object extra_info = Qnil;
 5266   int wx, wy;
 5267 
 5268   /* Set `window' to the window under frame pixel coordinates (x,y)  */
 5269   if (f)
 5270     window = window_from_coordinates (f, XINT (*x), XINT (*y),
 5271                                       &part, &wx, &wy, 0);
 5272   else
 5273     window = Qnil;
 5274 
 5275   if (WINDOWP (window))
 5276     {
 5277       /* It's a click in window window at frame coordinates (x,y)  */
 5278       struct window *w = XWINDOW (window);
 5279       Lisp_Object string_info = Qnil;
 5280       int textpos = -1, rx = -1, ry = -1;
 5281       int dx = -1, dy = -1;
 5282       int width = -1, height = -1;
 5283       Lisp_Object object = Qnil;
 5284 
 5285       /* Set event coordinates to window-relative coordinates
 5286          for constructing the Lisp event below.  */
 5287       XSETINT (*x, wx);
 5288       XSETINT (*y, wy);
 5289 
 5290       if (part == ON_TEXT)
 5291         {
 5292           wx += WINDOW_LEFT_MARGIN_WIDTH (w);
 5293         }
 5294       else if (part == ON_MODE_LINE || part == ON_HEADER_LINE)
 5295         {
 5296           /* Mode line or header line.  Look for a string under
 5297              the mouse that may have a `local-map' property.  */
 5298           Lisp_Object string;
 5299           int charpos;
 5300 
 5301           posn = part == ON_MODE_LINE ? Qmode_line : Qheader_line;
 5302           rx = wx, ry = wy;
 5303           string = mode_line_string (w, part, &rx, &ry, &charpos,
 5304                                      &object, &dx, &dy, &width, &height);
 5305           if (STRINGP (string))
 5306             string_info = Fcons (string, make_number (charpos));
 5307           if (w == XWINDOW (selected_window)
 5308               && current_buffer == XBUFFER (w->buffer))
 5309             textpos = PT;
 5310           else
 5311             textpos = XMARKER (w->pointm)->charpos;
 5312         }
 5313       else if (part == ON_VERTICAL_BORDER)
 5314         {
 5315           posn = Qvertical_line;
 5316           wx = -1;
 5317           dx = 0;
 5318           width = 1;
 5319         }
 5320       else if (part == ON_LEFT_MARGIN || part == ON_RIGHT_MARGIN)
 5321         {
 5322           Lisp_Object string;
 5323           int charpos;
 5324 
 5325           posn = (part == ON_LEFT_MARGIN) ? Qleft_margin : Qright_margin;
 5326           rx = wx, ry = wy;
 5327           string = marginal_area_string (w, part, &rx, &ry, &charpos,
 5328                                          &object, &dx, &dy, &width, &height);
 5329           if (STRINGP (string))
 5330             string_info = Fcons (string, make_number (charpos));
 5331           if (part == ON_LEFT_MARGIN)
 5332             wx = 0;
 5333           else
 5334             wx = window_box_right_offset (w, TEXT_AREA) - 1;
 5335         }
 5336       else if (part == ON_LEFT_FRINGE)
 5337         {
 5338           posn = Qleft_fringe;
 5339           rx = 0;
 5340           dx = wx;
 5341           wx = (WINDOW_HAS_FRINGES_OUTSIDE_MARGINS (w)
 5342                 ? 0
 5343                 : window_box_width (w, LEFT_MARGIN_AREA));
 5344           dx -= wx;
 5345         }
 5346       else if (part == ON_RIGHT_FRINGE)
 5347         {
 5348           posn = Qright_fringe;
 5349           rx = 0;