* frame.c (Fdelete_frame): Call Fselect_frame with the appropriate
[bpt/emacs.git] / src / keyboard.c
CommitLineData
284f4730 1/* Keyboard and mouse input; editor command loop.
519a3b65 2 Copyright (C) 1985, 1986, 1987, 1988, 1989, 1992 Free Software Foundation, Inc.
284f4730
JB
3
4This file is part of GNU Emacs.
5
6GNU Emacs is free software; you can redistribute it and/or modify
7it under the terms of the GNU General Public License as published by
8the Free Software Foundation; either version 1, or (at your option)
9any later version.
10
11GNU Emacs is distributed in the hope that it will be useful,
12but WITHOUT ANY WARRANTY; without even the implied warranty of
13MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14GNU General Public License for more details.
15
16You should have received a copy of the GNU General Public License
17along with GNU Emacs; see the file COPYING. If not, write to
18the Free Software Foundation, 675 Mass Ave, Cambridge, MA 02139, USA. */
19
20/* Allow config.h to undefine symbols found here. */
21#include <signal.h>
22
23#include "config.h"
24#include <stdio.h>
25#undef NULL
26#include "termchar.h"
27#include "termopts.h"
28#include "lisp.h"
29#include "termhooks.h"
30#include "macros.h"
ff11dfa1 31#include "frame.h"
284f4730
JB
32#include "window.h"
33#include "commands.h"
34#include "buffer.h"
35#include "disptab.h"
36#include "keyboard.h"
37#include <setjmp.h>
38#include <errno.h>
39
284f4730
JB
40#ifndef VMS
41#include <sys/ioctl.h>
284f4730
JB
42#endif
43
52baf19e 44#include "syssignal.h"
6ef5b54f 45#include "systty.h"
ffd56f97 46#include "systime.h"
52baf19e
JB
47
48extern int errno;
49
284f4730
JB
50#ifdef HAVE_X_WINDOWS
51extern Lisp_Object Vmouse_grabbed;
52
53/* Make all keyboard buffers much bigger when using X windows. */
54#define KBD_BUFFER_SIZE 4096
55#else /* No X-windows, character input */
56#define KBD_BUFFER_SIZE 256
57#endif /* No X-windows */
58
59/* Following definition copied from eval.c */
60
61struct backtrace
62 {
63 struct backtrace *next;
64 Lisp_Object *function;
65 Lisp_Object *args; /* Points to vector of args. */
66 int nargs; /* length of vector. If nargs is UNEVALLED,
67 args points to slot holding list of
68 unevalled args */
69 char evalargs;
70 };
71
72/* Non-nil disable property on a command means
73 do not execute it; call disabled-command-hook's value instead. */
74Lisp_Object Qdisabled, Vdisabled_command_hook;
75
76#define NUM_RECENT_KEYS (100)
77int recent_keys_index; /* Index for storing next element into recent_keys */
78int total_keys; /* Total number of elements stored into recent_keys */
79Lisp_Object recent_keys[NUM_RECENT_KEYS]; /* Holds last 100 keystrokes */
80
81/* Buffer holding the key that invoked the current command. */
82Lisp_Object *this_command_keys;
83int this_command_key_count; /* Size in use. */
84int this_command_keys_size; /* Size allocated. */
85
86extern int minbuf_level;
87
88extern struct backtrace *backtrace_list;
89
90/* Nonzero means do menu prompting. */
91static int menu_prompting;
92
93/* Character to see next line of menu prompt. */
94static Lisp_Object menu_prompt_more_char;
95
96/* For longjmp to where kbd input is being done. */
97static jmp_buf getcjmp;
98
99/* True while doing kbd input. */
100int waiting_for_input;
101
102/* True while displaying for echoing. Delays C-g throwing. */
103static int echoing;
104
105/* Nonzero means C-G should cause immediate error-signal. */
106int immediate_quit;
107
108/* Character to recognize as the help char. */
109Lisp_Object help_char;
110
111/* Form to execute when help char is typed. */
112Lisp_Object Vhelp_form;
113
114/* Character that causes a quit. Normally C-g.
115
116 If we are running on an ordinary terminal, this must be an ordinary
117 ASCII char, since we want to make it our interrupt character.
118
119 If we are not running on an ordinary terminal, it still needs to be
120 an ordinary ASCII char. This character needs to be recognized in
121 the input interrupt handler. At this point, the keystroke is
122 represented as a struct input_event, while the desired quit
123 character is specified as a lispy event. The mapping from struct
124 input_events to lispy events cannot run in an interrupt handler,
125 and the reverse mapping is difficult for anything but ASCII
126 keystrokes.
127
128 FOR THESE ELABORATE AND UNSATISFYING REASONS, quit_char must be an
129 ASCII character. */
130int quit_char;
131
132extern Lisp_Object current_global_map;
133extern int minibuf_level;
134
135/* Current depth in recursive edits. */
136int command_loop_level;
137
138/* Total number of times command_loop has read a key sequence. */
139int num_input_keys;
140
141/* Last input character read as a command. */
142Lisp_Object last_command_char;
143
7d6de002
RS
144/* Last input character read as a command, not counting menus
145 reached by the mouse. */
146Lisp_Object last_nonmenu_event;
147
284f4730
JB
148/* Last input character read for any purpose. */
149Lisp_Object last_input_char;
150
151/* If not Qnil, an object to be read as the next command input. */
152Lisp_Object unread_command_char;
153
154/* Char to use as prefix when a meta character is typed in.
155 This is bound on entry to minibuffer in case ESC is changed there. */
156
157Lisp_Object meta_prefix_char;
158
159/* Last size recorded for a current buffer which is not a minibuffer. */
160static int last_non_minibuf_size;
161
06ef7355 162/* Number of idle seconds before an auto-save and garbage collection. */
284f4730
JB
163static Lisp_Object Vauto_save_timeout;
164
165/* Total number of times read_char has returned. */
166int num_input_chars;
167
51172b6d
RS
168/* Total number of times read_char has returned, outside of macros. */
169int num_nonmacro_input_chars;
170
284f4730
JB
171/* Auto-save automatically when this many characters have been typed
172 since the last time. */
173
174static int auto_save_interval;
175
51172b6d 176/* Value of num_nonmacro_input_chars as of last auto save. */
284f4730
JB
177
178int last_auto_save;
179
180/* Last command executed by the editor command loop, not counting
181 commands that set the prefix argument. */
182
183Lisp_Object last_command;
184
185/* The command being executed by the command loop.
186 Commands may set this, and the value set will be copied into last_command
187 instead of the actual command. */
188Lisp_Object this_command;
189
3e51c7b7 190#ifdef MULTI_FRAME
fce33686
JB
191/* The frame in which the last input event occurred, or Qmacro if the
192 last event came from a macro.
ff11dfa1 193 command_loop_1 will select this frame before running the
284f4730
JB
194 command bound to an event sequence, and read_key_sequence will
195 toss the existing prefix if the user starts typing at a
ff11dfa1
JB
196 new frame. */
197Lisp_Object Vlast_event_frame;
3e51c7b7 198#endif
284f4730 199
1113d9db
JB
200/* The timestamp of the last input event we received from the X server.
201 X Windows wants this for selection ownership. */
284f4730
JB
202unsigned long last_event_timestamp;
203
204Lisp_Object Qself_insert_command;
205Lisp_Object Qforward_char;
206Lisp_Object Qbackward_char;
207
208/* read_key_sequence stores here the command definition of the
209 key sequence that it reads. */
210Lisp_Object read_key_sequence_cmd;
211
212/* Form to evaluate (if non-nil) when Emacs is started. */
213Lisp_Object Vtop_level;
214
215/* User-supplied string to translate input characters through. */
216Lisp_Object Vkeyboard_translate_table;
217
218/* Keymap mapping ASCII function key sequences onto their preferred forms. */
219extern Lisp_Object Vfunction_key_map;
220
221/* File in which we write all commands we read. */
222FILE *dribble;
223
224/* Nonzero if input is available. */
225int input_pending;
226
227/* Nonzero if should obey 0200 bit in input chars as "Meta". */
228int meta_key;
229
230extern char *pending_malloc_warning;
231
232/* Circular buffer for pre-read keyboard input. */
233static struct input_event kbd_buffer[KBD_BUFFER_SIZE];
234
235/* Pointer to next available character in kbd_buffer.
236 If kbd_fetch_ptr == kbd_store_ptr, the buffer is empty.
237 This may be kbd_buffer + KBD_BUFFER_SIZE, meaning that the the
238 next available char is in kbd_buffer[0]. */
239static struct input_event *kbd_fetch_ptr;
240
241/* Pointer to next place to store character in kbd_buffer. This
242 may be kbd_buffer + KBD_BUFFER_SIZE, meaning that the next
243 character should go in kbd_buffer[0]. */
244static struct input_event *kbd_store_ptr;
245
246/* The above pair of variables forms a "queue empty" flag. When we
247 enqueue a non-hook event, we increment kbd_write_count. When we
248 dequeue a non-hook event, we increment kbd_read_count. We say that
249 there is input available iff the two counters are equal.
250
251 Why not just have a flag set and cleared by the enqueuing and
252 dequeuing functions? Such a flag could be screwed up by interrupts
253 at inopportune times. */
254
255/* If this flag is non-zero, mouse movement events will appear in the
256 input stream. If is zero, mouse movement will be ignored. */
257int do_mouse_tracking;
258
259/* The window system handling code should set this if the mouse has
260 moved since the last call to the mouse_position_hook. Calling that
261 hook should clear this. Code assumes that if this is set, it can
262 call mouse_position_hook to get the promised position, so don't set
263 it unless you're prepared to substantiate the claim! */
264int mouse_moved;
265
266/* True iff there is an event in kbd_buffer, or if mouse tracking is
267 enabled and there is a new mouse position in the mouse movement
268 buffer. Note that if this is false, that doesn't mean that there
269 is readable input; all the events in the queue might be button-up
270 events, and do_mouse_tracking might be off. */
271#define EVENT_QUEUES_EMPTY \
272 ((kbd_fetch_ptr == kbd_store_ptr) && (!do_mouse_tracking || !mouse_moved))
273
274
275/* Symbols to head events. */
276Lisp_Object Qmouse_movement;
277
278Lisp_Object Qvscrollbar_part;
279Lisp_Object Qvslider_part;
280Lisp_Object Qvthumbup_part;
281Lisp_Object Qvthumbdown_part;
282
283Lisp_Object Qhscrollbar_part;
284Lisp_Object Qhslider_part;
285Lisp_Object Qhthumbleft_part;
286Lisp_Object Qhthumbright_part;
287
288/* Symbols to denote kinds of events. */
289Lisp_Object Qfunction_key;
290Lisp_Object Qmouse_click;
291/* Lisp_Object Qmouse_movement; - also an event header */
292Lisp_Object Qscrollbar_click;
293
294/* Properties of event headers. */
295Lisp_Object Qevent_kind;
296Lisp_Object Qevent_unmodified;
297
298/* Symbols to use for non-text mouse positions. */
299Lisp_Object Qmode_line;
e5d77022 300Lisp_Object Qvertical_line;
284f4730
JB
301
302
ffd56f97
JB
303/* Address (if not 0) of EMACS_TIME to zero out if a SIGIO interrupt
304 happens. */
305EMACS_TIME *input_available_clear_time;
284f4730
JB
306
307/* Nonzero means use SIGIO interrupts; zero means use CBREAK mode.
308 Default is 1 if INTERRUPT_INPUT is defined. */
309int interrupt_input;
310
311/* Nonzero while interrupts are temporarily deferred during redisplay. */
312int interrupts_deferred;
313
314/* nonzero means use ^S/^Q for flow control. */
315int flow_control;
316
284f4730
JB
317/* Allow m- file to inhibit use of FIONREAD. */
318#ifdef BROKEN_FIONREAD
319#undef FIONREAD
320#endif
321
322/* We are unable to use interrupts if FIONREAD is not available,
323 so flush SIGIO so we won't try. */
324#ifndef FIONREAD
325#ifdef SIGIO
326#undef SIGIO
327#endif
328#endif
329
330/* If we support X Windows, and won't get an interrupt when input
331 arrives from the server, poll periodically so we can detect C-g. */
332#ifdef HAVE_X_WINDOWS
333#ifndef SIGIO
334#define POLL_FOR_INPUT
335#endif
336#endif
337\f
338/* Global variable declarations. */
339
340/* Function for init_keyboard to call with no args (if nonzero). */
341void (*keyboard_init_hook) ();
342
343static int read_avail_input ();
344static void get_input_pending ();
345
346/* > 0 if we are to echo keystrokes. */
347static int echo_keystrokes;
348
349/* Nonzero means echo each character as typed. */
350static int immediate_echo;
351
352/* The text we're echoing in the modeline - partial key sequences,
353 usually. '\0'-terminated. */
354static char echobuf[100];
355
356/* Where to append more text to echobuf if we want to. */
357static char *echoptr;
358
359#define min(a,b) ((a)<(b)?(a):(b))
360#define max(a,b) ((a)>(b)?(a):(b))
361
362/* Install the string STR as the beginning of the string of echoing,
363 so that it serves as a prompt for the next character.
364 Also start echoing. */
365
366echo_prompt (str)
367 char *str;
368{
369 int len = strlen (str);
370 if (len > sizeof echobuf - 4)
371 len = sizeof echobuf - 4;
372 bcopy (str, echobuf, len + 1);
373 echoptr = echobuf + len;
374
375 echo ();
376}
377
378/* Add C to the echo string, if echoing is going on.
379 C can be a character, which is printed prettily ("M-C-x" and all that
380 jazz), or a symbol, whose name is printed. */
381
382echo_char (c)
383 Lisp_Object c;
384{
385 extern char *push_key_description ();
386
387 if (immediate_echo)
388 {
389 char *ptr = echoptr;
390
391 if (ptr != echobuf)
392 *ptr++ = ' ';
393
394 /* If someone has passed us a composite event, use its head symbol. */
395 if (EVENT_HAS_PARAMETERS (c))
396 c = EVENT_HEAD (c);
397
398 if (XTYPE (c) == Lisp_Int)
399 {
400 if (ptr - echobuf > sizeof echobuf - 6)
401 return;
402
403 ptr = push_key_description (c, ptr);
404 }
405 else if (XTYPE (c) == Lisp_Symbol)
406 {
407 struct Lisp_String *name = XSYMBOL (c)->name;
408 if (((ptr - echobuf) + name->size + 4) > sizeof echobuf)
409 return;
410 bcopy (name->data, ptr, name->size);
411 ptr += name->size;
412 }
413
414 if (echoptr == echobuf && c == help_char)
415 {
416 strcpy (ptr, " (Type ? for further options)");
417 ptr += strlen (ptr);
418 }
419
420 *ptr = 0;
421 echoptr = ptr;
422
423 echo ();
424 }
425}
426
427/* Temporarily add a dash to the end of the echo string if it's not
428 empty, so that it serves as a mini-prompt for the very next character. */
429
430echo_dash ()
431{
432 if (!immediate_echo && echoptr == echobuf)
433 return;
434
435 /* Put a dash at the end of the buffer temporarily,
436 but make it go away when the next character is added. */
437 echoptr[0] = '-';
438 echoptr[1] = 0;
439
440 echo ();
441}
442
443/* Display the current echo string, and begin echoing if not already
444 doing so. */
445
446echo ()
447{
448 if (!immediate_echo)
449 {
450 int i;
451 immediate_echo = 1;
452
453 for (i = 0; i < this_command_key_count; i++)
454 echo_char (this_command_keys[i]);
455 echo_dash ();
456 }
457
458 echoing = 1;
459 message1 (echobuf);
460 echoing = 0;
461
462 if (waiting_for_input && !NILP (Vquit_flag))
463 quit_throw_to_read_char ();
464}
465
466/* Turn off echoing, for the start of a new command. */
467
468cancel_echoing ()
469{
470 immediate_echo = 0;
471 echoptr = echobuf;
472}
473
474/* Return the length of the current echo string. */
475
476static int
477echo_length ()
478{
479 return echoptr - echobuf;
480}
481
482/* Truncate the current echo message to its first LEN chars.
483 This and echo_char get used by read_key_sequence when the user
ff11dfa1 484 switches frames while entering a key sequence. */
284f4730
JB
485
486static void
487echo_truncate (len)
488 int len;
489{
490 echobuf[len] = '\0';
491 echoptr = echobuf + strlen (echobuf);
492}
493
494\f
495/* Functions for manipulating this_command_keys. */
496static void
497add_command_key (key)
498 Lisp_Object key;
499{
500 if (this_command_key_count == this_command_keys_size)
501 {
502 this_command_keys_size *= 2;
503 this_command_keys
504 = (Lisp_Object *) xrealloc (this_command_keys,
505 (this_command_keys_size
506 * sizeof (Lisp_Object)));
507 }
508 this_command_keys[this_command_key_count++] = key;
509}
510\f
511Lisp_Object
512recursive_edit_1 ()
513{
514 int count = specpdl_ptr - specpdl;
515 Lisp_Object val;
516
517 if (command_loop_level > 0)
518 {
519 specbind (Qstandard_output, Qt);
520 specbind (Qstandard_input, Qt);
521 }
522
523 val = command_loop ();
524 if (EQ (val, Qt))
525 Fsignal (Qquit, Qnil);
526
527 unbind_to (count);
528 return Qnil;
529}
530
531/* When an auto-save happens, record the "time", and don't do again soon. */
532record_auto_save ()
533{
51172b6d 534 last_auto_save = num_nonmacro_input_chars;
284f4730
JB
535}
536\f
537Lisp_Object recursive_edit_unwind (), command_loop ();
538
539DEFUN ("recursive-edit", Frecursive_edit, Srecursive_edit, 0, 0, "",
540 "Invoke the editor command loop recursively.\n\
541To get out of the recursive edit, a command can do `(throw 'exit nil)';\n\
542that tells this function to return.\n\
543Alternately, `(throw 'exit t)' makes this function signal an error.\n\
544This function is called by the editor initialization to begin editing.")
545 ()
546{
547 int count = specpdl_ptr - specpdl;
548 Lisp_Object val;
549
550 command_loop_level++;
551 update_mode_lines = 1;
552
553 record_unwind_protect (recursive_edit_unwind,
554 (command_loop_level
555 && current_buffer != XBUFFER (XWINDOW (selected_window)->buffer))
556 ? Fcurrent_buffer ()
557 : Qnil);
558 recursive_edit_1 ();
559 return unbind_to (count, Qnil);
560}
561
562Lisp_Object
563recursive_edit_unwind (buffer)
564 Lisp_Object buffer;
565{
566 if (!NILP (buffer))
567 Fset_buffer (buffer);
568
569 command_loop_level--;
570 update_mode_lines = 1;
571 return Qnil;
572}
573\f
574Lisp_Object
575cmd_error (data)
576 Lisp_Object data;
577{
578 Lisp_Object errmsg, tail, errname, file_error;
579 Lisp_Object stream;
580 struct gcpro gcpro1;
581 int i;
582
583 Vquit_flag = Qnil;
584 Vinhibit_quit = Qt;
585 Vstandard_output = Qt;
586 Vstandard_input = Qt;
587 Vexecuting_macro = Qnil;
588 echo_area_glyphs = 0;
589
ff11dfa1 590 /* If the window system or terminal frame hasn't been initialized
284f4730
JB
591 yet, or we're not interactive, it's best to dump this message out
592 to stderr and exit. */
ff11dfa1 593 if (! FRAME_MESSAGE_BUF (selected_frame)
284f4730
JB
594 || noninteractive)
595 stream = Qexternal_debugging_output;
596 else
597 {
598 Fdiscard_input ();
599 bitch_at_user ();
600 stream = Qt;
601 }
602
603 errname = Fcar (data);
604
605 if (EQ (errname, Qerror))
606 {
607 data = Fcdr (data);
608 if (!CONSP (data)) data = Qnil;
609 errmsg = Fcar (data);
610 file_error = Qnil;
611 }
612 else
613 {
614 errmsg = Fget (errname, Qerror_message);
615 file_error = Fmemq (Qfile_error,
616 Fget (errname, Qerror_conditions));
617 }
618
619 /* Print an error message including the data items.
620 This is done by printing it into a scratch buffer
621 and then making a copy of the text in the buffer. */
622
623 if (!CONSP (data)) data = Qnil;
624 tail = Fcdr (data);
625 GCPRO1 (tail);
626
627 /* For file-error, make error message by concatenating
628 all the data items. They are all strings. */
629 if (!NILP (file_error) && !NILP (tail))
630 errmsg = XCONS (tail)->car, tail = XCONS (tail)->cdr;
631
632 if (XTYPE (errmsg) == Lisp_String)
633 Fprinc (errmsg, stream);
634 else
635 write_string_1 ("peculiar error", -1, stream);
636
637 for (i = 0; CONSP (tail); tail = Fcdr (tail), i++)
638 {
639 write_string_1 (i ? ", " : ": ", 2, stream);
640 if (!NILP (file_error))
641 Fprinc (Fcar (tail), stream);
642 else
643 Fprin1 (Fcar (tail), stream);
644 }
645 UNGCPRO;
646
ff11dfa1 647 /* If the window system or terminal frame hasn't been initialized
284f4730 648 yet, or we're in -batch mode, this error should cause Emacs to exit. */
ff11dfa1 649 if (! FRAME_MESSAGE_BUF (selected_frame)
284f4730
JB
650 || noninteractive)
651 {
652 Fterpri (stream);
653 Fkill_emacs (make_number (-1));
654 }
655
656 Vquit_flag = Qnil;
657
658 Vinhibit_quit = Qnil;
659 return make_number (0);
660}
661\f
662Lisp_Object command_loop_1 ();
663Lisp_Object command_loop_2 ();
664Lisp_Object top_level_1 ();
665
666/* Entry to editor-command-loop.
667 This level has the catches for exiting/returning to editor command loop.
668 It returns nil to exit recursive edit, t to abort it. */
669
670Lisp_Object
671command_loop ()
672{
673 if (command_loop_level > 0 || minibuf_level > 0)
674 {
675 return internal_catch (Qexit, command_loop_2, Qnil);
676 }
677 else
678 while (1)
679 {
680 internal_catch (Qtop_level, top_level_1, Qnil);
681 internal_catch (Qtop_level, command_loop_2, Qnil);
682
683 /* End of file in -batch run causes exit here. */
684 if (noninteractive)
685 Fkill_emacs (Qt);
686 }
687}
688
689/* Here we catch errors in execution of commands within the
690 editing loop, and reenter the editing loop.
691 When there is an error, cmd_error runs and returns a non-nil
692 value to us. A value of nil means that cmd_loop_1 itself
693 returned due to end of file (or end of kbd macro). */
694
695Lisp_Object
696command_loop_2 ()
697{
698 register Lisp_Object val;
699
700 do
701 val = internal_condition_case (command_loop_1, Qerror, cmd_error);
702 while (!NILP (val));
703
704 return Qnil;
705}
706
707Lisp_Object
708top_level_2 ()
709{
710 return Feval (Vtop_level);
711}
712
713Lisp_Object
714top_level_1 ()
715{
716 /* On entry to the outer level, run the startup file */
717 if (!NILP (Vtop_level))
718 internal_condition_case (top_level_2, Qerror, cmd_error);
719 else if (!NILP (Vpurify_flag))
720 message ("Bare impure Emacs (standard Lisp code not loaded)");
721 else
722 message ("Bare Emacs (standard Lisp code not loaded)");
723 return Qnil;
724}
725
726DEFUN ("top-level", Ftop_level, Stop_level, 0, 0, "",
727 "Exit all recursive editing levels.")
728 ()
729{
730 Fthrow (Qtop_level, Qnil);
731}
732
733DEFUN ("exit-recursive-edit", Fexit_recursive_edit, Sexit_recursive_edit, 0, 0, "",
734 "Exit from the innermost recursive edit or minibuffer.")
735 ()
736{
737 if (command_loop_level > 0 || minibuf_level > 0)
738 Fthrow (Qexit, Qnil);
739
740 error ("No recursive edit is in progress");
741}
742
743DEFUN ("abort-recursive-edit", Fabort_recursive_edit, Sabort_recursive_edit, 0, 0, "",
744 "Abort the command that requested this recursive edit or minibuffer input.")
745 ()
746{
747 if (command_loop_level > 0 || minibuf_level > 0)
748 Fthrow (Qexit, Qt);
749
750 error ("No recursive edit is in progress");
751}
752\f
753/* This is the actual command reading loop,
754 sans error-handling encapsulation. */
755
756Lisp_Object Fcommand_execute ();
757static int read_key_sequence ();
758
759Lisp_Object
760command_loop_1 ()
761{
762 Lisp_Object cmd;
763 int lose;
764 int nonundocount;
765 Lisp_Object keybuf[30];
766 int i;
767 int no_redisplay;
768 int no_direct;
769
770 Vprefix_arg = Qnil;
771 waiting_for_input = 0;
772 cancel_echoing ();
773
774 /* Don't clear out last_command at the beginning of a macro. */
775 if (XTYPE (Vexecuting_macro) != Lisp_String)
776 last_command = Qt;
777
778 nonundocount = 0;
779 no_redisplay = 0;
780 this_command_key_count = 0;
781
782 while (1)
783 {
784 /* Install chars successfully executed in kbd macro. */
785
786 if (defining_kbd_macro && NILP (Vprefix_arg))
787 finalize_kbd_macro_chars ();
788
789 /* Make sure the current window's buffer is selected. */
790 if (XBUFFER (XWINDOW (selected_window)->buffer) != current_buffer)
791 set_buffer_internal (XBUFFER (XWINDOW (selected_window)->buffer));
792
793 /* Display any malloc warning that just came out. Use while because
794 displaying one warning can cause another. */
795
796 while (pending_malloc_warning)
797 display_malloc_warning ();
798
799 no_direct = 0;
800
801 /* If minibuffer on and echo area in use,
802 wait 2 sec and redraw minibufer. */
803
804 if (minibuf_level && echo_area_glyphs)
805 {
f1bed6d8
RS
806 /* Bind inhibit-quit to t so that C-g gets read in
807 rather than quitting back to the minibuffer. */
808 int count = specpdl_ptr - specpdl;
809 specbind (Qinhibit_quit, Qt);
284f4730 810 Fsit_for (make_number (2), Qnil, Qnil);
f1bed6d8
RS
811 unbind_to (count);
812
284f4730
JB
813 echo_area_glyphs = 0;
814 no_direct = 1;
815 if (!NILP (Vquit_flag))
816 {
817 Vquit_flag = Qnil;
818 unread_command_char = make_number (quit_char);
819 }
820 }
821
822#ifdef C_ALLOCA
823 alloca (0); /* Cause a garbage collection now */
824 /* Since we can free the most stuff here. */
825#endif /* C_ALLOCA */
826
827 /* Read next key sequence; i gets its length. */
828 i = read_key_sequence (keybuf, (sizeof keybuf / sizeof (keybuf[0])), 0);
829
830 ++num_input_keys;
831
ff11dfa1
JB
832#ifdef MULTI_FRAME
833 /* Select the frame that the key sequence came from. */
834 if (XTYPE (Vlast_event_frame) == Lisp_Frame
835 && XFRAME (Vlast_event_frame) != selected_frame)
836 Fselect_frame (Vlast_event_frame, Qnil);
284f4730
JB
837#endif
838
839 /* Now we have read a key sequence of length I,
840 or else I is 0 and we found end of file. */
841
842 if (i == 0) /* End of file -- happens only in */
843 return Qnil; /* a kbd macro, at the end. */
844
284f4730
JB
845 last_command_char = keybuf[i - 1];
846
847 cmd = read_key_sequence_cmd;
848 if (!NILP (Vexecuting_macro))
849 {
850 if (!NILP (Vquit_flag))
851 {
852 Vexecuting_macro = Qt;
853 QUIT; /* Make some noise. */
854 /* Will return since macro now empty. */
855 }
856 }
857
858 /* Do redisplay processing after this command except in special
859 cases identified below that set no_redisplay to 1. */
860 no_redisplay = 0;
861
862 /* Execute the command. */
863
864 if (NILP (cmd))
865 {
866 /* nil means key is undefined. */
867 bitch_at_user ();
868 defining_kbd_macro = 0;
869 update_mode_lines = 1;
870 Vprefix_arg = Qnil;
871 }
872 else
873 {
874 this_command = cmd;
875 if (NILP (Vprefix_arg) && ! no_direct)
876 {
877 /* Recognize some common commands in common situations and
878 do them directly. */
879 if (EQ (cmd, Qforward_char) && point < ZV)
880 {
881 struct Lisp_Vector *dp
882 = window_display_table (XWINDOW (selected_window));
883 lose = FETCH_CHAR (point);
884 SET_PT (point + 1);
885 if (((dp == 0 && lose >= 040 && lose < 0177)
886 ||
887 (dp && (XTYPE (dp->contents[lose]) != Lisp_String
888 || XSTRING (dp->contents[lose])->size == sizeof (GLYPH))))
284f4730
JB
889 && (XFASTINT (XWINDOW (selected_window)->last_modified)
890 >= MODIFF)
891 && (XFASTINT (XWINDOW (selected_window)->last_point)
892 == point - 1)
893 && !windows_or_buffers_changed
894 && EQ (current_buffer->selective_display, Qnil)
895 && !detect_input_pending ()
896 && NILP (Vexecuting_macro))
897 no_redisplay = direct_output_forward_char (1);
898 goto directly_done;
899 }
900 else if (EQ (cmd, Qbackward_char) && point > BEGV)
901 {
902 struct Lisp_Vector *dp
903 = window_display_table (XWINDOW (selected_window));
904 SET_PT (point - 1);
905 lose = FETCH_CHAR (point);
906 if (((dp == 0 && lose >= 040 && lose < 0177)
907 ||
908 (dp && (XTYPE (dp->contents[lose]) != Lisp_String
909 || XSTRING (dp->contents[lose])->size == sizeof (GLYPH))))
284f4730
JB
910 && (XFASTINT (XWINDOW (selected_window)->last_modified)
911 >= MODIFF)
912 && (XFASTINT (XWINDOW (selected_window)->last_point)
913 == point + 1)
914 && !windows_or_buffers_changed
915 && EQ (current_buffer->selective_display, Qnil)
916 && !detect_input_pending ()
917 && NILP (Vexecuting_macro))
918 no_redisplay = direct_output_forward_char (-1);
919 goto directly_done;
920 }
921 else if (EQ (cmd, Qself_insert_command)
922 /* Try this optimization only on ascii keystrokes. */
923 && XTYPE (last_command_char) == Lisp_Int)
924 {
925 unsigned char c = XINT (last_command_char);
926
927 if (NILP (Vexecuting_macro) &&
928 !EQ (minibuf_window, selected_window))
929 {
930 if (!nonundocount || nonundocount >= 20)
931 {
932 Fundo_boundary ();
933 nonundocount = 0;
934 }
935 nonundocount++;
936 }
937 lose = (XFASTINT (XWINDOW (selected_window)->last_modified)
938 < MODIFF)
939 || (XFASTINT (XWINDOW (selected_window)->last_point)
940 != point)
941 || MODIFF <= current_buffer->save_modified
942 || windows_or_buffers_changed
943 || !EQ (current_buffer->selective_display, Qnil)
944 || detect_input_pending ()
945 || !NILP (Vexecuting_macro);
946 if (internal_self_insert (c, 0))
947 {
948 lose = 1;
949 nonundocount = 0;
950 }
951 if (!lose &&
952 (point == ZV || FETCH_CHAR (point) == '\n'))
953 {
954 struct Lisp_Vector *dp
955 = window_display_table (XWINDOW (selected_window));
956
957 if (dp == 0 || XTYPE (dp->contents[c]) != Lisp_String)
958 no_redisplay = direct_output_for_insert (c);
959 else if (XSTRING (dp->contents[c])->size
960 == sizeof (GLYPH))
961 no_redisplay =
962 direct_output_for_insert (*(GLYPH *)XSTRING (dp->contents[c])->data);
963 }
964 goto directly_done;
965 }
966 }
967
968 /* Here for a command that isn't executed directly */
969
970 nonundocount = 0;
971 if (NILP (Vprefix_arg))
972 Fundo_boundary ();
973 Fcommand_execute (cmd, Qnil);
974
284f4730 975 }
a764a753 976 directly_done: ;
284f4730
JB
977
978 /* If there is a prefix argument,
979 1) We don't want last_command to be ``universal-argument''
980 (that would be dumb), so don't set last_command,
981 2) we want to leave echoing on so that the prefix will be
982 echoed as part of this key sequence, so don't call
983 cancel_echoing, and
984 3) we want to leave this_command_key_count non-zero, so that
985 read_char will realize that it is re-reading a character, and
986 not echo it a second time. */
987 if (NILP (Vprefix_arg))
988 {
989 last_command = this_command;
990 cancel_echoing ();
991 this_command_key_count = 0;
992 }
993 }
994}
995\f
996/* Number of seconds between polling for input. */
997int polling_period;
998
999/* Nonzero means polling for input is temporarily suppresed. */
1000int poll_suppress_count;
1001
1002#ifdef POLL_FOR_INPUT
1003int polling_for_input;
1004
1005/* Handle an alarm once each second and read pending input
1006 so as to handle a C-g if it comces in. */
1007
1008SIGTYPE
1009input_poll_signal ()
1010{
1011#ifdef HAVE_X_WINDOWS
1012 extern int x_input_blocked;
1013 if (x_input_blocked == 0)
1014#endif
1015 if (!waiting_for_input)
1016 read_avail_input (0);
1017 signal (SIGALRM, input_poll_signal);
1018 alarm (polling_period);
1019}
1020
1021#endif
1022
1023/* Begin signals to poll for input, if they are appropriate.
1024 This function is called unconditionally from various places. */
1025
1026start_polling ()
1027{
1028#ifdef POLL_FOR_INPUT
1029 if (read_socket_hook)
1030 {
1031 poll_suppress_count--;
1032 if (poll_suppress_count == 0)
1033 {
1034 signal (SIGALRM, input_poll_signal);
1035 polling_for_input = 1;
1036 alarm (polling_period);
1037 }
1038 }
1039#endif
1040}
1041
1042/* Turn off polling. */
1043
1044stop_polling ()
1045{
1046#ifdef POLL_FOR_INPUT
1047 if (read_socket_hook)
1048 {
1049 if (poll_suppress_count == 0)
1050 {
1051 polling_for_input = 0;
1052 alarm (0);
1053 }
1054 poll_suppress_count++;
1055 }
1056#endif
1057}
1058\f
1059/* Input of single characters from keyboard */
1060
1061Lisp_Object print_help ();
1062static Lisp_Object kbd_buffer_get_event ();
1063
1064/* read a character from the keyboard; call the redisplay if needed */
1065/* commandflag 0 means do not do auto-saving, but do do redisplay.
1066 -1 means do not do redisplay, but do do autosaving.
1067 1 means do both. */
1068
7d6de002
RS
1069/* The arguments MAPS and NMAPS are for menu prompting.
1070 MAPS is an array of keymaps; NMAPS is the length of MAPS.
1071
1072 PREV_EVENT is the previous input event, or nil if we are reading
1073 the first event of a key sequence.
1074
1075 If we use a mouse menu to read the input, we store 1 into *USED_MOUSE_MENU.
1076 Otherwise we store 0 there. */
1077
284f4730 1078Lisp_Object
7d6de002 1079read_char (commandflag, nmaps, maps, prev_event, used_mouse_menu)
284f4730 1080 int commandflag;
7d6de002
RS
1081 int nmaps;
1082 Lisp_Object *maps;
1083 Lisp_Object prev_event;
1084 int *used_mouse_menu;
284f4730
JB
1085{
1086 register Lisp_Object c;
1087 int count;
1088 jmp_buf save_jump;
1089
1090 if (!NILP (unread_command_char))
1091 {
1092 c = unread_command_char;
1093 unread_command_char = Qnil;
1094
284f4730
JB
1095 if (this_command_key_count == 0)
1096 goto reread_first;
1097 else
1098 goto reread;
1099 }
1100
1101 if (!NILP (Vexecuting_macro))
1102 {
fce33686
JB
1103 /* We set this to Qmacro; since that's not a frame, nobody will
1104 try to switch frames on us, and the selected window will
1105 remain unchanged.
1106
1107 Since this event came from a macro, it would be misleading to
1108 leave Vlast_event_frame set to whereever the last real event
1109 came from. Normally, command_loop_1 selects
1110 Vlast_event_frame after each command is read, but events read
1111 from a macro should never cause a new frame to be selected. */
1112 Vlast_event_frame = Qmacro;
1113
284f4730
JB
1114 if (executing_macro_index >= Flength (Vexecuting_macro))
1115 {
1116 XSET (c, Lisp_Int, -1);
1117 return c;
1118 }
1119
1120 c = Faref (Vexecuting_macro, make_number (executing_macro_index));
1121 executing_macro_index++;
1122
1123 goto from_macro;
1124 }
1125
1126 /* Save outer setjmp data, in case called recursively. */
f76475ad 1127 save_getcjmp (save_jump);
284f4730
JB
1128
1129 stop_polling ();
1130
1131 if (commandflag >= 0 && !input_pending && !detect_input_pending ())
1132 redisplay ();
1133
1134 if (_setjmp (getcjmp))
1135 {
1136 XSET (c, Lisp_Int, quit_char);
ff11dfa1
JB
1137#ifdef MULTI_FRAME
1138 XSET (Vlast_event_frame, Lisp_Frame, selected_frame);
519a3b65 1139#endif
284f4730 1140
284f4730
JB
1141 goto non_reread;
1142 }
1143
1144 /* Message turns off echoing unless more keystrokes turn it on again. */
1145 if (echo_area_glyphs && *echo_area_glyphs && echo_area_glyphs != echobuf)
1146 cancel_echoing ();
1147 else
1148 /* If already echoing, continue. */
1149 echo_dash ();
1150
1151 /* If in middle of key sequence and minibuffer not active,
1152 start echoing if enough time elapses. */
1153 if (minibuf_level == 0 && !immediate_echo && this_command_key_count > 0
1154 && echo_keystrokes > 0
1155 && (echo_area_glyphs == 0 || *echo_area_glyphs == 0))
1156 {
1157 Lisp_Object tem0;
1158
7d6de002
RS
1159 /* After a mouse event, start echoing right away.
1160 This is because we are probably about to display a menu,
1161 and we don't want to delay before doing so. */
1162 if (XTYPE (prev_event) == Lisp_Cons)
284f4730 1163 echo ();
7d6de002
RS
1164 else
1165 {
1166 tem0 = sit_for (echo_keystrokes, 0, 1, 1);
1167 if (EQ (tem0, Qt))
1168 echo ();
1169 }
284f4730
JB
1170 }
1171
1172 /* Maybe auto save due to number of keystrokes or idle time. */
1173
1174 if (commandflag != 0
1175 && auto_save_interval > 0
51172b6d 1176 && num_nonmacro_input_chars - last_auto_save > max (auto_save_interval, 20)
284f4730
JB
1177 && !detect_input_pending ())
1178 {
1179 jmp_buf temp;
1180 save_getcjmp (temp);
1181 Fdo_auto_save (Qnil, Qnil);
1182 restore_getcjmp (temp);
1183 }
1184
7d6de002
RS
1185 /* Try reading a character via menu prompting.
1186 Try this before the sit-for, because the sit-for
1187 would do the wrong thing if we are supposed to do
1188 menu prompting. */
1189 c = Qnil;
1190 if (INTERACTIVE && !NILP (prev_event))
1191 c = read_char_menu_prompt (nmaps, maps, prev_event, used_mouse_menu);
1192
284f4730
JB
1193 /* Slow down auto saves logarithmically in size of current buffer,
1194 and garbage collect while we're at it. */
7d6de002
RS
1195 if (NILP (c))
1196 {
1197 int delay_level, buffer_size;
1198
1199 if (! MINI_WINDOW_P (XWINDOW (selected_window)))
1200 last_non_minibuf_size = Z - BEG;
1201 buffer_size = (last_non_minibuf_size >> 8) + 1;
1202 delay_level = 0;
1203 while (buffer_size > 64)
1204 delay_level++, buffer_size -= buffer_size >> 2;
1205 if (delay_level < 4) delay_level = 4;
1206 /* delay_level is 4 for files under around 50k, 7 at 100k,
1207 9 at 200k, 11 at 300k, and 12 at 500k. It is 15 at 1 meg. */
1208
1209 /* Auto save if enough time goes by without input. */
1210 if (commandflag != 0
51172b6d 1211 && num_nonmacro_input_chars > last_auto_save
7d6de002
RS
1212 && XTYPE (Vauto_save_timeout) == Lisp_Int
1213 && XINT (Vauto_save_timeout) > 0)
1214 {
1215 Lisp_Object tem0;
1216 int delay = delay_level * XFASTINT (Vauto_save_timeout) / 4;
1217 tem0 = sit_for (delay, 0, 1, 1);
1218 if (EQ (tem0, Qt))
1219 {
1220 jmp_buf temp;
1221 save_getcjmp (temp);
1222 Fdo_auto_save (Qnil, Qnil);
1223 restore_getcjmp (temp);
1224
1225 /* If we have auto-saved and there is still no input
1226 available, garbage collect if there has been enough
1227 consing going on to make it worthwhile. */
1228 if (!detect_input_pending ()
1229 && consing_since_gc > gc_cons_threshold / 2)
1230 Fgarbage_collect ();
1231 }
1232 }
1233 }
284f4730
JB
1234
1235 /* Actually read a character, waiting if necessary. */
7d6de002
RS
1236 if (NILP (c))
1237 c = kbd_buffer_get_event ();
284f4730
JB
1238
1239 if (NILP (c))
1240 abort (); /* Don't think this can happen. */
1241
284f4730 1242 /* Terminate Emacs in batch mode if at eof. */
7d6de002 1243 if (noninteractive && XTYPE (c) == Lisp_Int && XINT (c) < 0)
284f4730
JB
1244 Fkill_emacs (make_number (1));
1245
1246 non_reread:
1247
f76475ad 1248 restore_getcjmp (save_jump);
284f4730
JB
1249
1250 start_polling ();
1251
1252 echo_area_glyphs = 0;
1253
1254 /* Handle things that only apply to characters. */
1255 if (XTYPE (c) == Lisp_Int)
1256 {
1257 /* If kbd_buffer_get_event gave us an EOF, return that. */
1258 if (XINT (c) < 0)
1259 return c;
1260
1261 /* Strip the high bits, and maybe the meta bit too. */
1262 XSETINT (c, c & (meta_key ? 0377 : 0177));
1263
1264 if (XTYPE (Vkeyboard_translate_table) == Lisp_String
1265 && XSTRING (Vkeyboard_translate_table)->size > XINT (c))
1266 XSETINT (c, XSTRING (Vkeyboard_translate_table)->data[c]);
1267 }
1268
1269 total_keys++;
1270 recent_keys[recent_keys_index] = c;
1271 if (++recent_keys_index >= (sizeof (recent_keys)/sizeof(recent_keys[0])))
1272 recent_keys_index = 0;
1273
1274 /* Write c to the dribble file. If c is a lispy event, write
1275 the event's symbol to the dribble file, in <brackets>. Bleaugh.
1276 If you, dear reader, have a better idea, you've got the source. :-) */
1277 if (dribble)
1278 {
1279 if (XTYPE (c) == Lisp_Int)
1280 putc (c, dribble);
1281 else
1282 {
1283 Lisp_Object dribblee = c;
1284
1285 /* If it's a structured event, take the event header. */
1286 if (EVENT_HAS_PARAMETERS (dribblee))
1287 dribblee = EVENT_HEAD (dribblee);
1288
1289 if (XTYPE (c) == Lisp_Symbol)
1290 {
1291 putc ('<', dribble);
1292 fwrite (XSYMBOL (c)->name->data, sizeof (char),
1293 XSYMBOL (c)->name->size,
1294 dribble);
1295 putc ('>', dribble);
1296 }
1297 }
1298
1299 fflush (dribble);
1300 }
1301
1302 store_kbd_macro_char (c);
1303
51172b6d
RS
1304 num_nonmacro_input_chars++;
1305
284f4730
JB
1306 from_macro:
1307 reread_first:
1308 echo_char (c);
1309
1310 /* Record this character as part of the current key. */
1311 add_command_key (c);
1312
1313 /* Re-reading in the middle of a command */
1314 reread:
1315 last_input_char = c;
1316 num_input_chars++;
1317
1318 /* Process the help character specially if enabled */
1319 if (EQ (c, help_char) && !NILP (Vhelp_form))
1320 {
1321 Lisp_Object tem0;
1322 count = specpdl_ptr - specpdl;
1323
1324 record_unwind_protect (Fset_window_configuration,
1325 Fcurrent_window_configuration (Qnil));
1326
1327 tem0 = Feval (Vhelp_form);
1328 if (XTYPE (tem0) == Lisp_String)
1329 internal_with_output_to_temp_buffer ("*Help*", print_help, tem0);
1330
1331 cancel_echoing ();
1332 c = read_char (0);
ff11dfa1 1333 /* Remove the help from the frame */
284f4730
JB
1334 unbind_to (count, Qnil);
1335 redisplay ();
1336 if (EQ (c, make_number (040)))
1337 {
1338 cancel_echoing ();
7d6de002 1339 c = read_char (0, 0, 0, Qnil, 0);
284f4730
JB
1340 }
1341 }
1342
1343 return c;
1344}
1345
1346Lisp_Object
1347print_help (object)
1348 Lisp_Object object;
1349{
1350 Fprinc (object, Qnil);
1351 return Qnil;
1352}
1353
1354/* Copy out or in the info on where C-g should throw to.
1355 This is used when running Lisp code from within get_char,
1356 in case get_char is called recursively.
1357 See read_process_output. */
1358
1359save_getcjmp (temp)
1360 jmp_buf temp;
1361{
1362 bcopy (getcjmp, temp, sizeof getcjmp);
1363}
1364
1365restore_getcjmp (temp)
1366 jmp_buf temp;
1367{
1368 bcopy (temp, getcjmp, sizeof getcjmp);
1369}
1370
1371\f
1372/* Low level keyboard/mouse input.
1373 kbd_buffer_store_event places events in kbd_buffer, and
1374 kbd_buffer_get_event retrieves them.
1375 mouse_moved indicates when the mouse has moved again, and
1376 *mouse_position_hook provides the mouse position. */
1377
1378/* Set this for debugging, to have a way to get out */
1379int stop_character;
1380
ff11dfa1 1381extern int frame_garbaged;
284f4730
JB
1382
1383/* Return true iff there are any events in the queue that read-char
1384 would return. If this returns false, a read-char would block. */
1385static int
1386readable_events ()
1387{
1388 struct input_event *ep;
1389
1390 if (EVENT_QUEUES_EMPTY)
1391 return 0;
1392
1393 if (do_mouse_tracking)
1394 return 1;
1395
1396 /* Mouse tracking is disabled, so we need to actually scan the
1397 input queue to see if any events are currently readable. */
1398 for (ep = kbd_fetch_ptr; ep != kbd_store_ptr; ep++)
1399 {
1400 if (ep == kbd_buffer + KBD_BUFFER_SIZE)
1401 ep = kbd_buffer;
1402
1403 /* Skip button-up events. */
1404 if ((ep->kind == mouse_click || ep->kind == scrollbar_click)
1405 && (ep->modifiers & up_modifier))
1406 continue;
1407
1408 return 1;
1409 }
1410
1411 return 0;
1412}
1413
1414
1415/* Restore mouse tracking enablement. See Ftrack_mouse for the only use
1416 of this function. */
1417static Lisp_Object
1418tracking_off (old_value)
1419 Lisp_Object old_value;
1420{
1421 if (! XFASTINT (old_value))
1422 {
1423 do_mouse_tracking = 0;
1424
1425 /* Redisplay may have been preempted because there was input
1426 available, and it assumes it will be called again after the
1427 input has been processed. If the only input available was
1428 the sort that we have just disabled, then we need to call
1429 redisplay. */
1430 if (!readable_events ())
1431 {
1432 redisplay_preserve_echo_area ();
1433 get_input_pending (&input_pending);
1434 }
1435 }
1436}
1437
1438DEFUN ("track-mouse", Ftrack_mouse, Strack_mouse, 0, UNEVALLED, 0,
1439 "Evaluate BODY with mouse movement and button release events enabled.\n\
3371bdfc
RS
1440Within a `track-mouse', mouse motion and button releases generate input\n\
1441events that you can read with `read-event'.\n\
1442Normally, these occurrences don't generate events.")
284f4730
JB
1443 (args)
1444 Lisp_Object args;
1445{
1446 int count = specpdl_ptr - specpdl;
1447 Lisp_Object val;
1448
1449 XSET (val, Lisp_Int, do_mouse_tracking);
1450 record_unwind_protect (tracking_off, val);
1451
1452 do_mouse_tracking = 1;
1453
1454 val = Fprogn (args);
1455 return unbind_to (count, val);
1456}
1457
1458/* Store an event obtained at interrupt level into kbd_buffer, fifo */
1459
1460void
1461kbd_buffer_store_event (event)
1462 register struct input_event *event;
1463{
1464 if (event->kind == no_event)
1465 abort ();
1466
1467 if (event->kind == ascii_keystroke)
1468 {
1469 register int c = XFASTINT (event->code) & 0377;
1470
1471 if (c == quit_char
1472 || ((c == (0200 | quit_char)) && !meta_key))
1473 {
3e51c7b7
JB
1474 extern SIGTYPE interrupt_signal ();
1475
1476#ifdef MULTI_FRAME
284f4730 1477 /* If this results in a quit_char being returned to Emacs as
ff11dfa1 1478 input, set last-event-frame properly. If this doesn't
284f4730 1479 get returned to Emacs as an event, the next event read
ff11dfa1 1480 will set Vlast_event_frame again, so this is safe to do. */
ff11dfa1 1481 Vlast_event_frame = FRAME_FOCUS_FRAME (event->frame);
3e51c7b7
JB
1482#endif
1483
ffd56f97 1484 last_event_timestamp = event->timestamp;
284f4730
JB
1485 interrupt_signal ();
1486 return;
1487 }
1488
1489 if (c && c == stop_character)
1490 {
1491 sys_suspend ();
1492 return;
1493 }
1494
1495 XSET (event->code, Lisp_Int, c);
1496 }
1497
1498 if (kbd_store_ptr - kbd_buffer == KBD_BUFFER_SIZE)
1499 kbd_store_ptr = kbd_buffer;
1500
1501 /* Don't let the very last slot in the buffer become full,
1502 since that would make the two pointers equal,
1503 and that is indistinguishable from an empty buffer.
1504 Discard the event if it would fill the last slot. */
1505 if (kbd_fetch_ptr - 1 != kbd_store_ptr)
1506 {
1507 kbd_store_ptr->kind = event->kind;
1508 kbd_store_ptr->code = event->code;
1509 kbd_store_ptr->part = event->part;
ff11dfa1 1510 kbd_store_ptr->frame = event->frame;
284f4730
JB
1511 kbd_store_ptr->modifiers = event->modifiers;
1512 kbd_store_ptr->x = event->x;
1513 kbd_store_ptr->y = event->y;
1514 kbd_store_ptr->timestamp = event->timestamp;
1515
1516 kbd_store_ptr++;
1517 }
1518}
1519
1520static Lisp_Object make_lispy_event ();
1521static Lisp_Object make_lispy_movement ();
1522static Lisp_Object modify_event_symbol ();
1523
1524static Lisp_Object
1525kbd_buffer_get_event ()
1526{
1527 register int c;
1528 Lisp_Object obj;
1529
1530 if (noninteractive)
1531 {
1532 c = getchar ();
1533 XSET (obj, Lisp_Int, c);
1534 return obj;
1535 }
1536
1537 /* Wait until there is input available. */
1538 for (;;)
1539 {
1540
1541 /* Process or toss any events that we don't want to return as
1542 input. The fact that we remove undesirable events here
1543 allows us to use EVENT_QUEUES_EMPTY in the rest of this loop. */
1544 if (! do_mouse_tracking)
1545 while (kbd_fetch_ptr != kbd_store_ptr)
1546 {
1547 if (kbd_fetch_ptr == kbd_buffer + KBD_BUFFER_SIZE)
1548 kbd_fetch_ptr = kbd_buffer;
1549
1550 if (kbd_fetch_ptr->kind == mouse_click
1551 || kbd_fetch_ptr->kind == scrollbar_click)
1552 {
1553 if ((kbd_fetch_ptr->modifiers & up_modifier) == 0)
1554 break;
1555 }
1556 else
1557 break;
1558
1559 kbd_fetch_ptr++;
1560 }
1561
1562 if (!EVENT_QUEUES_EMPTY)
1563 break;
1564
1565 /* If the quit flag is set, then read_char will return
1566 quit_char, so that counts as "available input." */
1567 if (!NILP (Vquit_flag))
1568 quit_throw_to_read_char ();
1569
1570 /* One way or another, wait until input is available; then, if
1571 interrupt handlers have not read it, read it now. */
1572
1573#ifdef OLDVMS
1574 wait_for_kbd_input ();
1575#else
1576/* Note SIGIO has been undef'd if FIONREAD is missing. */
1577#ifdef SIGIO
1578 gobble_input (0);
1579#endif /* SIGIO */
1580 if (EVENT_QUEUES_EMPTY)
1581 {
f76475ad
JB
1582 Lisp_Object minus_one;
1583
1584 XSET (minus_one, Lisp_Int, -1);
1585 wait_reading_process_input (0, 0, minus_one, 1);
284f4730
JB
1586
1587 if (!interrupt_input && EVENT_QUEUES_EMPTY)
1588 {
1589 read_avail_input (0);
1590 }
1591 }
1592#endif /* not VMS */
1593 }
1594
1595 /* At this point, we know that there is a readable event available
1596 somewhere. If the event queue is empty, then there must be a
1597 mouse movement enabled and available. */
1598 if (kbd_fetch_ptr != kbd_store_ptr)
1599 {
1600 if (kbd_fetch_ptr == kbd_buffer + KBD_BUFFER_SIZE)
1601 kbd_fetch_ptr = kbd_buffer;
3e51c7b7
JB
1602
1603#ifdef MULTI_FRAME
2ce30ea2
JB
1604 XSET (Vlast_event_frame, Lisp_Frame,
1605 XFRAME (FRAME_FOCUS_FRAME (kbd_fetch_ptr->frame)));
3e51c7b7
JB
1606#endif
1607
1113d9db 1608 last_event_timestamp = kbd_fetch_ptr->timestamp;
284f4730
JB
1609 obj = make_lispy_event (kbd_fetch_ptr);
1610 kbd_fetch_ptr->kind = no_event;
1611 kbd_fetch_ptr++;
1612 if (XTYPE (obj) == Lisp_Int)
1613 XSET (obj, Lisp_Int, XINT (obj) & (meta_key ? 0377 : 0177));
1614 }
1615 else if (do_mouse_tracking && mouse_moved)
1616 {
ff11dfa1 1617 FRAME_PTR frame;
e5d77022
JB
1618 Lisp_Object x, y;
1619 unsigned long time;
284f4730 1620
ff11dfa1 1621 (*mouse_position_hook) (&frame, &x, &y, &time);
3e51c7b7 1622#ifdef MULTI_FRAME
ff11dfa1 1623 XSET (Vlast_event_frame, Lisp_Frame, frame);
3e51c7b7 1624#endif
284f4730 1625
ff11dfa1 1626 obj = make_lispy_movement (frame, x, y, time);
284f4730
JB
1627 }
1628 else
1629 /* We were promised by the above while loop that there was
1630 something for us to read! */
1631 abort ();
1632
1633 input_pending = readable_events ();
1634
1635 return (obj);
1636}
1637
1638/* Caches for modify_event_symbol. */
1639static Lisp_Object func_key_syms;
1640static Lisp_Object mouse_syms;
1641
1642/* You'll notice that this table is arranged to be conveniently
1643 indexed by X Windows keysym values. */
1644static char *lispy_function_keys[] =
1645 {
1646 /* X Keysym value */
1647
1648 "home", /* 0xff50 */ /* IsCursorKey */
1649 "left",
1650 "up",
1651 "right",
1652 "down",
1653 "prior",
1654 "next",
1655 "end",
1656 "begin",
1657 0, /* 0xff59 */
1658 0, 0, 0, 0, 0, 0,
1659 "select", /* 0xff60 */ /* IsMiscFunctionKey */
1660 "print",
1661 "execute",
1662 "insert",
1663 0, /* 0xff64 */
1664 "undo",
1665 "redo",
1666 "menu",
1667 "find",
1668 "cancel",
1669 "help",
1670 "break", /* 0xff6b */
1671
1672 /* Here are some keys found mostly on HP keyboards. The X event
1673 handling code will strip bit 29, which flags vendor-specific
1674 keysyms. */
1675 "reset", /* 0x1000ff6c */
1676 "system",
1677 "user",
1678 "clearline",
1679 "insertline",
1680 "deleteline",
1681 "insertchar",
1682 "deletechar",
1683 "backtab",
1684 "kp_backtab", /* 0x1000ff75 */
1685 0, /* 0xff76 */
1686 0, 0, 0, 0, 0, 0, 0, 0, 0, /* 0xff7f */
1687 "kp-space", /* 0xff80 */ /* IsKeypadKey */
1688 0, 0, 0, 0, 0, 0, 0, 0,
1689 "kp-tab", /* 0xff89 */
1690 0, 0, 0,
1691 "kp-enter", /* 0xff8d */
1692 0, 0, 0,
1693 "kp-f1", /* 0xff91 */
1694 "kp-f2",
1695 "kp-f3",
1696 "kp-f4",
1697 0, /* 0xff95 */
1698 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
1699 "kp-multiply", /* 0xffaa */
1700 "kp-add",
1701 "kp-separator",
1702 "kp-subtract",
1703 "kp-decimal",
1704 "kp-divide", /* 0xffaf */
1705 "kp-0", /* 0xffb0 */
1706 "kp-1", "kp-2", "kp-3", "kp-4", "kp-5", "kp-6", "kp-7", "kp-8", "kp-9",
1707 0, /* 0xffba */
1708 0, 0,
1709 "kp-equal", /* 0xffbd */
1710 "f1", /* 0xffbe */ /* IsFunctionKey */
1711 "f2", "f3", "f4",
1712 "f5", "f6", "f7", "f8", "f9", "f10", "f11", "f12",
1713 "f13", "f14", "f15", "f16", "f17", "f18", "f19", "f20",
1714 "f21", "f22", "f23", "f24", "f25", "f26", "f27", "f28",
1715 "f29", "f30", "f31", "f32", "f33", "f34", "f35" /* 0xffe0 */
1716 };
1717
1718static char *lispy_mouse_names[] =
1719{
1720 "mouse-1", "mouse-2", "mouse-3", "mouse-4", "mouse-5"
1721};
1722
1723/* Given a struct input_event, build the lisp event which represents
1724 it. If EVENT is 0, build a mouse movement event from the mouse
1725 movement buffer, which should have a movement event in it. */
1726
1727static Lisp_Object
1728make_lispy_event (event)
1729 struct input_event *event;
1730{
1731#ifdef SWITCH_ENUM_BUG
1732 switch ((int) event->kind)
1733#else
1734 switch (event->kind)
1735#endif
1736 {
1737
1738 /* A simple keystroke. */
1739 case ascii_keystroke:
1740 return event->code;
1741 break;
1742
1743 /* A function key. The symbol may need to have modifier prefixes
1744 tacked onto it. */
1745 case non_ascii_keystroke:
1746 return modify_event_symbol (XFASTINT (event->code), event->modifiers,
1747 Qfunction_key,
1748 lispy_function_keys, &func_key_syms,
1749 (sizeof (lispy_function_keys)
1750 / sizeof (lispy_function_keys[0])));
1751 break;
1752
1753 /* A mouse click - build a list of the relevant information. */
1754 case mouse_click:
1755 {
1756 int part;
1757 Lisp_Object window =
ff11dfa1 1758 window_from_coordinates (event->frame,
284f4730
JB
1759 XINT (event->x), XINT (event->y),
1760 &part);
1761 Lisp_Object posn;
1762
1763 if (XTYPE (window) != Lisp_Window)
1764 posn = Qnil;
1765 else
1766 {
1767 XSETINT (event->x, (XINT (event->x)
1768 - XINT (XWINDOW (window)->left)));
1769 XSETINT (event->y, (XINT (event->y)
1770 - XINT (XWINDOW (window)->top)));
1771
1772 if (part == 1)
1773 posn = Qmode_line;
1774 else if (part == 2)
e5d77022 1775 posn = Qvertical_line;
284f4730
JB
1776 else
1777 XSET (posn, Lisp_Int,
1778 buffer_posn_from_coords (XWINDOW (window),
1779 XINT (event->x),
1780 XINT (event->y)));
1781 }
1782
1783 return Fcons (modify_event_symbol (XFASTINT (event->code) - 1,
1784 event->modifiers,
1785 Qmouse_click,
1786 lispy_mouse_names, &mouse_syms,
1787 (sizeof (lispy_mouse_names)
1788 / sizeof (lispy_mouse_names[0]))),
1789 Fcons (window,
1790 Fcons (posn,
1791 Fcons (Fcons (event->x, event->y),
1113d9db
JB
1792 Fcons (make_number
1793 (event->timestamp),
284f4730
JB
1794 Qnil)))));
1795 }
1796
1797 /* A scrollbar click. Build a list containing the relevant
1798 information. */
1799 case scrollbar_click:
1800 {
1801 Lisp_Object button
1802 = modify_event_symbol (XFASTINT (event->code) - 1,
1803 event->modifiers,
1804 Qmouse_click,
1805 lispy_mouse_names, &mouse_syms,
1806 (sizeof (lispy_mouse_names)
1807 / sizeof (lispy_mouse_names[0])));
1808 return Fcons (event->part,
ff11dfa1 1809 Fcons (FRAME_SELECTED_WINDOW (event->frame),
284f4730
JB
1810 Fcons (button,
1811 Fcons (Fcons (event->x, event->y),
1113d9db
JB
1812 Fcons (make_number
1813 (event->timestamp),
284f4730
JB
1814 Qnil)))));
1815 }
1816
1817 /* The 'kind' field of the event is something we don't recognize. */
1818 default:
1819 abort();
1820 }
1821}
1822
1823static Lisp_Object
ff11dfa1
JB
1824make_lispy_movement (frame, x, y, time)
1825 FRAME_PTR frame;
284f4730 1826 Lisp_Object x, y;
e5d77022 1827 unsigned long time;
284f4730
JB
1828{
1829 Lisp_Object window;
1830 int ix, iy;
1831 Lisp_Object posn;
1832 int part;
1833
1834 ix = XINT (x);
1835 iy = XINT (y);
ff11dfa1
JB
1836 window = (frame
1837 ? window_from_coordinates (frame, ix, iy, &part)
284f4730
JB
1838 : Qnil);
1839 if (XTYPE (window) != Lisp_Window)
1840 posn = Qnil;
1841 else
1842 {
1843 ix -= XINT (XWINDOW (window)->left);
1844 iy -= XINT (XWINDOW (window)->top);
1845 if (part == 1)
1846 posn = Qmode_line;
1847 else if (part == 2)
e5d77022 1848 posn = Qvertical_line;
284f4730
JB
1849 else
1850 XSET (posn, Lisp_Int, buffer_posn_from_coords (XWINDOW (window),
1851 ix, iy));
1852 }
1853
1854 XSETINT (x, ix);
1855 XSETINT (y, iy);
1856 return Fcons (Qmouse_movement,
1857 Fcons (window,
1858 Fcons (posn,
1859 Fcons (Fcons (x, y),
e5d77022 1860 Fcons (make_number (time), Qnil)))));
284f4730
JB
1861}
1862
1863
1864
1865/* Place the written representation of MODIFIERS in BUF, '\0'-terminated,
1866 and return its length. */
1867
1868static int
1869format_modifiers (modifiers, buf)
1870 int modifiers;
1871 char *buf;
1872{
1873 char *p = buf;
1874
fce33686
JB
1875 /* Events with the `up' modifier should always be turned into
1876 click or drag events. */
1877 if (modifiers & up_modifier)
1878 abort ();
1879
1880 if (modifiers & alt_modifier) { *p++ = 'A'; *p++ = '-'; }
1881 if (modifiers & ctrl_modifier) { *p++ = 'C'; *p++ = '-'; }
1882 if (modifiers & hyper_modifier) { *p++ = 'H'; *p++ = '-'; }
1883 if (modifiers & meta_modifier) { *p++ = 'M'; *p++ = '-'; }
284f4730 1884 if (modifiers & shift_modifier) { *p++ = 'S'; *p++ = '-'; }
fce33686
JB
1885 if (modifiers & super_modifier) { strcpy (p, "super-"); p += 6; }
1886 if (modifiers & down_modifier) { strcpy (p, "down-"); p += 5; }
1887 if (modifiers & drag_modifier) { strcpy (p, "drag-"); p += 5; }
284f4730
JB
1888 *p = '\0';
1889
1890 return p - buf;
1891}
1892
1893
1894/* Given a symbol whose name begins with modifiers ("C-", "M-", etc),
1895 return a symbol with the modifiers placed in the canonical order.
fce33686
JB
1896 Canonical order is alphabetical, except for down and drag, which
1897 always come last.
284f4730
JB
1898
1899 Fdefine_key calls this to make sure that (for example) C-M-foo
1900 and M-C-foo end up being equivalent in the keymap. */
1901
1902Lisp_Object
1903reorder_modifiers (symbol)
1904 Lisp_Object symbol;
1905{
1906 struct Lisp_String *name;
1907 int i;
1908 int modifiers;
1909 int not_canonical;
1910
1911 CHECK_SYMBOL (symbol, 1);
1912
1913 modifiers = 0;
1914 name = XSYMBOL (symbol)->name;
1915
1916 /* Special case for things with only one modifier, which is
1917 (hopefully) the vast majority of cases. */
1918 if (! (name->size >= 4 && name->data[1] == '-' && name->data[3] == '-'))
1919 return symbol;
1920
fce33686 1921 for (i = 0; i+1 < name->data[i]; )
284f4730
JB
1922 switch (name->data[i])
1923 {
fce33686
JB
1924 case 'A':
1925 if (name->data[i] != '-') goto no_more_modifiers;
1926 not_canonical |= (modifiers & ~(alt_modifier - 1));
1927 modifiers |= alt_modifier;
1928 i += 2;
284f4730
JB
1929 break;
1930
1931 case 'C':
fce33686
JB
1932 if (name->data[i] != '-') goto no_more_modifiers;
1933 not_canonical |= (modifiers & ~(ctrl_modifier - 1));
284f4730 1934 modifiers |= ctrl_modifier;
fce33686
JB
1935 i += 2;
1936 break;
1937
1938 case 'H':
1939 if (name->data[i] != '-') goto no_more_modifiers;
1940 not_canonical |= (modifiers & ~(hyper_modifier - 1));
1941 modifiers |= hyper_modifier;
1942 i += 2;
1943 break;
1944
1945 case 'M':
1946 if (name->data[i] != '-') goto no_more_modifiers;
1947 not_canonical |= (modifiers & ~(meta_modifier - 1));
1948 modifiers |= meta_modifier;
1949 i += 2;
284f4730
JB
1950 break;
1951
1952 case 'S':
fce33686
JB
1953 if (name->data[i] != '-') goto no_more_modifiers;
1954 not_canonical |= (modifiers & ~(shift_modifier - 1));
284f4730 1955 modifiers |= shift_modifier;
fce33686
JB
1956 i += 2;
1957 break;
1958
1959 case 's':
1960 if (i + 6 > name->size
1961 || strncmp (name->data + i, "super-", 6))
1962 goto no_more_modifiers;
1963 not_canonical |= (modifiers & ~(super_modifier - 1));
1964 modifiers |= super_modifier;
1965 i += 6;
284f4730
JB
1966 break;
1967
fce33686
JB
1968 case 'd':
1969 if (i + 5 > name->size)
1970 goto no_more_modifiers;
1971 if (! strncmp (name->data + i, "drag-", 5))
1972 {
1973 not_canonical |= (modifiers & ~(drag_modifier - 1));
1974 modifiers |= drag_modifier;
1975 i += 5;
1976 }
1977 else if (! strncmp (name->data + i, "down-", 5))
1978 {
1979 not_canonical |= (modifiers & ~(down_modifier - 1));
1980 modifiers |= down_modifier;
1981 i += 5;
1982 }
1983 else
1984 goto no_more_modifiers;
284f4730
JB
1985 break;
1986
1987 default:
1988 goto no_more_modifiers;
1989 }
1990 no_more_modifiers:
1991
1992 if (!not_canonical)
1993 return symbol;
1994
1995 /* The modifiers were out of order, so find a new symbol with the
1996 mods in order. Since the symbol name could contain nulls, we can't
1997 use intern here; we have to use Fintern, which expects a genuine
1998 Lisp_String, and keeps a reference to it. */
1999 {
fce33686 2000 char *new_mods = (char *) alloca (sizeof ("A-C-H-M-S-super-U-down-drag-"));
284f4730
JB
2001 int len = format_modifiers (modifiers, new_mods);
2002 Lisp_Object new_name = make_uninit_string (len + name->size - i);
2003
2004 bcopy (new_mods, XSTRING (new_name)->data, len);
2005 bcopy (name->data + i, XSTRING (new_name)->data + len, name->size - i);
2006
2007 return Fintern (new_name, Qnil);
2008 }
2009}
2010
2011
2012/* For handling events, we often want to produce a symbol whose name
2013 is a series of modifier key prefixes ("M-", "C-", etcetera) attached
2014 to some base, like the name of a function key or mouse button.
2015 modify_event_symbol produces symbols of this sort.
2016
2017 NAME_TABLE should point to an array of strings, such that NAME_TABLE[i]
2018 is the name of the i'th symbol. TABLE_SIZE is the number of elements
2019 in the table.
2020
2021 SYMBOL_TABLE should be a pointer to a Lisp_Object whose value will
2022 persist between calls to modify_event_symbol that it can use to
2023 store a cache of the symbols it's generated for this NAME_TABLE
2024 before.
2025
2026 SYMBOL_NUM is the number of the base name we want from NAME_TABLE.
2027
2028 MODIFIERS is a set of modifier bits (as given in struct input_events)
2029 whose prefixes should be applied to the symbol name.
2030
2031 SYMBOL_KIND is the value to be placed in the event_kind property of
2032 the returned symbol. */
2033
2034static Lisp_Object
2035modify_event_symbol (symbol_num, modifiers, symbol_kind, name_table,
2036 symbol_table, table_size)
2037 int symbol_num;
2038 unsigned modifiers;
2039 Lisp_Object symbol_kind;
2040 char **name_table;
2041 Lisp_Object *symbol_table;
2042 int table_size;
2043{
2044 Lisp_Object *slot, *unmodified_slot;
2045
2046 /* Is this a request for a valid symbol? */
2047 if (symbol_num < 0 || symbol_num >= table_size
2048 || modifiers >= NUM_MODIFIER_COMBOS)
2049 abort ();
2050
2051 /* If *symbol_table is not a vector of the appropriate size,
2052 set it to one. */
2053 if (XTYPE (*symbol_table) != Lisp_Vector
2054 || XVECTOR (*symbol_table)->size != table_size)
2055 *symbol_table = Fmake_vector (make_number (table_size), Qnil);
2056
2057 unmodified_slot = slot = & XVECTOR (*symbol_table)->contents[symbol_num];
2058
2059 /* If there are modifier keys, there had better be a vector in
2060 this symbol's position of the symbol_table. */
2061 if (modifiers != 0)
2062 {
2063 Lisp_Object slot_contents = *slot;
2064
2065 /* If there isn't the right sort of vector there, put one in. */
2066 if (XTYPE (slot_contents) != Lisp_Vector
2067 || XVECTOR (slot_contents)->size != NUM_MODIFIER_COMBOS)
2068 {
2069 *slot = Fmake_vector (make_number (NUM_MODIFIER_COMBOS), Qnil);
2070
2071 /* Make sure that the vector has an entry for the unmodified
2072 symbol, so we can put it on the event_unmodified property. */
2073 if (! NILP (slot_contents))
2074 XVECTOR (*slot)->contents[0] = slot_contents;
2075 else
2076 XVECTOR (*slot)->contents[0] = intern (name_table [symbol_num]);
2077 }
2078 }
2079
2080 /* If this entry has been filled in with a modified symbol vector,
2081 point to the appropriate slot within that. */
2082 if (XTYPE (*slot) == Lisp_Vector)
2083 {
2084 unmodified_slot = & XVECTOR (*slot)->contents[0];
2085 slot = & XVECTOR (*slot)->contents[modifiers];
2086 }
2087
2088 /* Make sure we have an unmodified version of the symbol in its
2089 proper place? */
2090 if (NILP (*unmodified_slot))
2091 {
2092 *unmodified_slot = intern (name_table [symbol_num]);
2093 Fput (*unmodified_slot, Qevent_kind, symbol_kind);
2094 Fput (*unmodified_slot, Qevent_unmodified, *unmodified_slot);
2095 }
2096
2097 /* Have we already created a symbol for this combination of modifiers? */
2098 if (NILP (*slot))
2099 {
2100 /* No, let's create one. */
2101 char *modified_name
2102 = (char *) alloca (sizeof ("C-M-S-U-")
2103 + strlen (name_table [symbol_num]));
2104
2105 strcpy (modified_name + format_modifiers (modifiers, modified_name),
2106 name_table [symbol_num]);
2107
2108 *slot = intern (modified_name);
2109 Fput (*slot, Qevent_kind, symbol_kind);
2110 Fput (*slot, Qevent_unmodified, *unmodified_slot);
2111 }
2112
2113 return *slot;
2114}
2115\f
2116DEFUN ("mouse-click-p", Fmouse_click_p, Smouse_click_p, 1, 1, 0,
2117 "Return non-nil iff OBJECT is a representation of a mouse event.\n\
2118A mouse event is a list of five elements whose car is a symbol of the\n\
2119form <MODIFIERS>mouse-<DIGIT>. I hope this is a temporary hack.")
2120 (object)
2121 Lisp_Object object;
2122{
2123 if (EVENT_HAS_PARAMETERS (object)
2124 && EQ (EVENT_HEAD_KIND (EVENT_HEAD (object)),
2125 Qmouse_click))
2126 return Qt;
2127 else
2128 return Qnil;
2129}
2130\f
2131/* Store into *addr a value nonzero if terminal input chars are available.
2132 Serves the purpose of ioctl (0, FIONREAD, addr)
2133 but works even if FIONREAD does not exist.
2134 (In fact, this may actually read some input.) */
2135
2136static void
2137get_input_pending (addr)
2138 int *addr;
2139{
2140 /* First of all, have we already counted some input? */
2141 *addr = !NILP (Vquit_flag) || readable_events ();
2142
2143 /* If input is being read as it arrives, and we have none, there is none. */
2144 if (*addr > 0 || (interrupt_input && ! interrupts_deferred))
2145 return;
2146
2147 /* Try to read some input and see how much we get. */
2148 gobble_input (0);
2149 *addr = !NILP (Vquit_flag) || readable_events ();
2150}
2151
2152/* Interface to read_avail_input, blocking SIGIO if necessary. */
2153
2154int
2155gobble_input (expected)
2156 int expected;
2157{
2158#ifndef VMS
2159#ifdef SIGIO
2160 if (interrupt_input)
2161 {
32676c08 2162 SIGMASKTYPE mask;
e065a56e 2163 mask = sigblockx (SIGIO);
284f4730 2164 read_avail_input (expected);
e065a56e 2165 sigsetmask (mask);
284f4730
JB
2166 }
2167 else
2168#endif
2169 read_avail_input (expected);
2170#endif
2171}
2172\f
2173#ifndef VMS
2174
2175/* Read any terminal input already buffered up by the system
2176 into the kbd_buffer, but do not wait.
2177
2178 EXPECTED should be nonzero if the caller knows there is some input.
2179
2180 Except on VMS, all input is read by this function.
2181 If interrupt_input is nonzero, this function MUST be called
2182 only when SIGIO is blocked.
2183
2184 Returns the number of keyboard chars read, or -1 meaning
2185 this is a bad time to try to read input. */
2186
2187static int
2188read_avail_input (expected)
2189 int expected;
2190{
2191 struct input_event buf[KBD_BUFFER_SIZE];
2192 register int i;
2193 int nread;
2194
2195 if (read_socket_hook)
2196 /* No need for FIONREAD or fcntl; just say don't wait. */
2197 nread = (*read_socket_hook) (0, buf, KBD_BUFFER_SIZE, expected, expected);
2198 else
2199 {
2200 unsigned char cbuf[KBD_BUFFER_SIZE];
2201
2202#ifdef FIONREAD
2203 /* Find out how much input is available. */
2204 if (ioctl (0, FIONREAD, &nread) < 0)
2205 /* Formerly simply reported no input, but that sometimes led to
2206 a failure of Emacs to terminate.
2207 SIGHUP seems appropriate if we can't reach the terminal. */
2208 kill (getpid (), SIGHUP);
2209 if (nread == 0)
2210 return 0;
2211 if (nread > sizeof cbuf)
2212 nread = sizeof cbuf;
2213#else /* no FIONREAD */
2214#ifdef USG
2215 /* Read some input if available, but don't wait. */
2216 nread = sizeof cbuf;
2217 fcntl (fileno (stdin), F_SETFL, O_NDELAY);
2218#else
2219 you lose;
2220#endif
2221#endif
2222
2223 /* Now read; for one reason or another, this will not block. */
2224 while (1)
2225 {
2226 nread = read (fileno (stdin), cbuf, nread);
2227#ifdef AIX
2228 /* The kernel sometimes fails to deliver SIGHUP for ptys.
2229 This looks incorrect, but it isn't, because _BSD causes
2230 O_NDELAY to be defined in fcntl.h as O_NONBLOCK,
2231 and that causes a value other than 0 when there is no input. */
2232 if (nread == 0)
2233 kill (SIGHUP, 0);
2234#endif
2235 /* Retry the read if it is interrupted. */
2236 if (nread >= 0
2237 || ! (errno == EAGAIN || errno == EFAULT
2238#ifdef EBADSLT
2239 || errno == EBADSLT
2240#endif
2241 ))
2242 break;
2243 }
2244
2245#ifndef FIONREAD
2246#ifdef USG
2247 fcntl (fileno (stdin), F_SETFL, 0);
2248#endif /* USG */
2249#endif /* no FIONREAD */
2250 for (i = 0; i < nread; i++)
2251 {
2252 buf[i].kind = ascii_keystroke;
2253 XSET (buf[i].code, Lisp_Int, cbuf[i]);
ff11dfa1 2254 buf[i].frame = selected_frame;
284f4730
JB
2255 }
2256 }
2257
2258 /* Scan the chars for C-g and store them in kbd_buffer. */
2259 for (i = 0; i < nread; i++)
2260 {
2261 kbd_buffer_store_event (&buf[i]);
2262 /* Don't look at input that follows a C-g too closely.
2263 This reduces lossage due to autorepeat on C-g. */
2264 if (buf[i].kind == ascii_keystroke
2265 && XINT(buf[i].code) == quit_char)
2266 break;
2267 }
2268
2269 return nread;
2270}
2271#endif /* not VMS */
2272\f
2273#ifdef SIGIO /* for entire page */
2274/* Note SIGIO has been undef'd if FIONREAD is missing. */
2275
2ce30ea2 2276SIGTYPE
284f4730
JB
2277input_available_signal (signo)
2278 int signo;
2279{
2280 /* Must preserve main program's value of errno. */
2281 int old_errno = errno;
2282#ifdef BSD4_1
2283 extern int select_alarmed;
2284#endif
2285
2286#ifdef USG
2287 /* USG systems forget handlers when they are used;
2288 must reestablish each time */
2289 signal (signo, input_available_signal);
2290#endif /* USG */
2291
2292#ifdef BSD4_1
2293 sigisheld (SIGIO);
2294#endif
2295
ffd56f97
JB
2296 if (input_available_clear_time)
2297 EMACS_SET_SECS_USECS (*input_available_clear_time, 0, 0);
284f4730
JB
2298
2299 while (1)
2300 {
2301 int nread;
2302 nread = read_avail_input (1);
2303 /* -1 means it's not ok to read the input now.
2304 UNBLOCK_INPUT will read it later; now, avoid infinite loop.
2305 0 means there was no keyboard input available. */
2306 if (nread <= 0)
2307 break;
2308
2309#ifdef BSD4_1
2310 select_alarmed = 1; /* Force the select emulator back to life */
2311#endif
2312 }
2313
2314#ifdef BSD4_1
2315 sigfree ();
2316#endif
2317 errno = old_errno;
2318}
2319#endif /* SIGIO */
2320\f
2321/* Return the prompt-string of a sparse keymap.
2322 This is the first element which is a string.
2323 Return nil if there is none. */
2324
2325Lisp_Object
2326map_prompt (map)
2327 Lisp_Object map;
2328{
2329 while (CONSP (map))
2330 {
2331 register Lisp_Object tem;
2332 tem = Fcar (map);
2333 if (XTYPE (tem) == Lisp_String)
2334 return tem;
2335 map = Fcdr (map);
2336 }
2337 return Qnil;
2338}
2339
2340static int echo_flag;
2341static int echo_now;
2342
2343/* Read a character like read_char but optionally prompt based on maps
7d6de002
RS
2344 in the array MAPS. NMAPS is the length of MAPS.
2345
2346 PREV_EVENT is the previous input event, or nil if we are reading
2347 the first event of a key sequence.
2348
2349 If we use a mouse menu to read the input, we store 1 into *USED_MOUSE_MENU.
2350 Otherwise we store 0 there.
284f4730
JB
2351
2352 The prompting is done based on the prompt-string of the map
2353 and the strings associated with various map elements. */
2354
2355Lisp_Object
7d6de002
RS
2356read_char_menu_prompt (nmaps, maps, prev_event, used_mouse_menu)
2357 int nmaps;
2358 Lisp_Object *maps;
2359 Lisp_Object prev_event;
2360 int *used_mouse_menu;
284f4730 2361{
7d6de002
RS
2362 int mapno;
2363 register Lisp_Object name;
284f4730 2364 int nlength;
ff11dfa1 2365 int width = FRAME_WIDTH (selected_frame) - 4;
7d6de002
RS
2366 char *menu = (char *) alloca (width + 4);
2367 int idx = -1;
2368 Lisp_Object rest, vector;
2369
2370 *used_mouse_menu = 0;
284f4730
JB
2371
2372 /* Use local over global Menu maps */
2373
7d6de002
RS
2374 if (! menu_prompting)
2375 return Qnil;
2376
2377 /* Get the menu name from the first map that has one (a prompt string). */
2378 for (mapno = 0; mapno < nmaps; mapno++)
2379 {
2380 name = map_prompt (maps[mapno]);
2381 if (!NILP (name))
2382 break;
2383 }
284f4730 2384
7d6de002 2385 /* If we don't have any menus, just read a character normally. */
284f4730 2386 if (NILP (name))
7d6de002
RS
2387 return Qnil;
2388
72cea080
RS
2389#ifdef HAVE_X_WINDOW
2390#ifndef NO_X_MENU
7d6de002
RS
2391 /* If we got to this point via a mouse click,
2392 use a real menu for mouse selection. */
2393 if (XTYPE (prev_event) == Lisp_Cons)
2394 {
2395 /* Display the menu and get the selection. */
2396 Lisp_Object *realmaps
2397 = (Lisp_Object *) alloca (nmaps * sizeof (Lisp_Object));
2398 Lisp_Object value;
2399 int nmaps1 = 0;
2400
2401 /* Use the maps that are not nil. */
2402 for (mapno = 0; mapno < nmaps; mapno++)
2403 if (!NILP (maps[mapno]))
2404 realmaps[nmaps1++] = maps[mapno];
2405
2406 value = Fx_popup_menu (prev_event, Flist (nmaps1, realmaps));
2407 if (NILP (value))
2408 XSET (value, Lisp_Int, quit_char);
2409 *used_mouse_menu = 1;
2410 return value;
2411 }
72cea080
RS
2412#endif /* not NO_X_MENU */
2413#endif /* HAVE_X_WINDOW */
284f4730
JB
2414
2415 /* Prompt string always starts with map's prompt, and a space. */
2416 strcpy (menu, XSTRING (name)->data);
2417 nlength = XSTRING (name)->size;
7d6de002 2418 menu[nlength++] = ':';
284f4730
JB
2419 menu[nlength++] = ' ';
2420 menu[nlength] = 0;
2421
7d6de002
RS
2422 /* Start prompting at start of first map. */
2423 mapno = 0;
2424 rest = maps[mapno];
284f4730
JB
2425
2426 /* Present the documented bindings, a line at a time. */
2427 while (1)
2428 {
2429 int notfirst = 0;
2430 int i = nlength;
2431 Lisp_Object obj;
2432 int ch;
2433
284f4730 2434 /* Loop over elements of map. */
7d6de002 2435 while (i < width)
284f4730 2436 {
7d6de002 2437 Lisp_Object s, elt;
284f4730 2438
7d6de002
RS
2439 /* If reached end of map, start at beginning of next map. */
2440 if (NILP (rest))
2441 {
2442 mapno++;
2443 /* At end of last map, wrap around to first map if just starting,
2444 or end this line if already have something on it. */
2445 if (mapno == nmaps)
284f4730 2446 {
7d6de002
RS
2447 if (notfirst)
2448 break;
2449 else
2450 mapno = 0;
284f4730 2451 }
7d6de002 2452 rest = maps[mapno];
284f4730 2453 }
7d6de002
RS
2454
2455 /* Look at the next element of the map. */
2456 if (idx >= 0)
2457 elt = XVECTOR (vector)->contents[idx];
284f4730 2458 else
7d6de002
RS
2459 elt = Fcar_safe (rest);
2460
2461 if (idx < 0 && XTYPE (elt) == Lisp_Vector)
284f4730 2462 {
7d6de002
RS
2463 /* If we found a dense table in the keymap,
2464 advanced past it, but start scanning its contents. */
2465 rest = Fcdr_safe (rest);
2466 vector = elt;
2467 idx = 0;
284f4730 2468 }
7d6de002
RS
2469 else
2470 {
2471 /* An ordinary element. */
2472 s = Fcar_safe (Fcdr_safe (elt));
2473 if (XTYPE (s) != Lisp_String)
2474 /* Ignore the element if it has no prompt string. */
2475 ;
2476 /* If we have room for the prompt string, add it to this line.
2477 If this is the first on the line, always add it. */
2478 else if (XSTRING (s)->size + i < width
2479 || !notfirst)
2480 {
2481 int thiswidth;
284f4730 2482
7d6de002
RS
2483 /* Punctuate between strings. */
2484 if (notfirst)
2485 {
2486 strcpy (menu + i, ", ");
2487 i += 2;
2488 }
2489 notfirst = 1;
2490
2491 /* Add as much of string as fits. */
2492 thiswidth = XSTRING (s)->size;
2493 if (thiswidth + i > width)
2494 thiswidth = width - i;
2495 bcopy (XSTRING (s)->data, menu + i, thiswidth);
2496 i += thiswidth;
2497 }
2498 else
2499 {
2500 /* If this element does not fit, end the line now,
2501 and save the element for the next line. */
2502 strcpy (menu + i, "...");
2503 break;
2504 }
2505
2506 /* Move past this element. */
2507 if (idx >= 0 && idx + 1 >= XVECTOR (rest)->size)
2508 /* Handle reaching end of dense table. */
2509 idx = -1;
2510 if (idx >= 0)
2511 idx++;
2512 else
2513 rest = Fcdr_safe (rest);
2514 }
284f4730
JB
2515 }
2516
2517 /* Prompt with that and read response. */
2518 message1 (menu);
7d6de002 2519 obj = read_char (1, 0, 0, Qnil, 0);
284f4730
JB
2520
2521 if (XTYPE (obj) != Lisp_Int)
2522 return obj;
2523 else
2524 ch = XINT (obj);
2525
2526 if (obj != menu_prompt_more_char
2527 && (XTYPE (menu_prompt_more_char) != Lisp_Int
2528 || obj != make_number (Ctl (XINT (menu_prompt_more_char)))))
2529 return obj;
2530 }
2531}
284f4730
JB
2532\f
2533/* Reading key sequences. */
2534
2535/* Follow KEY in the maps in CURRENT[0..NMAPS-1], placing its bindings
2536 in DEFS[0..NMAPS-1]. Set NEXT[i] to DEFS[i] if DEFS[i] is a
2537 keymap, or nil otherwise. Return the index of the first keymap in
2538 which KEY has any binding, or NMAPS if no map has a binding.
2539
2540 If KEY is a meta ASCII character, treat it like meta-prefix-char
2541 followed by the corresponding non-meta character. Keymaps in
2542 CURRENT with non-prefix bindings for meta-prefix-char become nil in
2543 NEXT.
2544
2545 When KEY is not defined in any of the keymaps, if it is an upper
2546 case letter and there are bindings for the corresponding lower-case
2547 letter, return the bindings for the lower-case letter.
2548
2549 NEXT may == CURRENT. */
2550
2551static int
2552follow_key (key, nmaps, current, defs, next)
2553 Lisp_Object key;
2554 Lisp_Object *current, *defs, *next;
2555 int nmaps;
2556{
2557 int i, first_binding;
2558
2559 /* If KEY is a meta ASCII character, treat it like meta-prefix-char
2560 followed by the corresponding non-meta character. */
2561 if (XTYPE (key) == Lisp_Int
2562 && XINT (key) >= 0200)
2563 {
2564 for (i = 0; i < nmaps; i++)
2565 if (! NILP (current[i]))
2566 {
2567 next[i] = get_keyelt (access_keymap (current[i],
2568 meta_prefix_char));
2569
2570 /* Note that since we pass the resulting bindings through
2571 get_keymap_1, non-prefix bindings for meta-prefix-char
2572 disappear. */
2573 next[i] = get_keymap_1 (next[i], 0);
2574 }
2575 else
2576 next[i] = Qnil;
2577
2578 current = next;
2579 XSET (key, Lisp_Int, XFASTINT (key) & 0177);
2580 }
2581
2582 first_binding = nmaps;
2583 for (i = nmaps - 1; i >= 0; i--)
2584 {
2585 if (! NILP (current[i]))
2586 {
2587 defs[i] = get_keyelt (access_keymap (current[i], key));
2588 if (! NILP (defs[i]))
2589 first_binding = i;
2590 }
2591 else
2592 defs[i] = Qnil;
2593 }
2594
2595 /* When KEY is not defined in any of the keymaps, if it is an upper
2596 case letter and there are bindings for the corresponding
2597 lower-case letter, return the bindings for the lower-case letter. */
2598 if (first_binding == nmaps
2599 && XTYPE (key) == Lisp_Int
2600 && UPPERCASEP (XINT (key)))
2601 {
2602 XSETINT (key, DOWNCASE (XINT (key)));
2603
2604 first_binding = nmaps;
2605 for (i = nmaps - 1; i >= 0; i--)
2606 {
2607 if (! NILP (current[i]))
2608 {
2609 defs[i] = get_keyelt (access_keymap (current[i], key));
2610 if (! NILP (defs[i]))
2611 first_binding = i;
2612 }
2613 else
2614 defs[i] = Qnil;
2615 }
2616 }
2617
2618 /* Given the set of bindings we've found, produce the next set of maps. */
2619 for (i = 0; i < nmaps; i++)
2620 next[i] = NILP (defs[i]) ? Qnil : get_keymap_1 (defs[i], 0);
2621
2622 return first_binding;
2623}
2624
2625/* Read a sequence of keys that ends with a non prefix character
2626 according to the keymaps in KEYMAPS[0..nmaps-1]. Keymaps appearing
2627 earlier in KEYMAPS take precidence over those appearing later.
2628
2629 Store the sequence in KEYBUF, a buffer of size BUFSIZE. Prompt
2630 with PROMPT. Echo starting immediately unless `prompt' is 0.
2631 Return the length of the key sequence stored.
2632
ff11dfa1 2633 If the user switches frames in the midst of a key sequence, we
284f4730
JB
2634 throw away any prefix we have read so far, and start afresh. For
2635 mouse clicks, we look up the click in the keymap of the buffer
2636 clicked on, throwing away any prefix if it is not the same buffer
2637 we used to be reading from. */
2638
2639static int
2640read_key_sequence (keybuf, bufsize, prompt)
2641 Lisp_Object *keybuf;
2642 int bufsize;
2643 Lisp_Object prompt;
2644{
2645 /* How many keys there are in the current key sequence. */
2646 int t;
2647
2648 /* The buffer that the most recently read event was typed at. This
2649 helps us read mouse clicks according to the buffer clicked in,
ff11dfa1 2650 and notice when the mouse has moved from one frame to another. */
284f4730
JB
2651 struct buffer *last_event_buffer = current_buffer;
2652
2653 /* The length of the echo buffer when we started reading, and
2654 the length of this_command_keys when we started reading. */
2655 int echo_start;
2656 int keys_start = this_command_key_count;
2657
2658 /* The number of keymaps we're scanning right now, and the number of
2659 keymaps we have allocated space for. */
2660 int nmaps;
2661 int nmaps_allocated = 0;
2662
253598e4 2663 /* submaps[0..nmaps-1] are the prefix definitions of KEYBUF[0..t-1]
284f4730 2664 in the current keymaps, or nil where it is not a prefix. */
253598e4 2665 Lisp_Object *submaps;
284f4730
JB
2666
2667 /* defs[0..nmaps-1] are the definitions of KEYBUF[0..t-1] in
2668 the current keymaps. */
2669 Lisp_Object *defs;
2670
253598e4
JB
2671 /* The index of the first keymap that has a binding for this key
2672 sequence. In other words, the lowest i such that defs[i] is
2673 non-nil.*/
284f4730
JB
2674 int first_binding;
2675
2676 /* If mock_input > t, then KEYBUF[t] should be read as the next
253598e4
JB
2677 input key.
2678
2679 We use this to recover after recognizing a function key. Once we
2680 realize that a suffix of the current key sequence is actually a
2681 function key's escape sequence, we replace the suffix with the
2682 function key's binding from Vfunction_key_map. Now keybuf
2683 contains a new and different key sequence, so the echo area and
2684 the submaps and defs arrays are wrong. In this situation, we set
2685 mock_input to t, set t to 0, and jump to restart; the loop will
2686 read keys from keybuf up until mock_input, which rebuilds the
2687 state, and then it will resume reading characters from the keyboard. */
284f4730
JB
2688 int mock_input = 0;
2689
253598e4
JB
2690 /* If the sequence is unbound in submaps[], then
2691 keymap[fkey_start..fkey_end-1] is a prefix in Vfunction_key_map,
2692 and fkey_map is its binding. If mock_input is in use, these
2693 might be > t, indicating that all function key scanning should
284f4730 2694 hold off until t reaches them. */
253598e4 2695
284f4730
JB
2696 int fkey_start = 0, fkey_end = 0;
2697 Lisp_Object fkey_map = Vfunction_key_map;
2698
7d6de002
RS
2699 last_nonmenu_event = Qnil;
2700
284f4730
JB
2701 if (INTERACTIVE)
2702 {
2703 if (prompt)
2704 echo_prompt (prompt);
2705 else if (cursor_in_echo_area)
2706 /* This doesn't put in a dash if the echo buffer is empty, so
2707 you don't always see a dash hanging out in the minibuffer. */
2708 echo_dash ();
2709 echo_start = echo_length ();
2710 }
2711
253598e4 2712 /* If there is no function key map, turn off function key scanning. */
284f4730
JB
2713 if (NILP (Fkeymapp (Vfunction_key_map)))
2714 fkey_start = fkey_end = bufsize + 1;
2715
2716 restart:
2717 t = 0;
2718 this_command_key_count = keys_start;
2719
2720 {
2721 Lisp_Object *maps;
2722
2723 nmaps = current_minor_maps (0, &maps) + 2;
2724 if (nmaps > nmaps_allocated)
2725 {
253598e4 2726 submaps = (Lisp_Object *) alloca (nmaps * sizeof (submaps[0]));
284f4730
JB
2727 defs = (Lisp_Object *) alloca (nmaps * sizeof (defs[0]));
2728 nmaps_allocated = nmaps;
2729 }
253598e4
JB
2730 bcopy (maps, submaps, (nmaps - 2) * sizeof (submaps[0]));
2731 submaps[nmaps-2] = last_event_buffer->keymap;
2732 submaps[nmaps-1] = global_map;
284f4730
JB
2733 }
2734
2735 /* Find an accurate initial value for first_binding. */
2736 for (first_binding = 0; first_binding < nmaps; first_binding++)
253598e4 2737 if (! NILP (submaps[first_binding]))
284f4730
JB
2738 break;
2739
253598e4 2740 while ((first_binding < nmaps && ! NILP (submaps[first_binding]))
284f4730
JB
2741 || (first_binding >= nmaps && fkey_start < t))
2742 {
2743 Lisp_Object key;
7d6de002 2744 int used_mouse_menu = 0;
284f4730
JB
2745
2746 if (t >= bufsize)
2747 error ("key sequence too long");
2748
253598e4 2749 /* Are we re-reading a key sequence, as indicated by mock_input? */
284f4730
JB
2750 if (t < mock_input)
2751 {
2752 key = keybuf[t];
2753 add_command_key (key);
2754 echo_char (key);
2755 }
253598e4
JB
2756
2757 /* If not, we should actually read a character. */
284f4730
JB
2758 else
2759 {
2760 struct buffer *buf;
2761
7d6de002
RS
2762 key = read_char (!prompt, nmaps, submaps, last_nonmenu_event,
2763 &used_mouse_menu);
284f4730
JB
2764
2765 /* The above routines return -1 at the end of a macro.
2766 Emacs 18 handles this by returning immediately with a
2767 zero, so that's what we'll do. */
2768 if (XTYPE (key) == Lisp_Int && XINT (key) < 0)
2769 return 0;
2770
2771 Vquit_flag = Qnil;
2772
ff11dfa1 2773#ifdef MULTI_FRAME
284f4730 2774 /* What buffer was this event typed/moused at? */
7d6de002
RS
2775 if (used_mouse_menu)
2776 /* Never change last_event_buffer for using a menu. */
2777 buf = last_event_buffer;
2778 else if (XTYPE (key) == Lisp_Int || XTYPE (key) == Lisp_Symbol)
fce33686
JB
2779 {
2780 buf = ((XTYPE (Vlast_event_frame) == Lisp_Frame)
2781 ? (XBUFFER
2782 (XWINDOW
2783 (FRAME_SELECTED_WINDOW
2784 (XFRAME (Vlast_event_frame)))->buffer))
2785 : last_event_buffer);
2786 }
284f4730
JB
2787 else if (EVENT_HAS_PARAMETERS (key))
2788 {
2789 Lisp_Object window = EVENT_WINDOW (key);
2790
2791 if (NILP (window))
2792 abort ();
2793
2794 buf = XBUFFER (XWINDOW (window)->buffer);
2795 }
2796 else
2797 abort ();
2798
2799 /* If this event came to a different buffer than the one
2800 we're currently in, switch buffers and start a new key
2801 sequence, starting with key. */
2802 if (buf != last_event_buffer)
2803 {
2804 last_event_buffer = buf;
ff11dfa1 2805 Fselect_frame (Vlast_event_frame, Qnil);
284f4730
JB
2806
2807 /* Arrange to read key as the next event. */
2808 keybuf[0] = key;
2809 mock_input = 1;
2810
2811 /* Truncate the key sequence in the echo area. */
2812 if (INTERACTIVE)
2813 echo_truncate (echo_start);
2814
2815 goto restart;
2816 }
e5d77022 2817#endif
284f4730
JB
2818 }
2819
2820 first_binding = (follow_key (key,
2821 nmaps - first_binding,
253598e4 2822 submaps + first_binding,
284f4730 2823 defs + first_binding,
253598e4 2824 submaps + first_binding)
284f4730
JB
2825 + first_binding);
2826 keybuf[t++] = key;
7d6de002
RS
2827 /* Normally, last_nonmenu_event gets the previous key we read.
2828 But when a mouse popup menu is being used,
2829 we don't update last_nonmenu_event; it continues to hold the mouse
2830 event that preceded the first level of menu. */
2831 if (!used_mouse_menu)
2832 last_nonmenu_event = key;
284f4730
JB
2833
2834 /* If the sequence is unbound, see if we can hang a function key
253598e4
JB
2835 off the end of it. We only want to scan real keyboard input
2836 for function key sequences, so if mock_input says that we're
2837 re-scanning after expanding a function key, don't examine it. */
284f4730 2838 if (first_binding >= nmaps
253598e4 2839 && t >= mock_input)
284f4730
JB
2840 {
2841 Lisp_Object fkey_next;
2842
2843 /* Scan from fkey_end until we find a bound suffix. */
2844 while (fkey_end < t)
2845 {
067ffa38
JB
2846 /* Look up meta-characters by prefixing them
2847 with meta_prefix_char. I hate this. */
253598e4 2848 if (keybuf[fkey_end] & 0x80)
067ffa38
JB
2849 fkey_next =
2850 get_keymap_1 (get_keyelt
2851 (access_keymap (fkey_map, meta_prefix_char)),
2852 0);
2853 else
2854 fkey_next = fkey_map;
2855
284f4730 2856 fkey_next =
067ffa38 2857 get_keyelt (access_keymap
85bc5181 2858 (fkey_next, keybuf[fkey_end++] & 0x7f));
067ffa38 2859
85bc5181 2860 /* If keybuf[fkey_start..fkey_end] is bound in the
a764a753 2861 function key map and it's a suffix of the current
85bc5181 2862 sequence (i.e. fkey_end == t), replace it with
a764a753 2863 the binding and restart with fkey_start at the end. */
284f4730
JB
2864 if (XTYPE (fkey_next) == Lisp_Vector
2865 && fkey_end == t)
2866 {
2867 t = fkey_start + XVECTOR (fkey_next)->size;
2868 if (t >= bufsize)
2869 error ("key sequence too long");
2870
2871 bcopy (XVECTOR (fkey_next)->contents,
2872 keybuf + fkey_start,
2873 (t - fkey_start) * sizeof (keybuf[0]));
2874
2875 mock_input = t;
2876 fkey_start = fkey_end = t;
2877
2878 /* Truncate the key sequence in the echo area. */
2879 if (INTERACTIVE)
2880 echo_truncate (echo_start);
2881
2882 goto restart;
2883 }
2884
2885 fkey_map = get_keymap_1 (fkey_next, 0);
2886
a764a753
JB
2887 /* If we no longer have a bound suffix, try a new positions for
2888 fkey_start. */
284f4730
JB
2889 if (NILP (fkey_map))
2890 {
2891 fkey_end = ++fkey_start;
2892 fkey_map = Vfunction_key_map;
2893 }
2894 }
2895 }
2896 }
2897
2898 read_key_sequence_cmd = (first_binding < nmaps
2899 ? defs[first_binding]
2900 : Qnil);
2901
2902 return t;
2903}
2904
c0a58692 2905DEFUN ("read-key-sequence", Fread_key_sequence, Sread_key_sequence, 1, 2, 0,
284f4730
JB
2906 "Read a sequence of keystrokes and return as a string or vector.\n\
2907The sequence is sufficient to specify a non-prefix command in the\n\
2908current local and global maps.\n\
2909\n\
c0a58692
RS
2910First arg PROMPT is a prompt string. If nil, do not prompt specially.\n\
2911Second (optional) arg CONTINUE-ECHO, if non-nil, means this key echos\n\
2912as a continuation of the previous key.\n\
284f4730 2913\n\
ff11dfa1 2914If Emacs is running on multiple frames, switching between frames in\n\
284f4730
JB
2915the midst of a keystroke will toss any prefix typed so far. A C-g\n\
2916typed while in this function is treated like any other character, and\n\
2917`quit-flag' is not set.")
c0a58692
RS
2918 (prompt, continue_echo)
2919 Lisp_Object prompt, continue_echo;
284f4730
JB
2920{
2921 Lisp_Object keybuf[30];
2922 register int i;
2923 struct gcpro gcpro1, gcpro2;
2924
2925 if (!NILP (prompt))
2926 CHECK_STRING (prompt, 0);
2927 QUIT;
2928
2929 bzero (keybuf, sizeof keybuf);
2930 GCPRO1 (keybuf[0]);
2931 gcpro1.nvars = (sizeof keybuf/sizeof (keybuf[0]));
2932
daa37602 2933 if (NILP (continue_echo))
c0a58692
RS
2934 this_command_key_count = 0;
2935
284f4730
JB
2936 i = read_key_sequence (keybuf, (sizeof keybuf/sizeof (keybuf[0])),
2937 NILP (prompt) ? 0 : XSTRING (prompt)->data);
2938
2939 UNGCPRO;
2940 return make_array (i, keybuf);
2941}
2942\f
2943DEFUN ("command-execute", Fcommand_execute, Scommand_execute, 1, 2, 0,
2944 "Execute CMD as an editor command.\n\
2945CMD must be a symbol that satisfies the `commandp' predicate.\n\
2946Optional second arg RECORD-FLAG non-nil\n\
2947means unconditionally put this command in `command-history'.\n\
2948Otherwise, that is done only if an arg is read using the minibuffer.")
2949 (cmd, record)
2950 Lisp_Object cmd, record;
2951{
2952 register Lisp_Object final;
2953 register Lisp_Object tem;
2954 Lisp_Object prefixarg;
2955 struct backtrace backtrace;
2956 extern int debug_on_next_call;
2957
2958 prefixarg = Vprefix_arg, Vprefix_arg = Qnil;
2959 Vcurrent_prefix_arg = prefixarg;
2960 debug_on_next_call = 0;
2961
2962 if (XTYPE (cmd) == Lisp_Symbol)
2963 {
2964 tem = Fget (cmd, Qdisabled);
2965 if (!NILP (tem))
2966 return call1 (Vrun_hooks, Vdisabled_command_hook);
2967 }
2968
2969 while (1)
2970 {
ffd56f97 2971 final = Findirect_function (cmd);
284f4730
JB
2972
2973 if (CONSP (final) && (tem = Fcar (final), EQ (tem, Qautoload)))
2974 do_autoload (final, cmd);
2975 else
2976 break;
2977 }
2978
2979 if (XTYPE (final) == Lisp_String
2980 || XTYPE (final) == Lisp_Vector)
2981 {
2982 /* If requested, place the macro in the command history. For
2983 other sorts of commands, call-interactively takes care of
2984 this. */
2985 if (!NILP (record))
2986 Vcommand_history
2987 = Fcons (Fcons (Qexecute_kbd_macro,
2988 Fcons (final, Fcons (prefixarg, Qnil))),
2989 Vcommand_history);
2990
2991 return Fexecute_kbd_macro (final, prefixarg);
2992 }
2993 if (CONSP (final) || XTYPE (final) == Lisp_Subr
2994 || XTYPE (final) == Lisp_Compiled)
2995 {
2996 backtrace.next = backtrace_list;
2997 backtrace_list = &backtrace;
2998 backtrace.function = &Qcall_interactively;
2999 backtrace.args = &cmd;
3000 backtrace.nargs = 1;
3001 backtrace.evalargs = 0;
3002
3003 tem = Fcall_interactively (cmd, record);
3004
3005 backtrace_list = backtrace.next;
3006 return tem;
3007 }
3008 return Qnil;
3009}
3010\f
284f4730
JB
3011DEFUN ("execute-extended-command", Fexecute_extended_command, Sexecute_extended_command,
3012 1, 1, "P",
3013 "Read function name, then read its arguments and call it.")
3014 (prefixarg)
3015 Lisp_Object prefixarg;
3016{
3017 Lisp_Object function;
3018 char buf[40];
3019 Lisp_Object saved_keys;
3020 struct gcpro gcpro1;
3021
3022 saved_keys = Fthis_command_keys ();
3023 buf[0] = 0;
3024 GCPRO1 (saved_keys);
3025
3026 if (EQ (prefixarg, Qminus))
3027 strcpy (buf, "- ");
3028 else if (CONSP (prefixarg) && XINT (XCONS (prefixarg)->car) == 4)
3029 strcpy (buf, "C-u ");
3030 else if (CONSP (prefixarg) && XTYPE (XCONS (prefixarg)->car) == Lisp_Int)
3031 sprintf (buf, "%d ", XINT (XCONS (prefixarg)->car));
3032 else if (XTYPE (prefixarg) == Lisp_Int)
3033 sprintf (buf, "%d ", XINT (prefixarg));
3034
3035 /* This isn't strictly correct if execute-extended-command
3036 is bound to anything else. Perhaps it should use
3037 this_command_keys? */
3038 strcat (buf, "M-x ");
3039
3040 /* Prompt with buf, and then read a string, completing from and
3041 restricting to the set of all defined commands. Don't provide
3042 any initial input. The last Qnil says not to perform a
3043 peculiar hack on the initial input. */
3044 function = Fcompleting_read (build_string (buf),
3045 Vobarray, Qcommandp,
3046 Qt, Qnil, Qnil);
3047
1113d9db
JB
3048 /* Set this_command_keys to the concatenation of saved_keys and
3049 function, followed by a RET. */
284f4730 3050 {
1113d9db 3051 struct Lisp_String *str;
284f4730
JB
3052 int i;
3053 Lisp_Object tem;
3054
1113d9db
JB
3055 this_command_key_count = 0;
3056
3057 str = XSTRING (saved_keys);
3058 for (i = 0; i < str->size; i++)
284f4730 3059 {
1113d9db 3060 XFASTINT (tem) = str->data[i];
284f4730
JB
3061 add_command_key (tem);
3062 }
1113d9db
JB
3063
3064 str = XSTRING (function);
3065 for (i = 0; i < str->size; i++)
3066 {
3067 XFASTINT (tem) = str->data[i];
3068 add_command_key (tem);
3069 }
3070
3071 XFASTINT (tem) = '\015';
3072 add_command_key (tem);
284f4730
JB
3073 }
3074
3075 UNGCPRO;
3076
3077 function = Fintern (function, Vobarray);
3078 Vprefix_arg = prefixarg;
3079 this_command = function;
3080
3081 return Fcommand_execute (function, Qt);
3082}
3083\f
3084
3085detect_input_pending ()
3086{
3087 if (!input_pending)
3088 get_input_pending (&input_pending);
3089
3090 return input_pending;
3091}
3092
ffd56f97
JB
3093/* This is called in some cases before a possible quit.
3094 It cases the next call to detect_input_pending to recompute input_pending.
3095 So calling this function unnecessarily can't do any harm. */
3096clear_input_pending ()
3097{
3098 input_pending = 0;
3099}
3100
284f4730
JB
3101DEFUN ("input-pending-p", Finput_pending_p, Sinput_pending_p, 0, 0, 0,
3102 "T if command input is currently available with no waiting.\n\
3103Actually, the value is nil only if we can be sure that no input is available.")
3104 ()
3105{
3106 if (!NILP (unread_command_char))
3107 return (Qt);
3108
3109 return detect_input_pending () ? Qt : Qnil;
3110}
3111
3112DEFUN ("recent-keys", Frecent_keys, Srecent_keys, 0, 0, 0,
daa37602 3113 "Return vector of last 100 chars read from terminal.")
284f4730
JB
3114 ()
3115{
3116 Lisp_Object val;
3117
3118 if (total_keys < NUM_RECENT_KEYS)
3119 return Fvector (total_keys, recent_keys);
3120 else
3121 {
3122 val = Fvector (NUM_RECENT_KEYS, recent_keys);
3123 bcopy (recent_keys + recent_keys_index,
3124 XVECTOR (val)->contents,
3125 (NUM_RECENT_KEYS - recent_keys_index) * sizeof (Lisp_Object));
3126 bcopy (recent_keys,
3127 XVECTOR (val)->contents + NUM_RECENT_KEYS - recent_keys_index,
3128 recent_keys_index * sizeof (Lisp_Object));
3129 return val;
3130 }
3131}
3132
3133DEFUN ("this-command-keys", Fthis_command_keys, Sthis_command_keys, 0, 0, 0,
3134 "Return string of the keystrokes that invoked this command.")
3135 ()
3136{
3137 return make_array (this_command_key_count, this_command_keys);
3138}
3139
3140DEFUN ("recursion-depth", Frecursion_depth, Srecursion_depth, 0, 0, 0,
3141 "Return the current depth in recursive edits.")
3142 ()
3143{
3144 Lisp_Object temp;
3145 XFASTINT (temp) = command_loop_level + minibuf_level;
3146 return temp;
3147}
3148
3149DEFUN ("open-dribble-file", Fopen_dribble_file, Sopen_dribble_file, 1, 1,
3150 "FOpen dribble file: ",
3151 "Start writing all keyboard characters to FILE.")
3152 (file)
3153 Lisp_Object file;
3154{
3155 if (NILP (file))
3156 {
3157 fclose (dribble);
3158 dribble = 0;
3159 }
3160 else
3161 {
3162 file = Fexpand_file_name (file, Qnil);
3163 dribble = fopen (XSTRING (file)->data, "w");
3164 }
3165 return Qnil;
3166}
3167
3168DEFUN ("discard-input", Fdiscard_input, Sdiscard_input, 0, 0, 0,
3169 "Discard the contents of the terminal input buffer.\n\
3170Also cancel any kbd macro being defined.")
3171 ()
3172{
3173 defining_kbd_macro = 0;
3174 update_mode_lines++;
3175
284f4730
JB
3176 unread_command_char = Qnil;
3177
3178 discard_tty_input ();
3179
3180 kbd_fetch_ptr = kbd_store_ptr;
3181 input_pending = 0;
3182
3183 return Qnil;
3184}
3185\f
3186DEFUN ("suspend-emacs", Fsuspend_emacs, Ssuspend_emacs, 0, 1, "",
3187 "Stop Emacs and return to superior process. You can resume later.\n\
3188On systems that don't have job control, run a subshell instead.\n\n\
3189If optional arg STUFFSTRING is non-nil, its characters are stuffed\n\
3190to be read as terminal input by Emacs's superior shell.\n\
3191Before suspending, if `suspend-hook' is bound and value is non-nil\n\
3192call the value as a function of no args. Don't suspend if it returns non-nil.\n\
3193Otherwise, suspend normally and after resumption call\n\
3194`suspend-resume-hook' if that is bound and non-nil.\n\
3195\n\
3196Some operating systems cannot stop the Emacs process and resume it later.\n\
3197On such systems, Emacs will start a subshell and wait for it to exit.")
3198 (stuffstring)
3199 Lisp_Object stuffstring;
3200{
3201 register Lisp_Object tem;
3202 int count = specpdl_ptr - specpdl;
3203 int old_height, old_width;
3204 int width, height;
3205 struct gcpro gcpro1;
3206 extern init_sys_modes ();
3207
3208 if (!NILP (stuffstring))
3209 CHECK_STRING (stuffstring, 0);
3210 GCPRO1 (stuffstring);
3211
3212 /* Call value of suspend-hook
3213 if it is bound and value is non-nil. */
3214 if (!NILP (Vrun_hooks))
3215 {
3216 tem = call1 (Vrun_hooks, intern ("suspend-hook"));
3217 if (!EQ (tem, Qnil)) return Qnil;
3218 }
3219
ff11dfa1 3220 get_frame_size (&old_width, &old_height);
284f4730
JB
3221 reset_sys_modes ();
3222 /* sys_suspend can get an error if it tries to fork a subshell
3223 and the system resources aren't available for that. */
3224 record_unwind_protect (init_sys_modes, 0);
3225 stuff_buffered_input (stuffstring);
3226 sys_suspend ();
3227 unbind_to (count, Qnil);
3228
3229 /* Check if terminal/window size has changed.
3230 Note that this is not useful when we are running directly
3231 with a window system; but suspend should be disabled in that case. */
ff11dfa1 3232 get_frame_size (&width, &height);
284f4730 3233 if (width != old_width || height != old_height)
d5045cf9 3234 change_frame_size (0, height, width, 0, 0);
284f4730
JB
3235
3236 /* Call value of suspend-resume-hook
3237 if it is bound and value is non-nil. */
3238 if (!NILP (Vrun_hooks))
3239 call1 (Vrun_hooks, intern ("suspend-resume-hook"));
3240
3241 UNGCPRO;
3242 return Qnil;
3243}
3244
3245/* If STUFFSTRING is a string, stuff its contents as pending terminal input.
3246 Then in any case stuff anthing Emacs has read ahead and not used. */
3247
3248stuff_buffered_input (stuffstring)
3249 Lisp_Object stuffstring;
3250{
3251 register unsigned char *p;
3252
3253/* stuff_char works only in BSD, versions 4.2 and up. */
3254#ifdef BSD
3255#ifndef BSD4_1
3256 if (XTYPE (stuffstring) == Lisp_String)
3257 {
3258 register int count;
3259
3260 p = XSTRING (stuffstring)->data;
3261 count = XSTRING (stuffstring)->size;
3262 while (count-- > 0)
3263 stuff_char (*p++);
3264 stuff_char ('\n');
3265 }
3266 /* Anything we have read ahead, put back for the shell to read. */
3267 while (kbd_fetch_ptr != kbd_store_ptr)
3268 {
3269 if (kbd_fetch_ptr == kbd_buffer + KBD_BUFFER_SIZE)
3270 kbd_fetch_ptr = kbd_buffer;
3271 if (kbd_fetch_ptr->kind == ascii_keystroke)
3272 stuff_char (XINT (kbd_fetch_ptr->code));
3273 kbd_fetch_ptr++;
3274 }
3275 input_pending = 0;
3276#endif
3277#endif /* BSD and not BSD4_1 */
3278}
3279\f
ffd56f97
JB
3280set_waiting_for_input (time_to_clear)
3281 EMACS_TIME *time_to_clear;
284f4730 3282{
ffd56f97 3283 input_available_clear_time = time_to_clear;
284f4730
JB
3284
3285 /* Tell interrupt_signal to throw back to read_char, */
3286 waiting_for_input = 1;
3287
3288 /* If interrupt_signal was called before and buffered a C-g,
3289 make it run again now, to avoid timing error. */
3290 if (!NILP (Vquit_flag))
3291 quit_throw_to_read_char ();
3292
3293 /* If alarm has gone off already, echo now. */
3294 if (echo_flag)
3295 {
3296 echo ();
3297 echo_flag = 0;
3298 }
3299}
3300
3301clear_waiting_for_input ()
3302{
3303 /* Tell interrupt_signal not to throw back to read_char, */
3304 waiting_for_input = 0;
ffd56f97 3305 input_available_clear_time = 0;
284f4730
JB
3306}
3307
3308/* This routine is called at interrupt level in response to C-G.
3309 If interrupt_input, this is the handler for SIGINT.
3310 Otherwise, it is called from kbd_buffer_store_event,
3311 in handling SIGIO or SIGTINT.
3312
3313 If `waiting_for_input' is non zero, then unless `echoing' is nonzero,
3314 immediately throw back to read_char.
3315
3316 Otherwise it sets the Lisp variable quit-flag not-nil.
3317 This causes eval to throw, when it gets a chance.
3318 If quit-flag is already non-nil, it stops the job right away. */
3319
3320SIGTYPE
3321interrupt_signal ()
3322{
3323 char c;
3324 /* Must preserve main program's value of errno. */
3325 int old_errno = errno;
3326 extern Lisp_Object Vwindow_system;
3327
3328#ifdef USG
3329 /* USG systems forget handlers when they are used;
3330 must reestablish each time */
3331 signal (SIGINT, interrupt_signal);
3332 signal (SIGQUIT, interrupt_signal);
3333#endif /* USG */
3334
3335 cancel_echoing ();
3336
d5045cf9 3337 if (!NILP (Vquit_flag) && FRAME_TERMCAP_P (selected_frame))
284f4730
JB
3338 {
3339 fflush (stdout);
3340 reset_sys_modes ();
3341 sigfree ();
3342#ifdef SIGTSTP /* Support possible in later USG versions */
3343/*
3344 * On systems which can suspend the current process and return to the original
3345 * shell, this command causes the user to end up back at the shell.
3346 * The "Auto-save" and "Abort" questions are not asked until
3347 * the user elects to return to emacs, at which point he can save the current
3348 * job and either dump core or continue.
3349 */
3350 sys_suspend ();
3351#else
3352#ifdef VMS
3353 if (sys_suspend () == -1)
3354 {
3355 printf ("Not running as a subprocess;\n");
3356 printf ("you can continue or abort.\n");
3357 }
3358#else /* not VMS */
3359 /* Perhaps should really fork an inferior shell?
3360 But that would not provide any way to get back
3361 to the original shell, ever. */
3362 printf ("No support for stopping a process on this operating system;\n");
3363 printf ("you can continue or abort.\n");
3364#endif /* not VMS */
3365#endif /* not SIGTSTP */
3366 printf ("Auto-save? (y or n) ");
3367 fflush (stdout);
3368 if (((c = getchar ()) & ~040) == 'Y')
3369 Fdo_auto_save (Qnil, Qnil);
3370 while (c != '\n') c = getchar ();
3371#ifdef VMS
3372 printf ("Abort (and enter debugger)? (y or n) ");
3373#else /* not VMS */
3374 printf ("Abort (and dump core)? (y or n) ");
3375#endif /* not VMS */
3376 fflush (stdout);
3377 if (((c = getchar ()) & ~040) == 'Y')
3378 abort ();
3379 while (c != '\n') c = getchar ();
3380 printf ("Continuing...\n");
3381 fflush (stdout);
3382 init_sys_modes ();
3383 }
3384 else
3385 {
3386 /* If executing a function that wants to be interrupted out of
3387 and the user has not deferred quitting by binding `inhibit-quit'
3388 then quit right away. */
3389 if (immediate_quit && NILP (Vinhibit_quit))
3390 {
3391 immediate_quit = 0;
3392 sigfree ();
3393 Fsignal (Qquit, Qnil);
3394 }
3395 else
3396 /* Else request quit when it's safe */
3397 Vquit_flag = Qt;
3398 }
3399
3400 if (waiting_for_input && !echoing)
3401 quit_throw_to_read_char ();
3402
3403 errno = old_errno;
3404}
3405
3406/* Handle a C-g by making read_char return C-g. */
3407
3408quit_throw_to_read_char ()
3409{
3410 quit_error_check ();
3411 sigfree ();
3412 /* Prevent another signal from doing this before we finish. */
f76475ad 3413 clear_waiting_for_input ();
284f4730
JB
3414 input_pending = 0;
3415
284f4730
JB
3416 unread_command_char = Qnil;
3417
3418 _longjmp (getcjmp, 1);
3419}
3420\f
3421DEFUN ("set-input-mode", Fset_input_mode, Sset_input_mode, 3, 4, 0,
3422 "Set mode of reading keyboard input.\n\
464f8898
RS
3423First arg INTERRUPT non-nil means use input interrupts;\n\
3424 nil means use CBREAK mode.\n\
3425Second arg FLOW non-nil means use ^S/^Q flow control for output to terminal\n\
284f4730 3426 (no effect except in CBREAK mode).\n\
464f8898 3427Third arg META non-nil means accept 8-bit input (for a Meta key).\n\
284f4730 3428 Otherwise, the top bit is ignored, on the assumption it is parity.\n\
464f8898 3429Optional fourth arg QUIT if non-nil specifies character to use for quitting.")
284f4730
JB
3430 (interrupt, flow, meta, quit)
3431 Lisp_Object interrupt, flow, meta, quit;
3432{
3433 if (!NILP (quit)
3434 && (XTYPE (quit) != Lisp_Int
3435 || XINT (quit) < 0 || XINT (quit) > 0400))
3436 error ("set-input-mode: QUIT must be an ASCII character.");
3437
3438 reset_sys_modes ();
3439#ifdef SIGIO
3440/* Note SIGIO has been undef'd if FIONREAD is missing. */
3441#ifdef NO_SOCK_SIGIO
3442 if (read_socket_hook)
3443 interrupt_input = 0; /* No interrupts if reading from a socket. */
3444 else
3445#endif /* NO_SOCK_SIGIO */
3446 interrupt_input = !NILP (interrupt);
3447#else /* not SIGIO */
3448 interrupt_input = 0;
3449#endif /* not SIGIO */
3450/* Our VMS input only works by interrupts, as of now. */
3451#ifdef VMS
3452 interrupt_input = 1;
3453#endif
3454 flow_control = !NILP (flow);
3455 meta_key = !NILP (meta);
3456 if (!NILP (quit))
3457 /* Don't let this value be out of range. */
3458 quit_char = XINT (quit) & (meta_key ? 0377 : 0177);
3459
3460 init_sys_modes ();
3461 return Qnil;
3462}
3463\f
3464init_keyboard ()
3465{
3466 this_command_keys_size = 40;
3467 this_command_keys =
3468 (Lisp_Object *) xmalloc (this_command_keys_size * sizeof (Lisp_Object));
3469
3470 /* This is correct before outermost invocation of the editor loop */
3471 command_loop_level = -1;
3472 immediate_quit = 0;
3473 quit_char = Ctl ('g');
3474 unread_command_char = Qnil;
3475 recent_keys_index = 0;
3476 total_keys = 0;
3477 kbd_fetch_ptr = kbd_buffer;
3478 kbd_store_ptr = kbd_buffer;
3479 do_mouse_tracking = 0;
3480 input_pending = 0;
3481
3482 if (!noninteractive)
3483 {
3484 signal (SIGINT, interrupt_signal);
3485#ifdef HAVE_TERMIO
3486 /* For systems with SysV TERMIO, C-g is set up for both SIGINT and
3487 SIGQUIT and we can't tell which one it will give us. */
3488 signal (SIGQUIT, interrupt_signal);
3489#endif /* HAVE_TERMIO */
3490/* Note SIGIO has been undef'd if FIONREAD is missing. */
3491#ifdef SIGIO
3492 signal (SIGIO, input_available_signal);
8ea0a720 3493#endif /* SIGIO */
284f4730
JB
3494 }
3495
3496/* Use interrupt input by default, if it works and noninterrupt input
3497 has deficiencies. */
3498
3499#ifdef INTERRUPT_INPUT
3500 interrupt_input = 1;
3501#else
3502 interrupt_input = 0;
3503#endif
3504
3505/* Our VMS input only works by interrupts, as of now. */
3506#ifdef VMS
3507 interrupt_input = 1;
3508#endif
3509
3510 sigfree ();
3511 dribble = 0;
3512
3513 if (keyboard_init_hook)
3514 (*keyboard_init_hook) ();
3515
3516#ifdef POLL_FOR_INPUT
3517 poll_suppress_count = 1;
3518 start_polling ();
3519#endif
3520}
3521
3522/* This type's only use is in syms_of_keyboard, to initialize the
3523 event header symbols and put properties on them. */
3524struct event_head {
3525 Lisp_Object *var;
3526 char *name;
3527 Lisp_Object *kind;
3528};
3529
3530struct event_head head_table[] = {
3531 &Qmouse_movement, "mouse-movement", &Qmouse_movement,
3532 &Qvscrollbar_part, "vscrollbar-part", &Qscrollbar_click,
3533 &Qvslider_part, "vslider-part", &Qscrollbar_click,
3534 &Qvthumbup_part, "vthumbup-part", &Qscrollbar_click,
3535 &Qvthumbdown_part, "vthumbdown-part", &Qscrollbar_click,
3536 &Qhscrollbar_part, "hscrollbar-part", &Qscrollbar_click,
3537 &Qhslider_part, "hslider-part", &Qscrollbar_click,
3538 &Qhthumbleft_part, "hthumbleft-part", &Qscrollbar_click,
3539 &Qhthumbright_part,"hthumbright-part", &Qscrollbar_click
3540};
3541
3542syms_of_keyboard ()
3543{
3544 Qself_insert_command = intern ("self-insert-command");
3545 staticpro (&Qself_insert_command);
3546
3547 Qforward_char = intern ("forward-char");
3548 staticpro (&Qforward_char);
3549
3550 Qbackward_char = intern ("backward-char");
3551 staticpro (&Qbackward_char);
3552
3553 Qdisabled = intern ("disabled");
3554 staticpro (&Qdisabled);
3555
3556 Qfunction_key = intern ("function-key");
3557 staticpro (&Qfunction_key);
3558 Qmouse_movement = intern ("mouse-click");
3559 staticpro (&Qmouse_click);
3560 Qmouse_movement = intern ("scrollbar-click");
3561 staticpro (&Qmouse_movement);
3562
3563 Qmode_line = intern ("mode-line");
3564 staticpro (&Qmode_line);
e5d77022
JB
3565 Qvertical_line = intern ("vertical-line");
3566 staticpro (&Qvertical_line);
284f4730
JB
3567
3568 Qevent_kind = intern ("event-type");
3569 staticpro (&Qevent_kind);
3570 Qevent_unmodified = intern ("event-unmodified");
3571 staticpro (&Qevent_unmodified);
3572
3573 {
3574 struct event_head *p;
3575
3576 for (p = head_table;
3577 p < head_table + (sizeof (head_table) / sizeof (head_table[0]));
3578 p++)
3579 {
3580 *p->var = intern (p->name);
3581 staticpro (p->var);
3582 Fput (*p->var, Qevent_kind, *p->kind);
3583 Fput (*p->var, Qevent_unmodified, *p->var);
3584 }
3585 }
3586
3587 func_key_syms = Qnil;
3588 staticpro (&func_key_syms);
3589
3590 mouse_syms = Qnil;
3591 staticpro (&mouse_syms);
3592
3593 defsubr (&Sread_key_sequence);
3594 defsubr (&Srecursive_edit);
3595 defsubr (&Strack_mouse);
3596 defsubr (&Smouse_click_p);
3597 defsubr (&Sinput_pending_p);
3598 defsubr (&Scommand_execute);
3599 defsubr (&Srecent_keys);
3600 defsubr (&Sthis_command_keys);
3601 defsubr (&Ssuspend_emacs);
3602 defsubr (&Sabort_recursive_edit);
3603 defsubr (&Sexit_recursive_edit);
3604 defsubr (&Srecursion_depth);
3605 defsubr (&Stop_level);
3606 defsubr (&Sdiscard_input);
3607 defsubr (&Sopen_dribble_file);
3608 defsubr (&Sset_input_mode);
3609 defsubr (&Sexecute_extended_command);
3610
3611 DEFVAR_LISP ("disabled-command-hook", &Vdisabled_command_hook,
3612 "Value is called instead of any command that is disabled\n\
7d6de002 3613\(has a non-nil `disabled' property).");
284f4730
JB
3614
3615 DEFVAR_LISP ("last-command-char", &last_command_char,
3616 "Last terminal input key that was part of a command.");
3617
7d6de002
RS
3618 DEFVAR_LISP ("last-nonmenu-event", &last_nonmenu_event,
3619 "Last terminal input key in a command, except for mouse menus.\n\
3620Mouse menus give back keys that don't look like mouse events;\n\
3621this variable holds the actual mouse event that led to the menu,\n\
3622so that you can determine whether the command was run by mouse or not.");
3623
284f4730
JB
3624 DEFVAR_LISP ("last-input-char", &last_input_char,
3625 "Last terminal input key.");
3626
3627 DEFVAR_LISP ("unread-command-char", &unread_command_char,
3628 "Object to be read as next input from input stream, or nil if none.");
3629
3630 DEFVAR_LISP ("meta-prefix-char", &meta_prefix_char,
3631 "Meta-prefix character code. Meta-foo as command input\n\
3632turns into this character followed by foo.");
3633 XSET (meta_prefix_char, Lisp_Int, 033);
3634
3635 DEFVAR_LISP ("last-command", &last_command,
3636 "The last command executed. Normally a symbol with a function definition,\n\
3637but can be whatever was found in the keymap, or whatever the variable\n\
3638`this-command' was set to by that command.");
3639 last_command = Qnil;
3640
3641 DEFVAR_LISP ("this-command", &this_command,
3642 "The command now being executed.\n\
3643The command can set this variable; whatever is put here\n\
3644will be in `last-command' during the following command.");
3645 this_command = Qnil;
3646
3647 DEFVAR_INT ("auto-save-interval", &auto_save_interval,
3648 "*Number of keyboard input characters between auto-saves.\n\
3649Zero means disable autosaving due to number of characters typed.");
3650 auto_save_interval = 300;
3651
3652 DEFVAR_LISP ("auto-save-timeout", &Vauto_save_timeout,
3653 "*Number of seconds idle time before auto-save.\n\
06ef7355
RS
3654Zero or nil means disable auto-saving due to idleness.\n\
3655After auto-saving due to this many seconds of idle time,\n\
84447c71 3656Emacs also does a garbage collection if that seems to be warranted.");
284f4730
JB
3657 XFASTINT (Vauto_save_timeout) = 30;
3658
3659 DEFVAR_INT ("echo-keystrokes", &echo_keystrokes,
3660 "*Nonzero means echo unfinished commands after this many seconds of pause.");
3661 echo_keystrokes = 1;
3662
3663 DEFVAR_INT ("polling-period", &polling_period,
3664 "*Interval between polling for input during Lisp execution.\n\
3665The reason for polling is to make C-g work to stop a running program.\n\
3666Polling is needed only when using X windows and SIGIO does not work.\n\
3667Polling is automatically disabled in all other cases.");
3668 polling_period = 2;
3669
3670 DEFVAR_INT ("num-input-keys", &num_input_keys,
3671 "*Number of complete keys read from the keyboard so far.");
3672 num_input_keys = 0;
3673
3e51c7b7 3674#ifdef MULTI_FRAME
ff11dfa1 3675 DEFVAR_LISP ("last-event-frame", &Vlast_event_frame,
fce33686
JB
3676 "*The frame in which the most recently read event occurred.\n\
3677If the last event came from a keyboard macro, this is set to `macro'.");
ff11dfa1 3678 Vlast_event_frame = Qnil;
3e51c7b7 3679#endif
284f4730
JB
3680
3681 DEFVAR_LISP ("help-char", &help_char,
3682 "Character to recognize as meaning Help.\n\
3683When it is read, do `(eval help-form)', and display result if it's a string.\n\
3684If the value of `help-form' is nil, this char can be read normally.");
3685 XSET (help_char, Lisp_Int, Ctl ('H'));
3686
3687 DEFVAR_LISP ("help-form", &Vhelp_form,
3688 "Form to execute when character help-char is read.\n\
3689If the form returns a string, that string is displayed.\n\
3690If `help-form' is nil, the help char is not recognized.");
3691 Vhelp_form = Qnil;
3692
3693 DEFVAR_LISP ("top-level", &Vtop_level,
3694 "Form to evaluate when Emacs starts up.\n\
3695Useful to set before you dump a modified Emacs.");
3696 Vtop_level = Qnil;
3697
3698 DEFVAR_LISP ("keyboard-translate-table", &Vkeyboard_translate_table,
3699 "String used as translate table for keyboard input, or nil.\n\
3700Each character is looked up in this string and the contents used instead.\n\
3701If string is of length N, character codes N and up are untranslated.");
3702 Vkeyboard_translate_table = Qnil;
3703
284f4730 3704 DEFVAR_BOOL ("menu-prompting", &menu_prompting,
7d6de002 3705 "Non-nil means prompt with menus when appropriate.\n\
284f4730 3706This is done when reading from a keymap that has a prompt string,\n\
7d6de002
RS
3707for elements that have prompt strings.\n\
3708The menu is displayed on the screen\n\
3709if X menus were enabled at configuration\n\
3710time and the previous event was a mouse click prefix key.\n\
3711Otherwise, menu prompting uses the echo area.");
284f4730
JB
3712 menu_prompting = 1;
3713
3714 DEFVAR_LISP ("menu-prompt-more-char", &menu_prompt_more_char,
3715 "Character to see next line of menu prompt.\n\
3716Type this character while in a menu prompt to rotate around the lines of it.");
3717 XSET (menu_prompt_more_char, Lisp_Int, ' ');
3718}
3719
3720keys_of_keyboard ()
3721{
3722 initial_define_key (global_map, Ctl ('Z'), "suspend-emacs");
3723 initial_define_key (control_x_map, Ctl ('Z'), "suspend-emacs");
3724 initial_define_key (meta_map, Ctl ('C'), "exit-recursive-edit");
3725 initial_define_key (global_map, Ctl (']'), "abort-recursive-edit");
3726 initial_define_key (meta_map, 'x', "execute-extended-command");
3727}