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