(shrink-window-if-larger-than-buffer): Moved from electric.el to windows.el,
[emacs.git] / src / keyboard.c
blobd72125cc98ef64b0880790cded9c872111b25b22
1 /* Keyboard and mouse input; editor command loop.
2 Copyright (C) 1985, 1986, 1987, 1988, 1989, 1993 Free Software Foundation, Inc.
4 This file is part of GNU Emacs.
6 GNU Emacs is free software; you can redistribute it and/or modify
7 it under the terms of the GNU General Public License as published by
8 the Free Software Foundation; either version 2, or (at your option)
9 any later version.
11 GNU Emacs is distributed in the hope that it will be useful,
12 but WITHOUT ANY WARRANTY; without even the implied warranty of
13 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14 GNU General Public License for more details.
16 You should have received a copy of the GNU General Public License
17 along with GNU Emacs; see the file COPYING. If not, write to
18 the Free Software Foundation, 675 Mass Ave, Cambridge, MA 02139, USA. */
20 /* Allow config.h to undefine symbols found here. */
21 #include <signal.h>
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"
31 #include "frame.h"
32 #include "window.h"
33 #include "commands.h"
34 #include "buffer.h"
35 #include "disptab.h"
36 #include "dispextern.h"
37 #include "keyboard.h"
38 #include "intervals.h"
39 #include "blockinput.h"
40 #include <setjmp.h>
41 #include <errno.h>
43 #ifndef VMS
44 #include <sys/ioctl.h>
45 #endif
47 #include "syssignal.h"
48 #include "systty.h"
49 #include "systime.h"
51 extern int errno;
53 /* Variables for blockinput.h: */
55 /* Non-zero if interrupt input is blocked right now. */
56 int interrupt_input_blocked;
58 /* Nonzero means an input interrupt has arrived
59 during the current critical section. */
60 int interrupt_input_pending;
63 #ifdef HAVE_X_WINDOWS
64 extern Lisp_Object Vmouse_grabbed;
66 /* Make all keyboard buffers much bigger when using X windows. */
67 #define KBD_BUFFER_SIZE 4096
68 #else /* No X-windows, character input */
69 #define KBD_BUFFER_SIZE 256
70 #endif /* No X-windows */
72 /* Following definition copied from eval.c */
74 struct backtrace
76 struct backtrace *next;
77 Lisp_Object *function;
78 Lisp_Object *args; /* Points to vector of args. */
79 int nargs; /* length of vector. If nargs is UNEVALLED,
80 args points to slot holding list of
81 unevalled args */
82 char evalargs;
85 /* Non-nil disable property on a command means
86 do not execute it; call disabled-command-hook's value instead. */
87 Lisp_Object Qdisabled, Vdisabled_command_hook;
89 #define NUM_RECENT_KEYS (100)
90 int recent_keys_index; /* Index for storing next element into recent_keys */
91 int total_keys; /* Total number of elements stored into recent_keys */
92 Lisp_Object recent_keys; /* A vector, holding the last 100 keystrokes */
94 /* Vector holding the key sequence that invoked the current command.
95 It is reused for each command, and it may be longer than the current
96 sequence; this_command_key_count indicates how many elements
97 actually mean something.
98 It's easier to staticpro a single Lisp_Object than an array. */
99 Lisp_Object this_command_keys;
100 int this_command_key_count;
102 extern int minbuf_level;
104 extern struct backtrace *backtrace_list;
106 /* Nonzero means do menu prompting. */
107 static int menu_prompting;
109 /* Character to see next line of menu prompt. */
110 static Lisp_Object menu_prompt_more_char;
112 /* For longjmp to where kbd input is being done. */
113 static jmp_buf getcjmp;
115 /* True while doing kbd input. */
116 int waiting_for_input;
118 /* True while displaying for echoing. Delays C-g throwing. */
119 static int echoing;
121 /* Nonzero means C-G should cause immediate error-signal. */
122 int immediate_quit;
124 /* Character to recognize as the help char. */
125 Lisp_Object help_char;
127 /* Form to execute when help char is typed. */
128 Lisp_Object Vhelp_form;
130 /* Character that causes a quit. Normally C-g.
132 If we are running on an ordinary terminal, this must be an ordinary
133 ASCII char, since we want to make it our interrupt character.
135 If we are not running on an ordinary terminal, it still needs to be
136 an ordinary ASCII char. This character needs to be recognized in
137 the input interrupt handler. At this point, the keystroke is
138 represented as a struct input_event, while the desired quit
139 character is specified as a lispy event. The mapping from struct
140 input_events to lispy events cannot run in an interrupt handler,
141 and the reverse mapping is difficult for anything but ASCII
142 keystrokes.
144 FOR THESE ELABORATE AND UNSATISFYING REASONS, quit_char must be an
145 ASCII character. */
146 int quit_char;
148 extern Lisp_Object current_global_map;
149 extern int minibuf_level;
151 /* Current depth in recursive edits. */
152 int command_loop_level;
154 /* Total number of times command_loop has read a key sequence. */
155 int num_input_keys;
157 /* Last input character read as a command. */
158 Lisp_Object last_command_char;
160 /* Last input character read as a command, not counting menus
161 reached by the mouse. */
162 Lisp_Object last_nonmenu_event;
164 /* Last input character read for any purpose. */
165 Lisp_Object last_input_char;
167 /* If not Qnil, a list of objects to be read as subsequent command input. */
168 Lisp_Object unread_command_events;
170 /* If not -1, an event to be read as subsequent command input. */
171 int unread_command_char;
173 /* If not Qnil, this is a switch-frame event which we decided to put
174 off until the end of a key sequence. This should be read as the
175 next command input, after any unread_command_events.
177 read_key_sequence uses this to delay switch-frame events until the
178 end of the key sequence; Fread_char uses it to put off switch-frame
179 events until a non-ASCII event is acceptable as input. */
180 Lisp_Object unread_switch_frame;
182 /* A mask of extra modifier bits to put into every keyboard char. */
183 int extra_keyboard_modifiers;
185 /* Char to use as prefix when a meta character is typed in.
186 This is bound on entry to minibuffer in case ESC is changed there. */
188 Lisp_Object meta_prefix_char;
190 /* Last size recorded for a current buffer which is not a minibuffer. */
191 static int last_non_minibuf_size;
193 /* Number of idle seconds before an auto-save and garbage collection. */
194 static Lisp_Object Vauto_save_timeout;
196 /* Total number of times read_char has returned. */
197 int num_input_chars;
199 /* Total number of times read_char has returned, outside of macros. */
200 int num_nonmacro_input_chars;
202 /* Auto-save automatically when this many characters have been typed
203 since the last time. */
205 static int auto_save_interval;
207 /* Value of num_nonmacro_input_chars as of last auto save. */
209 int last_auto_save;
211 /* Last command executed by the editor command loop, not counting
212 commands that set the prefix argument. */
214 Lisp_Object last_command;
216 /* The command being executed by the command loop.
217 Commands may set this, and the value set will be copied into last_command
218 instead of the actual command. */
219 Lisp_Object this_command;
221 #ifdef MULTI_FRAME
222 /* The frame in which the last input event occurred, or Qmacro if the
223 last event came from a macro. We use this to determine when to
224 generate switch-frame events. This may be cleared by functions
225 like Fselect_frame, to make sure that a switch-frame event is
226 generated by the next character. */
227 Lisp_Object internal_last_event_frame;
229 /* A user-visible version of the above, intended to allow users to
230 figure out where the last event came from, if the event doesn't
231 carry that information itself (i.e. if it was a character). */
232 Lisp_Object Vlast_event_frame;
233 #endif
235 /* The timestamp of the last input event we received from the X server.
236 X Windows wants this for selection ownership. */
237 unsigned long last_event_timestamp;
239 Lisp_Object Qself_insert_command;
240 Lisp_Object Qforward_char;
241 Lisp_Object Qbackward_char;
243 /* read_key_sequence stores here the command definition of the
244 key sequence that it reads. */
245 Lisp_Object read_key_sequence_cmd;
247 /* Form to evaluate (if non-nil) when Emacs is started. */
248 Lisp_Object Vtop_level;
250 /* User-supplied string to translate input characters through. */
251 Lisp_Object Vkeyboard_translate_table;
253 /* Keymap mapping ASCII function key sequences onto their preferred forms. */
254 extern Lisp_Object Vfunction_key_map;
256 /* Non-nil means deactivate the mark at end of this command. */
257 Lisp_Object Vdeactivate_mark;
259 /* Menu bar specified in Lucid Emacs fashion. */
261 Lisp_Object Vlucid_menu_bar_dirty_flag;
262 Lisp_Object Qrecompute_lucid_menubar, Qactivate_menubar_hook;
264 /* Hooks to run before and after each command. */
265 Lisp_Object Qpre_command_hook, Qpost_command_hook;
266 Lisp_Object Vpre_command_hook, Vpost_command_hook;
268 /* File in which we write all commands we read. */
269 FILE *dribble;
271 /* Nonzero if input is available. */
272 int input_pending;
274 /* Nonzero if should obey 0200 bit in input chars as "Meta". */
275 int meta_key;
277 extern char *pending_malloc_warning;
279 /* Circular buffer for pre-read keyboard input. */
280 static struct input_event kbd_buffer[KBD_BUFFER_SIZE];
282 /* Vector to GCPRO the frames and windows mentioned in kbd_buffer.
284 The interrupt-level event handlers will never enqueue an event on a
285 frame which is not in Vframe_list, and once an event is dequeued,
286 internal_last_event_frame or the event itself points to the frame.
287 So that's all fine.
289 But while the event is sitting in the queue, it's completely
290 unprotected. Suppose the user types one command which will run for
291 a while and then delete a frame, and then types another event at
292 the frame that will be deleted, before the command gets around to
293 it. Suppose there are no references to this frame elsewhere in
294 Emacs, and a GC occurs before the second event is dequeued. Now we
295 have an event referring to a freed frame, which will crash Emacs
296 when it is dequeued.
298 Similar things happen when an event on a scroll bar is enqueued; the
299 window may be deleted while the event is in the queue.
301 So, we use this vector to protect the frame_or_window field in the
302 event queue. That way, they'll be dequeued as dead frames or
303 windows, but still valid lisp objects.
305 If kbd_buffer[i].kind != no_event, then
306 (XVECTOR (kbd_buffer_frame_or_window)->contents[i]
307 == kbd_buffer[i].frame_or_window. */
308 static Lisp_Object kbd_buffer_frame_or_window;
310 /* Pointer to next available character in kbd_buffer.
311 If kbd_fetch_ptr == kbd_store_ptr, the buffer is empty.
312 This may be kbd_buffer + KBD_BUFFER_SIZE, meaning that the the
313 next available char is in kbd_buffer[0]. */
314 static struct input_event *kbd_fetch_ptr;
316 /* Pointer to next place to store character in kbd_buffer. This
317 may be kbd_buffer + KBD_BUFFER_SIZE, meaning that the next
318 character should go in kbd_buffer[0]. */
319 #ifdef __STDC__
320 volatile
321 #endif
322 static struct input_event *kbd_store_ptr;
324 /* The above pair of variables forms a "queue empty" flag. When we
325 enqueue a non-hook event, we increment kbd_write_count. When we
326 dequeue a non-hook event, we increment kbd_read_count. We say that
327 there is input available iff the two counters are not equal.
329 Why not just have a flag set and cleared by the enqueuing and
330 dequeuing functions? Such a flag could be screwed up by interrupts
331 at inopportune times. */
333 /* If this flag is non-zero, we will check mouse_moved to see when the
334 mouse moves, and motion events will appear in the input stream. If
335 it is zero, mouse motion will be ignored. */
336 int do_mouse_tracking;
338 /* The window system handling code should set this if the mouse has
339 moved since the last call to the mouse_position_hook. Calling that
340 hook should clear this. Code assumes that if this is set, it can
341 call mouse_position_hook to get the promised position, so don't set
342 it unless you're prepared to substantiate the claim! */
343 int mouse_moved;
345 /* True iff there is an event in kbd_buffer, or if mouse tracking is
346 enabled and there is a new mouse position in the mouse movement
347 buffer. Note that if this is false, that doesn't mean that there
348 is readable input; all the events in the queue might be button-up
349 events, and do_mouse_tracking might be off. */
350 #define EVENT_QUEUES_EMPTY \
351 ((kbd_fetch_ptr == kbd_store_ptr) && (!do_mouse_tracking || !mouse_moved))
354 /* Symbols to head events. */
355 Lisp_Object Qmouse_movement;
356 Lisp_Object Qscroll_bar_movement;
357 Lisp_Object Qswitch_frame;
359 /* Symbols to denote kinds of events. */
360 Lisp_Object Qfunction_key;
361 Lisp_Object Qmouse_click;
362 /* Lisp_Object Qmouse_movement; - also an event header */
364 /* Properties of event headers. */
365 Lisp_Object Qevent_kind;
366 Lisp_Object Qevent_symbol_elements;
368 Lisp_Object Qmenu_enable;
370 /* An event header symbol HEAD may have a property named
371 Qevent_symbol_element_mask, which is of the form (BASE MODIFIERS);
372 BASE is the base, unmodified version of HEAD, and MODIFIERS is the
373 mask of modifiers applied to it. If present, this is used to help
374 speed up parse_modifiers. */
375 Lisp_Object Qevent_symbol_element_mask;
377 /* An unmodified event header BASE may have a property named
378 Qmodifier_cache, which is an alist mapping modifier masks onto
379 modified versions of BASE. If present, this helps speed up
380 apply_modifiers. */
381 Lisp_Object Qmodifier_cache;
383 /* Symbols to use for parts of windows. */
384 Lisp_Object Qmode_line;
385 Lisp_Object Qvertical_line;
386 Lisp_Object Qvertical_scroll_bar;
387 Lisp_Object Qmenu_bar;
389 extern Lisp_Object Qmenu_enable;
391 Lisp_Object recursive_edit_unwind (), command_loop ();
392 Lisp_Object Fthis_command_keys ();
394 /* Address (if not 0) of EMACS_TIME to zero out if a SIGIO interrupt
395 happens. */
396 EMACS_TIME *input_available_clear_time;
398 /* Nonzero means use SIGIO interrupts; zero means use CBREAK mode.
399 Default is 1 if INTERRUPT_INPUT is defined. */
400 int interrupt_input;
402 /* Nonzero while interrupts are temporarily deferred during redisplay. */
403 int interrupts_deferred;
405 /* nonzero means use ^S/^Q for flow control. */
406 int flow_control;
408 /* Allow m- file to inhibit use of FIONREAD. */
409 #ifdef BROKEN_FIONREAD
410 #undef FIONREAD
411 #endif
413 /* We are unable to use interrupts if FIONREAD is not available,
414 so flush SIGIO so we won't try. */
415 #ifndef FIONREAD
416 #ifdef SIGIO
417 #undef SIGIO
418 #endif
419 #endif
421 /* If we support X Windows, and won't get an interrupt when input
422 arrives from the server, poll periodically so we can detect C-g. */
423 #ifdef HAVE_X_WINDOWS
424 #ifndef SIGIO
425 #define POLL_FOR_INPUT
426 #endif
427 #endif
429 /* Global variable declarations. */
431 /* Function for init_keyboard to call with no args (if nonzero). */
432 void (*keyboard_init_hook) ();
434 static int read_avail_input ();
435 static void get_input_pending ();
437 /* > 0 if we are to echo keystrokes. */
438 static int echo_keystrokes;
440 /* Nonzero means echo each character as typed. */
441 static int immediate_echo;
443 /* The text we're echoing in the modeline - partial key sequences,
444 usually. '\0'-terminated. This really shouldn't have a fixed size. */
445 static char echobuf[300];
447 /* Where to append more text to echobuf if we want to. */
448 static char *echoptr;
450 #define min(a,b) ((a)<(b)?(a):(b))
451 #define max(a,b) ((a)>(b)?(a):(b))
453 /* Install the string STR as the beginning of the string of echoing,
454 so that it serves as a prompt for the next character.
455 Also start echoing. */
457 echo_prompt (str)
458 char *str;
460 int len = strlen (str);
461 if (len > sizeof echobuf - 4)
462 len = sizeof echobuf - 4;
463 bcopy (str, echobuf, len);
464 echoptr = echobuf + len;
465 *echoptr = '\0';
467 echo ();
470 /* Add C to the echo string, if echoing is going on.
471 C can be a character, which is printed prettily ("M-C-x" and all that
472 jazz), or a symbol, whose name is printed. */
474 echo_char (c)
475 Lisp_Object c;
477 extern char *push_key_description ();
479 if (immediate_echo)
481 char *ptr = echoptr;
483 if (ptr != echobuf)
484 *ptr++ = ' ';
486 /* If someone has passed us a composite event, use its head symbol. */
487 c = EVENT_HEAD (c);
489 if (XTYPE (c) == Lisp_Int)
491 if (ptr - echobuf > sizeof echobuf - 6)
492 return;
494 ptr = push_key_description (XINT (c), ptr);
496 else if (XTYPE (c) == Lisp_Symbol)
498 struct Lisp_String *name = XSYMBOL (c)->name;
499 if (((ptr - echobuf) + name->size + 4) > sizeof echobuf)
500 return;
501 bcopy (name->data, ptr, name->size);
502 ptr += name->size;
505 if (echoptr == echobuf && EQ (c, help_char))
507 strcpy (ptr, " (Type ? for further options)");
508 ptr += strlen (ptr);
511 *ptr = 0;
512 echoptr = ptr;
514 echo ();
518 /* Temporarily add a dash to the end of the echo string if it's not
519 empty, so that it serves as a mini-prompt for the very next character. */
521 echo_dash ()
523 if (!immediate_echo && echoptr == echobuf)
524 return;
525 /* Do nothing if not echoing at all. */
526 if (echoptr == 0)
527 return;
529 /* Put a dash at the end of the buffer temporarily,
530 but make it go away when the next character is added. */
531 echoptr[0] = '-';
532 echoptr[1] = 0;
534 echo ();
537 /* Display the current echo string, and begin echoing if not already
538 doing so. */
540 echo ()
542 if (!immediate_echo)
544 int i;
545 immediate_echo = 1;
547 for (i = 0; i < this_command_key_count; i++)
548 echo_char (XVECTOR (this_command_keys)->contents[i]);
549 echo_dash ();
552 echoing = 1;
553 message1 (echobuf);
554 echoing = 0;
556 if (waiting_for_input && !NILP (Vquit_flag))
557 quit_throw_to_read_char ();
560 /* Turn off echoing, for the start of a new command. */
562 cancel_echoing ()
564 immediate_echo = 0;
565 echoptr = echobuf;
568 /* Return the length of the current echo string. */
570 static int
571 echo_length ()
573 return echoptr - echobuf;
576 /* Truncate the current echo message to its first LEN chars.
577 This and echo_char get used by read_key_sequence when the user
578 switches frames while entering a key sequence. */
580 static void
581 echo_truncate (len)
582 int len;
584 echobuf[len] = '\0';
585 echoptr = echobuf + len;
589 /* Functions for manipulating this_command_keys. */
590 static void
591 add_command_key (key)
592 Lisp_Object key;
594 int size = XVECTOR (this_command_keys)->size;
596 if (this_command_key_count >= size)
598 Lisp_Object new_keys = Fmake_vector (make_number (size * 2), Qnil);
600 bcopy (XVECTOR (this_command_keys)->contents,
601 XVECTOR (new_keys)->contents,
602 size * sizeof (Lisp_Object));
604 this_command_keys = new_keys;
607 XVECTOR (this_command_keys)->contents[this_command_key_count++] = key;
610 Lisp_Object
611 recursive_edit_1 ()
613 int count = specpdl_ptr - specpdl;
614 Lisp_Object val;
616 if (command_loop_level > 0)
618 specbind (Qstandard_output, Qt);
619 specbind (Qstandard_input, Qt);
622 val = command_loop ();
623 if (EQ (val, Qt))
624 Fsignal (Qquit, Qnil);
626 return unbind_to (count, Qnil);
629 /* When an auto-save happens, record the "time", and don't do again soon. */
630 record_auto_save ()
632 last_auto_save = num_nonmacro_input_chars;
635 DEFUN ("recursive-edit", Frecursive_edit, Srecursive_edit, 0, 0, "",
636 "Invoke the editor command loop recursively.\n\
637 To get out of the recursive edit, a command can do `(throw 'exit nil)';\n\
638 that tells this function to return.\n\
639 Alternately, `(throw 'exit t)' makes this function signal an error.\n\
640 This function is called by the editor initialization to begin editing.")
643 int count = specpdl_ptr - specpdl;
644 Lisp_Object val;
646 command_loop_level++;
647 update_mode_lines = 1;
649 record_unwind_protect (recursive_edit_unwind,
650 (command_loop_level
651 && current_buffer != XBUFFER (XWINDOW (selected_window)->buffer))
652 ? Fcurrent_buffer ()
653 : Qnil);
654 recursive_edit_1 ();
655 return unbind_to (count, Qnil);
658 Lisp_Object
659 recursive_edit_unwind (buffer)
660 Lisp_Object buffer;
662 if (!NILP (buffer))
663 Fset_buffer (buffer);
665 command_loop_level--;
666 update_mode_lines = 1;
667 return Qnil;
670 Lisp_Object
671 cmd_error (data)
672 Lisp_Object data;
674 Lisp_Object errmsg, tail, errname, file_error;
675 Lisp_Object stream;
676 struct gcpro gcpro1;
677 int i;
679 Vquit_flag = Qnil;
680 Vinhibit_quit = Qt;
681 Vstandard_output = Qt;
682 Vstandard_input = Qt;
683 Vexecuting_macro = Qnil;
684 echo_area_glyphs = 0;
686 /* If the window system or terminal frame hasn't been initialized
687 yet, or we're not interactive, it's best to dump this message out
688 to stderr and exit. */
689 if (! FRAME_MESSAGE_BUF (selected_frame)
690 || noninteractive)
691 stream = Qexternal_debugging_output;
692 else
694 Fdiscard_input ();
695 bitch_at_user ();
696 stream = Qt;
699 errname = Fcar (data);
701 if (EQ (errname, Qerror))
703 data = Fcdr (data);
704 if (!CONSP (data)) data = Qnil;
705 errmsg = Fcar (data);
706 file_error = Qnil;
708 else
710 errmsg = Fget (errname, Qerror_message);
711 file_error = Fmemq (Qfile_error,
712 Fget (errname, Qerror_conditions));
715 /* Print an error message including the data items.
716 This is done by printing it into a scratch buffer
717 and then making a copy of the text in the buffer. */
719 if (!CONSP (data)) data = Qnil;
720 tail = Fcdr (data);
721 GCPRO1 (tail);
723 /* For file-error, make error message by concatenating
724 all the data items. They are all strings. */
725 if (!NILP (file_error) && !NILP (tail))
726 errmsg = XCONS (tail)->car, tail = XCONS (tail)->cdr;
728 if (XTYPE (errmsg) == Lisp_String)
729 Fprinc (errmsg, stream);
730 else
731 write_string_1 ("peculiar error", -1, stream);
733 for (i = 0; CONSP (tail); tail = Fcdr (tail), i++)
735 write_string_1 (i ? ", " : ": ", 2, stream);
736 if (!NILP (file_error))
737 Fprinc (Fcar (tail), stream);
738 else
739 Fprin1 (Fcar (tail), stream);
741 UNGCPRO;
743 /* If the window system or terminal frame hasn't been initialized
744 yet, or we're in -batch mode, this error should cause Emacs to exit. */
745 if (! FRAME_MESSAGE_BUF (selected_frame)
746 || noninteractive)
748 Fterpri (stream);
749 Fkill_emacs (make_number (-1));
752 Vquit_flag = Qnil;
754 Vinhibit_quit = Qnil;
755 return make_number (0);
758 Lisp_Object command_loop_1 ();
759 Lisp_Object command_loop_2 ();
760 Lisp_Object top_level_1 ();
762 /* Entry to editor-command-loop.
763 This level has the catches for exiting/returning to editor command loop.
764 It returns nil to exit recursive edit, t to abort it. */
766 Lisp_Object
767 command_loop ()
769 if (command_loop_level > 0 || minibuf_level > 0)
771 return internal_catch (Qexit, command_loop_2, Qnil);
773 else
774 while (1)
776 internal_catch (Qtop_level, top_level_1, Qnil);
777 internal_catch (Qtop_level, command_loop_2, Qnil);
779 /* End of file in -batch run causes exit here. */
780 if (noninteractive)
781 Fkill_emacs (Qt);
785 /* Here we catch errors in execution of commands within the
786 editing loop, and reenter the editing loop.
787 When there is an error, cmd_error runs and returns a non-nil
788 value to us. A value of nil means that cmd_loop_1 itself
789 returned due to end of file (or end of kbd macro). */
791 Lisp_Object
792 command_loop_2 ()
794 register Lisp_Object val;
797 val = internal_condition_case (command_loop_1, Qerror, cmd_error);
798 while (!NILP (val));
800 return Qnil;
803 Lisp_Object
804 top_level_2 ()
806 return Feval (Vtop_level);
809 Lisp_Object
810 top_level_1 ()
812 /* On entry to the outer level, run the startup file */
813 if (!NILP (Vtop_level))
814 internal_condition_case (top_level_2, Qerror, cmd_error);
815 else if (!NILP (Vpurify_flag))
816 message ("Bare impure Emacs (standard Lisp code not loaded)");
817 else
818 message ("Bare Emacs (standard Lisp code not loaded)");
819 return Qnil;
822 DEFUN ("top-level", Ftop_level, Stop_level, 0, 0, "",
823 "Exit all recursive editing levels.")
826 Fthrow (Qtop_level, Qnil);
829 DEFUN ("exit-recursive-edit", Fexit_recursive_edit, Sexit_recursive_edit, 0, 0, "",
830 "Exit from the innermost recursive edit or minibuffer.")
833 if (command_loop_level > 0 || minibuf_level > 0)
834 Fthrow (Qexit, Qnil);
836 error ("No recursive edit is in progress");
839 DEFUN ("abort-recursive-edit", Fabort_recursive_edit, Sabort_recursive_edit, 0, 0, "",
840 "Abort the command that requested this recursive edit or minibuffer input.")
843 if (command_loop_level > 0 || minibuf_level > 0)
844 Fthrow (Qexit, Qt);
846 error ("No recursive edit is in progress");
849 /* This is the actual command reading loop,
850 sans error-handling encapsulation. */
852 Lisp_Object Fcommand_execute ();
853 static int read_key_sequence ();
855 Lisp_Object
856 command_loop_1 ()
858 Lisp_Object cmd, tem;
859 int lose;
860 int nonundocount;
861 Lisp_Object keybuf[30];
862 int i;
863 int no_redisplay;
864 int no_direct;
865 int prev_modiff;
866 struct buffer *prev_buffer;
868 Vprefix_arg = Qnil;
869 Vdeactivate_mark = Qnil;
870 waiting_for_input = 0;
871 cancel_echoing ();
873 /* Don't clear out last_command at the beginning of a macro. */
874 if (XTYPE (Vexecuting_macro) != Lisp_String)
875 last_command = Qt;
877 nonundocount = 0;
878 no_redisplay = 0;
879 this_command_key_count = 0;
881 while (1)
883 /* Install chars successfully executed in kbd macro. */
885 if (defining_kbd_macro && NILP (Vprefix_arg))
886 finalize_kbd_macro_chars ();
888 /* Make sure the current window's buffer is selected. */
889 if (XBUFFER (XWINDOW (selected_window)->buffer) != current_buffer)
890 set_buffer_internal (XBUFFER (XWINDOW (selected_window)->buffer));
892 /* Display any malloc warning that just came out. Use while because
893 displaying one warning can cause another. */
895 while (pending_malloc_warning)
896 display_malloc_warning ();
898 no_direct = 0;
900 Vdeactivate_mark = Qnil;
902 /* If minibuffer on and echo area in use,
903 wait 2 sec and redraw minibufer. */
905 if (minibuf_level && echo_area_glyphs)
907 /* Bind inhibit-quit to t so that C-g gets read in
908 rather than quitting back to the minibuffer. */
909 int count = specpdl_ptr - specpdl;
910 specbind (Qinhibit_quit, Qt);
911 Fsit_for (make_number (2), Qnil, Qnil);
912 unbind_to (count, Qnil);
914 echo_area_glyphs = 0;
915 no_direct = 1;
916 if (!NILP (Vquit_flag))
918 Vquit_flag = Qnil;
919 unread_command_events = Fcons (make_number (quit_char), Qnil);
923 #ifdef C_ALLOCA
924 alloca (0); /* Cause a garbage collection now */
925 /* Since we can free the most stuff here. */
926 #endif /* C_ALLOCA */
928 #if 0
929 #ifdef MULTI_FRAME
930 /* Select the frame that the last event came from. Usually,
931 switch-frame events will take care of this, but if some lisp
932 code swallows a switch-frame event, we'll fix things up here.
933 Is this a good idea? */
934 if (XTYPE (internal_last_event_frame) == Lisp_Frame
935 && XFRAME (internal_last_event_frame) != selected_frame)
936 Fselect_frame (internal_last_event_frame, Qnil);
937 #endif
938 #endif
939 /* If it has changed current-menubar from previous value,
940 really recompute the menubar from the value. */
941 if (! NILP (Vlucid_menu_bar_dirty_flag))
942 call0 (Qrecompute_lucid_menubar);
944 #ifdef MULTI_FRAME
945 for (tem = Vframe_list; CONSP (tem); tem = XCONS (tem)->cdr)
947 struct frame *f = XFRAME (XCONS (tem)->car);
948 struct window *w = XWINDOW (FRAME_SELECTED_WINDOW (f));
950 /* If the user has switched buffers or windows, we need to
951 recompute to reflect the new bindings. But we'll
952 recompute when update_mode_lines is set too; that means
953 that people can use force-mode-line-update to request
954 that the menu bar be recomputed. The adverse effect on
955 the rest of the redisplay algorithm is about the same as
956 windows_or_buffers_changed anyway. */
957 if (windows_or_buffers_changed
958 || update_mode_lines
959 || (XFASTINT (w->last_modified) < MODIFF
960 && (XFASTINT (w->last_modified)
961 <= XBUFFER (w->buffer)->save_modified)))
963 struct buffer *prev = current_buffer;
964 current_buffer = XBUFFER (w->buffer);
965 FRAME_MENU_BAR_ITEMS (f) = menu_bar_items ();
966 current_buffer = prev;
969 #endif /* MULTI_FRAME */
971 /* Read next key sequence; i gets its length. */
972 i = read_key_sequence (keybuf, (sizeof keybuf / sizeof (keybuf[0])), 0);
974 ++num_input_keys;
976 /* Now we have read a key sequence of length I,
977 or else I is 0 and we found end of file. */
979 if (i == 0) /* End of file -- happens only in */
980 return Qnil; /* a kbd macro, at the end. */
982 last_command_char = keybuf[i - 1];
984 /* If the previous command tried to force a specific window-start,
985 forget about that, in case this command moves point far away
986 from that position. */
987 XWINDOW (selected_window)->force_start = Qnil;
989 cmd = read_key_sequence_cmd;
990 if (!NILP (Vexecuting_macro))
992 if (!NILP (Vquit_flag))
994 Vexecuting_macro = Qt;
995 QUIT; /* Make some noise. */
996 /* Will return since macro now empty. */
1000 /* Do redisplay processing after this command except in special
1001 cases identified below that set no_redisplay to 1. */
1002 no_redisplay = 0;
1004 prev_buffer = current_buffer;
1005 prev_modiff = MODIFF;
1007 /* Execute the command. */
1009 this_command = cmd;
1010 if (!NILP (Vpre_command_hook))
1011 call1 (Vrun_hooks, Qpre_command_hook);
1013 if (NILP (cmd))
1015 /* nil means key is undefined. */
1016 bitch_at_user ();
1017 defining_kbd_macro = 0;
1018 update_mode_lines = 1;
1019 Vprefix_arg = Qnil;
1022 else
1024 if (NILP (Vprefix_arg) && ! no_direct)
1026 /* Recognize some common commands in common situations and
1027 do them directly. */
1028 if (EQ (cmd, Qforward_char) && point < ZV)
1030 struct Lisp_Vector *dp
1031 = window_display_table (XWINDOW (selected_window));
1032 lose = FETCH_CHAR (point);
1033 SET_PT (point + 1);
1034 if ((dp
1035 ? (XTYPE (DISP_CHAR_VECTOR (dp, lose)) != Lisp_Vector
1036 && XVECTOR (DISP_CHAR_VECTOR (dp, lose))->size == 1)
1037 : (lose >= 0x20 && lose < 0x7f))
1038 && (XFASTINT (XWINDOW (selected_window)->last_modified)
1039 >= MODIFF)
1040 && (XFASTINT (XWINDOW (selected_window)->last_point)
1041 == point - 1)
1042 && !windows_or_buffers_changed
1043 && EQ (current_buffer->selective_display, Qnil)
1044 && !detect_input_pending ()
1045 && NILP (Vexecuting_macro))
1046 no_redisplay = direct_output_forward_char (1);
1047 goto directly_done;
1049 else if (EQ (cmd, Qbackward_char) && point > BEGV)
1051 struct Lisp_Vector *dp
1052 = window_display_table (XWINDOW (selected_window));
1053 SET_PT (point - 1);
1054 lose = FETCH_CHAR (point);
1055 if ((dp
1056 ? (XTYPE (DISP_CHAR_VECTOR (dp, lose)) != Lisp_Vector
1057 && XVECTOR (DISP_CHAR_VECTOR (dp, lose))->size == 1)
1058 : (lose >= 0x20 && lose < 0x7f))
1059 && (XFASTINT (XWINDOW (selected_window)->last_modified)
1060 >= MODIFF)
1061 && (XFASTINT (XWINDOW (selected_window)->last_point)
1062 == point + 1)
1063 && !windows_or_buffers_changed
1064 && EQ (current_buffer->selective_display, Qnil)
1065 && !detect_input_pending ()
1066 && NILP (Vexecuting_macro))
1067 no_redisplay = direct_output_forward_char (-1);
1068 goto directly_done;
1070 else if (EQ (cmd, Qself_insert_command)
1071 /* Try this optimization only on ascii keystrokes. */
1072 && XTYPE (last_command_char) == Lisp_Int)
1074 unsigned char c = XINT (last_command_char);
1076 if (NILP (Vexecuting_macro) &&
1077 !EQ (minibuf_window, selected_window))
1079 if (!nonundocount || nonundocount >= 20)
1081 Fundo_boundary ();
1082 nonundocount = 0;
1084 nonundocount++;
1086 lose = (XFASTINT (XWINDOW (selected_window)->last_modified)
1087 < MODIFF)
1088 || (XFASTINT (XWINDOW (selected_window)->last_point)
1089 != point)
1090 || MODIFF <= current_buffer->save_modified
1091 || windows_or_buffers_changed
1092 || !EQ (current_buffer->selective_display, Qnil)
1093 || detect_input_pending ()
1094 || !NILP (Vexecuting_macro);
1095 if (internal_self_insert (XINT (c), 0))
1097 lose = 1;
1098 nonundocount = 0;
1100 if (!lose &&
1101 (point == ZV || FETCH_CHAR (point) == '\n'))
1103 struct Lisp_Vector *dp
1104 = window_display_table (XWINDOW (selected_window));
1105 int lose = XINT (c);
1107 if (dp)
1109 Lisp_Object obj = DISP_CHAR_VECTOR (dp, lose);
1111 if (XTYPE (obj) == Lisp_Vector
1112 && XVECTOR (obj)->size == 1
1113 && (XTYPE (obj = XVECTOR (obj)->contents[0])
1114 == Lisp_Int))
1115 no_redisplay =
1116 direct_output_for_insert (XINT (obj));
1118 else
1120 if (lose >= 0x20 && lose <= 0x7e)
1121 no_redisplay = direct_output_for_insert (lose);
1124 goto directly_done;
1128 /* Here for a command that isn't executed directly */
1130 nonundocount = 0;
1131 if (NILP (Vprefix_arg))
1132 Fundo_boundary ();
1133 Fcommand_execute (cmd, Qnil);
1136 directly_done: ;
1138 if (!NILP (Vpost_command_hook))
1139 call1 (Vrun_hooks, Qpost_command_hook);
1141 /* If there is a prefix argument,
1142 1) We don't want last_command to be ``universal-argument''
1143 (that would be dumb), so don't set last_command,
1144 2) we want to leave echoing on so that the prefix will be
1145 echoed as part of this key sequence, so don't call
1146 cancel_echoing, and
1147 3) we want to leave this_command_key_count non-zero, so that
1148 read_char will realize that it is re-reading a character, and
1149 not echo it a second time. */
1150 if (NILP (Vprefix_arg))
1152 last_command = this_command;
1153 cancel_echoing ();
1154 this_command_key_count = 0;
1157 if (!NILP (current_buffer->mark_active))
1159 if (!NILP (Vdeactivate_mark) && !NILP (Vtransient_mark_mode))
1161 current_buffer->mark_active = Qnil;
1162 call1 (Vrun_hooks, intern ("deactivate-mark-hook"));
1164 else if (current_buffer != prev_buffer || MODIFF != prev_modiff)
1165 call1 (Vrun_hooks, intern ("activate-mark-hook"));
1170 /* Number of seconds between polling for input. */
1171 int polling_period;
1173 /* Nonzero means polling for input is temporarily suppresed. */
1174 int poll_suppress_count;
1176 #ifdef POLL_FOR_INPUT
1177 int polling_for_input;
1179 /* Handle an alarm once each second and read pending input
1180 so as to handle a C-g if it comces in. */
1182 SIGTYPE
1183 input_poll_signal ()
1185 if (interrupt_input_blocked == 0
1186 && !waiting_for_input)
1187 read_avail_input (0);
1188 signal (SIGALRM, input_poll_signal);
1189 alarm (polling_period);
1192 #endif
1194 /* Begin signals to poll for input, if they are appropriate.
1195 This function is called unconditionally from various places. */
1197 start_polling ()
1199 #ifdef POLL_FOR_INPUT
1200 if (read_socket_hook)
1202 poll_suppress_count--;
1203 if (poll_suppress_count == 0)
1205 signal (SIGALRM, input_poll_signal);
1206 polling_for_input = 1;
1207 alarm (polling_period);
1210 #endif
1213 /* Turn off polling. */
1215 stop_polling ()
1217 #ifdef POLL_FOR_INPUT
1218 if (read_socket_hook)
1220 if (poll_suppress_count == 0)
1222 polling_for_input = 0;
1223 alarm (0);
1225 poll_suppress_count++;
1227 #endif
1230 /* Input of single characters from keyboard */
1232 Lisp_Object print_help ();
1233 static Lisp_Object kbd_buffer_get_event ();
1235 /* read a character from the keyboard; call the redisplay if needed */
1236 /* commandflag 0 means do not do auto-saving, but do do redisplay.
1237 -1 means do not do redisplay, but do do autosaving.
1238 1 means do both. */
1240 /* The arguments MAPS and NMAPS are for menu prompting.
1241 MAPS is an array of keymaps; NMAPS is the length of MAPS.
1243 PREV_EVENT is the previous input event, or nil if we are reading
1244 the first event of a key sequence.
1246 If USED_MOUSE_MENU is non-zero, then we set *USED_MOUSE_MENU to 1
1247 if we used a mouse menu to read the input, or zero otherwise. If
1248 USED_MOUSE_MENU is zero, *USED_MOUSE_MENU is left alone. */
1250 Lisp_Object
1251 read_char (commandflag, nmaps, maps, prev_event, used_mouse_menu)
1252 int commandflag;
1253 int nmaps;
1254 Lisp_Object *maps;
1255 Lisp_Object prev_event;
1256 int *used_mouse_menu;
1258 register Lisp_Object c;
1259 int count;
1260 jmp_buf save_jump;
1262 if (CONSP (unread_command_events))
1264 c = XCONS (unread_command_events)->car;
1265 unread_command_events = XCONS (unread_command_events)->cdr;
1267 if (this_command_key_count == 0)
1268 goto reread_first;
1269 else
1270 goto reread;
1273 if (unread_command_char != -1)
1275 XSET (c, Lisp_Int, unread_command_char);
1276 unread_command_char = -1;
1278 if (this_command_key_count == 0)
1279 goto reread_first;
1280 else
1281 goto reread;
1284 if (!NILP (Vexecuting_macro))
1286 #ifdef MULTI_FRAME
1287 /* We set this to Qmacro; since that's not a frame, nobody will
1288 try to switch frames on us, and the selected window will
1289 remain unchanged.
1291 Since this event came from a macro, it would be misleading to
1292 leave internal_last_event_frame set to whereever the last
1293 real event came from. Normally, a switch-frame event selects
1294 internal_last_event_frame after each command is read, but
1295 events read from a macro should never cause a new frame to be
1296 selected. */
1297 Vlast_event_frame = internal_last_event_frame = Qmacro;
1298 #endif
1300 if (executing_macro_index >= XFASTINT (Flength (Vexecuting_macro)))
1302 XSET (c, Lisp_Int, -1);
1303 return c;
1306 c = Faref (Vexecuting_macro, make_number (executing_macro_index));
1307 if (XTYPE (Vexecuting_macro) == Lisp_String
1308 && (XINT (c) & 0x80))
1309 XFASTINT (c) = CHAR_META | (XINT (c) & ~0x80);
1311 executing_macro_index++;
1313 goto from_macro;
1316 if (!NILP (unread_switch_frame))
1318 c = unread_switch_frame;
1319 unread_switch_frame = Qnil;
1321 /* This event should make it into this_command_keys, and get echoed
1322 again, so we go to reread_first, rather than reread. */
1323 goto reread_first;
1326 /* Save outer setjmp data, in case called recursively. */
1327 save_getcjmp (save_jump);
1329 stop_polling ();
1331 if (commandflag >= 0 && !input_pending && !detect_input_pending ())
1332 redisplay ();
1334 if (_setjmp (getcjmp))
1336 XSET (c, Lisp_Int, quit_char);
1337 #ifdef MULTI_FRAME
1338 XSET (internal_last_event_frame, Lisp_Frame, selected_frame);
1339 Vlast_event_frame = internal_last_event_frame;
1340 #endif
1341 /* If we report the quit char as an event,
1342 don't do so more than once. */
1343 if (!NILP (Vinhibit_quit))
1344 Vquit_flag = Qnil;
1346 goto non_reread;
1349 /* Message turns off echoing unless more keystrokes turn it on again. */
1350 if (echo_area_glyphs && *echo_area_glyphs && echo_area_glyphs != echobuf)
1351 cancel_echoing ();
1352 else
1353 /* If already echoing, continue. */
1354 echo_dash ();
1356 /* If in middle of key sequence and minibuffer not active,
1357 start echoing if enough time elapses. */
1358 if (minibuf_level == 0 && !immediate_echo && this_command_key_count > 0
1359 && echo_keystrokes > 0
1360 && (echo_area_glyphs == 0 || *echo_area_glyphs == 0))
1362 Lisp_Object tem0;
1364 /* After a mouse event, start echoing right away.
1365 This is because we are probably about to display a menu,
1366 and we don't want to delay before doing so. */
1367 if (EVENT_HAS_PARAMETERS (prev_event))
1368 echo ();
1369 else
1371 tem0 = sit_for (echo_keystrokes, 0, 1, 1);
1372 if (EQ (tem0, Qt))
1373 echo ();
1377 /* Maybe auto save due to number of keystrokes or idle time. */
1379 if (commandflag != 0
1380 && auto_save_interval > 0
1381 && num_nonmacro_input_chars - last_auto_save > max (auto_save_interval, 20)
1382 && !detect_input_pending ())
1384 jmp_buf temp;
1385 save_getcjmp (temp);
1386 Fdo_auto_save (Qnil, Qnil);
1387 restore_getcjmp (temp);
1390 /* Try reading a character via menu prompting.
1391 Try this before the sit-for, because the sit-for
1392 would do the wrong thing if we are supposed to do
1393 menu prompting. */
1394 c = Qnil;
1395 if (INTERACTIVE && !NILP (prev_event))
1396 c = read_char_menu_prompt (nmaps, maps, prev_event, used_mouse_menu);
1398 /* Slow down auto saves logarithmically in size of current buffer,
1399 and garbage collect while we're at it. */
1400 if (NILP (c))
1402 int delay_level, buffer_size;
1404 if (! MINI_WINDOW_P (XWINDOW (selected_window)))
1405 last_non_minibuf_size = Z - BEG;
1406 buffer_size = (last_non_minibuf_size >> 8) + 1;
1407 delay_level = 0;
1408 while (buffer_size > 64)
1409 delay_level++, buffer_size -= buffer_size >> 2;
1410 if (delay_level < 4) delay_level = 4;
1411 /* delay_level is 4 for files under around 50k, 7 at 100k,
1412 9 at 200k, 11 at 300k, and 12 at 500k. It is 15 at 1 meg. */
1414 /* Auto save if enough time goes by without input. */
1415 if (commandflag != 0
1416 && num_nonmacro_input_chars > last_auto_save
1417 && XTYPE (Vauto_save_timeout) == Lisp_Int
1418 && XINT (Vauto_save_timeout) > 0)
1420 Lisp_Object tem0;
1421 int delay = delay_level * XFASTINT (Vauto_save_timeout) / 4;
1422 tem0 = sit_for (delay, 0, 1, 1);
1423 if (EQ (tem0, Qt))
1425 jmp_buf temp;
1426 save_getcjmp (temp);
1427 Fdo_auto_save (Qnil, Qnil);
1428 restore_getcjmp (temp);
1430 /* If we have auto-saved and there is still no input
1431 available, garbage collect if there has been enough
1432 consing going on to make it worthwhile. */
1433 if (!detect_input_pending ()
1434 && consing_since_gc > gc_cons_threshold / 2)
1435 Fgarbage_collect ();
1440 /* Actually read a character, waiting if necessary. */
1441 if (NILP (c))
1442 c = kbd_buffer_get_event ();
1444 if (NILP (c))
1445 abort (); /* Don't think this can happen. */
1447 /* Terminate Emacs in batch mode if at eof. */
1448 if (noninteractive && XTYPE (c) == Lisp_Int && XINT (c) < 0)
1449 Fkill_emacs (make_number (1));
1451 /* Test for ControlMask and Mod1Mask. */
1452 if (extra_keyboard_modifiers & 4)
1453 c &= ~0140;
1454 if (extra_keyboard_modifiers & 8)
1455 c |= 0200;
1457 non_reread:
1459 restore_getcjmp (save_jump);
1461 start_polling ();
1463 echo_area_glyphs = 0;
1465 /* Handle things that only apply to characters. */
1466 if (XTYPE (c) == Lisp_Int)
1468 /* If kbd_buffer_get_event gave us an EOF, return that. */
1469 if (XINT (c) == -1)
1470 return c;
1472 if (XTYPE (Vkeyboard_translate_table) == Lisp_String
1473 && XSTRING (Vkeyboard_translate_table)->size > XFASTINT (c))
1474 XSETINT (c, XSTRING (Vkeyboard_translate_table)->data[XFASTINT (c)]);
1477 total_keys++;
1478 XVECTOR (recent_keys)->contents[recent_keys_index] = c;
1479 if (++recent_keys_index >= NUM_RECENT_KEYS)
1480 recent_keys_index = 0;
1482 /* Write c to the dribble file. If c is a lispy event, write
1483 the event's symbol to the dribble file, in <brackets>. Bleaugh.
1484 If you, dear reader, have a better idea, you've got the source. :-) */
1485 if (dribble)
1487 if (XTYPE (c) == Lisp_Int)
1488 putc (XINT (c), dribble);
1489 else
1491 Lisp_Object dribblee = c;
1493 /* If it's a structured event, take the event header. */
1494 dribblee = EVENT_HEAD (dribblee);
1496 if (XTYPE (dribblee) == Lisp_Symbol)
1498 putc ('<', dribble);
1499 fwrite (XSYMBOL (dribblee)->name->data, sizeof (char),
1500 XSYMBOL (dribblee)->name->size,
1501 dribble);
1502 putc ('>', dribble);
1506 fflush (dribble);
1509 store_kbd_macro_char (c);
1511 num_nonmacro_input_chars++;
1513 from_macro:
1514 reread_first:
1516 /* Record this character as part of the current key.
1517 Don't record mouse motion; it should never matter. */
1518 if (! (EVENT_HAS_PARAMETERS (c)
1519 && EQ (EVENT_HEAD_KIND (EVENT_HEAD (c)), Qmouse_movement)))
1521 echo_char (c);
1522 add_command_key (c);
1525 /* Re-reading in the middle of a command */
1526 reread:
1527 last_input_char = c;
1528 num_input_chars++;
1530 /* Process the help character specially if enabled */
1531 if (EQ (c, help_char) && !NILP (Vhelp_form))
1533 Lisp_Object tem0;
1534 count = specpdl_ptr - specpdl;
1536 record_unwind_protect (Fset_window_configuration,
1537 Fcurrent_window_configuration (Qnil));
1539 tem0 = Feval (Vhelp_form);
1540 if (XTYPE (tem0) == Lisp_String)
1541 internal_with_output_to_temp_buffer ("*Help*", print_help, tem0);
1543 cancel_echoing ();
1544 c = read_char (0, 0, 0, Qnil, 0);
1545 /* Remove the help from the frame */
1546 unbind_to (count, Qnil);
1547 redisplay ();
1548 if (EQ (c, make_number (040)))
1550 cancel_echoing ();
1551 c = read_char (0, 0, 0, Qnil, 0);
1555 return c;
1558 Lisp_Object
1559 print_help (object)
1560 Lisp_Object object;
1562 Fprinc (object, Qnil);
1563 return Qnil;
1566 /* Copy out or in the info on where C-g should throw to.
1567 This is used when running Lisp code from within get_char,
1568 in case get_char is called recursively.
1569 See read_process_output. */
1571 save_getcjmp (temp)
1572 jmp_buf temp;
1574 bcopy (getcjmp, temp, sizeof getcjmp);
1577 restore_getcjmp (temp)
1578 jmp_buf temp;
1580 bcopy (temp, getcjmp, sizeof getcjmp);
1584 /* Low level keyboard/mouse input.
1585 kbd_buffer_store_event places events in kbd_buffer, and
1586 kbd_buffer_get_event retrieves them.
1587 mouse_moved indicates when the mouse has moved again, and
1588 *mouse_position_hook provides the mouse position. */
1590 /* Set this for debugging, to have a way to get out */
1591 int stop_character;
1593 extern int frame_garbaged;
1595 /* Return true iff there are any events in the queue that read-char
1596 would return. If this returns false, a read-char would block. */
1597 static int
1598 readable_events ()
1600 return ! EVENT_QUEUES_EMPTY;
1604 /* Restore mouse tracking enablement. See Ftrack_mouse for the only use
1605 of this function. */
1606 static Lisp_Object
1607 tracking_off (old_value)
1608 Lisp_Object old_value;
1610 if (! XFASTINT (old_value))
1612 do_mouse_tracking = 0;
1614 /* Redisplay may have been preempted because there was input
1615 available, and it assumes it will be called again after the
1616 input has been processed. If the only input available was
1617 the sort that we have just disabled, then we need to call
1618 redisplay. */
1619 if (!readable_events ())
1621 redisplay_preserve_echo_area ();
1622 get_input_pending (&input_pending);
1627 DEFUN ("track-mouse", Ftrack_mouse, Strack_mouse, 0, UNEVALLED, 0,
1628 "Evaluate BODY with mouse movement events enabled.\n\
1629 Within a `track-mouse' form, mouse motion generates input events that\n\
1630 you can read with `read-event'.\n\
1631 Normally, mouse motion is ignored.")
1632 (args)
1633 Lisp_Object args;
1635 int count = specpdl_ptr - specpdl;
1636 Lisp_Object val;
1638 XSET (val, Lisp_Int, do_mouse_tracking);
1639 record_unwind_protect (tracking_off, val);
1641 do_mouse_tracking = 1;
1643 val = Fprogn (args);
1644 return unbind_to (count, val);
1647 /* Store an event obtained at interrupt level into kbd_buffer, fifo */
1649 void
1650 kbd_buffer_store_event (event)
1651 register struct input_event *event;
1653 if (event->kind == no_event)
1654 abort ();
1656 if (event->kind == ascii_keystroke)
1658 register int c = XFASTINT (event->code) & 0377;
1660 if (c == quit_char)
1662 extern SIGTYPE interrupt_signal ();
1664 #ifdef MULTI_FRAME
1665 /* If this results in a quit_char being returned to Emacs as
1666 input, set Vlast_event_frame properly. If this doesn't
1667 get returned to Emacs as an event, the next event read
1668 will set Vlast_event_frame again, so this is safe to do. */
1670 Lisp_Object focus =
1671 FRAME_FOCUS_FRAME (XFRAME (event->frame_or_window));
1673 if (NILP (focus))
1674 internal_last_event_frame = event->frame_or_window;
1675 else
1676 internal_last_event_frame = focus;
1677 Vlast_event_frame = internal_last_event_frame;
1679 #endif
1681 last_event_timestamp = event->timestamp;
1682 interrupt_signal ();
1683 return;
1686 if (c && c == stop_character)
1688 sys_suspend ();
1689 return;
1692 XSET (event->code, Lisp_Int, c);
1695 if (kbd_store_ptr - kbd_buffer == KBD_BUFFER_SIZE)
1696 kbd_store_ptr = kbd_buffer;
1698 /* Don't let the very last slot in the buffer become full,
1699 since that would make the two pointers equal,
1700 and that is indistinguishable from an empty buffer.
1701 Discard the event if it would fill the last slot. */
1702 if (kbd_fetch_ptr - 1 != kbd_store_ptr)
1704 kbd_store_ptr->kind = event->kind;
1705 kbd_store_ptr->code = event->code;
1706 kbd_store_ptr->part = event->part;
1707 kbd_store_ptr->frame_or_window = event->frame_or_window;
1708 kbd_store_ptr->modifiers = event->modifiers;
1709 kbd_store_ptr->x = event->x;
1710 kbd_store_ptr->y = event->y;
1711 kbd_store_ptr->timestamp = event->timestamp;
1712 (XVECTOR (kbd_buffer_frame_or_window)->contents[kbd_store_ptr
1713 - kbd_buffer]
1714 = event->frame_or_window);
1716 kbd_store_ptr++;
1720 static Lisp_Object make_lispy_event ();
1721 static Lisp_Object make_lispy_movement ();
1722 static Lisp_Object modify_event_symbol ();
1723 static Lisp_Object make_lispy_switch_frame ();
1725 static Lisp_Object
1726 kbd_buffer_get_event ()
1728 register int c;
1729 Lisp_Object obj;
1731 if (noninteractive)
1733 c = getchar ();
1734 XSET (obj, Lisp_Int, c);
1735 return obj;
1738 retry:
1739 /* Wait until there is input available. */
1740 for (;;)
1742 if (!EVENT_QUEUES_EMPTY)
1743 break;
1745 /* If the quit flag is set, then read_char will return
1746 quit_char, so that counts as "available input." */
1747 if (!NILP (Vquit_flag))
1748 quit_throw_to_read_char ();
1750 /* One way or another, wait until input is available; then, if
1751 interrupt handlers have not read it, read it now. */
1753 #ifdef OLDVMS
1754 wait_for_kbd_input ();
1755 #else
1756 /* Note SIGIO has been undef'd if FIONREAD is missing. */
1757 #ifdef SIGIO
1758 gobble_input (0);
1759 #endif /* SIGIO */
1760 if (EVENT_QUEUES_EMPTY)
1762 Lisp_Object minus_one;
1764 XSET (minus_one, Lisp_Int, -1);
1765 wait_reading_process_input (0, 0, minus_one, 1);
1767 if (!interrupt_input && EVENT_QUEUES_EMPTY)
1769 read_avail_input (0);
1772 #endif /* not VMS */
1775 /* At this point, we know that there is a readable event available
1776 somewhere. If the event queue is empty, then there must be a
1777 mouse movement enabled and available. */
1778 if (kbd_fetch_ptr != kbd_store_ptr)
1780 struct input_event *event;
1782 event = ((kbd_fetch_ptr < kbd_buffer + KBD_BUFFER_SIZE)
1783 ? kbd_fetch_ptr
1784 : kbd_buffer);
1786 last_event_timestamp = event->timestamp;
1788 obj = Qnil;
1790 /* These two kinds of events get special handling
1791 and don't actually appear to the command loop. */
1792 if (event->kind == selection_request_event)
1794 #ifdef HAVE_X11
1795 x_handle_selection_request (event);
1796 kbd_fetch_ptr = event + 1;
1797 goto retry;
1798 #else
1799 /* We're getting selection request events, but we don't have
1800 a window system. */
1801 abort ();
1802 #endif
1805 if (event->kind == selection_clear_event)
1807 #ifdef HAVE_X11
1808 x_handle_selection_clear (event);
1809 kbd_fetch_ptr = event + 1;
1810 goto retry;
1811 #else
1812 /* We're getting selection request events, but we don't have
1813 a window system. */
1814 abort ();
1815 #endif
1818 #ifdef MULTI_FRAME
1819 /* If this event is on a different frame, return a switch-frame this
1820 time, and leave the event in the queue for next time. */
1822 Lisp_Object frame = event->frame_or_window;
1823 Lisp_Object focus;
1825 if (XTYPE (frame) == Lisp_Window)
1826 frame = WINDOW_FRAME (XWINDOW (frame));
1828 focus = FRAME_FOCUS_FRAME (XFRAME (frame));
1829 if (! NILP (focus))
1830 frame = focus;
1832 if (! EQ (frame, internal_last_event_frame))
1834 internal_last_event_frame = frame;
1835 obj = make_lispy_switch_frame (frame);
1838 #endif
1840 /* If we didn't decide to make a switch-frame event, go ahead
1841 and build a real event from the queue entry. */
1842 if (NILP (obj))
1844 obj = make_lispy_event (event);
1846 /* Wipe out this event, to catch bugs. */
1847 event->kind = no_event;
1848 (XVECTOR (kbd_buffer_frame_or_window)->contents[event - kbd_buffer]
1849 = Qnil);
1851 kbd_fetch_ptr = event + 1;
1854 else if (do_mouse_tracking && mouse_moved)
1856 FRAME_PTR f;
1857 Lisp_Object bar_window;
1858 enum scroll_bar_part part;
1859 Lisp_Object x, y;
1860 unsigned long time;
1862 (*mouse_position_hook) (&f, &bar_window, &part, &x, &y, &time);
1864 obj = Qnil;
1866 #ifdef MULTI_FRAME
1867 /* Decide if we should generate a switch-frame event. Don't
1868 generate switch-frame events for motion outside of all Emacs
1869 frames. */
1870 if (f)
1872 Lisp_Object frame = FRAME_FOCUS_FRAME (f);
1874 if (NILP (frame))
1875 XSET (frame, Lisp_Frame, f);
1877 if (! EQ (frame, internal_last_event_frame))
1879 XSET (internal_last_event_frame, Lisp_Frame, frame);
1880 obj = make_lispy_switch_frame (internal_last_event_frame);
1883 #endif
1885 /* If we didn't decide to make a switch-frame event, go ahead and
1886 return a mouse-motion event. */
1887 if (NILP (obj))
1888 obj = make_lispy_movement (f, bar_window, part, x, y, time);
1890 else
1891 /* We were promised by the above while loop that there was
1892 something for us to read! */
1893 abort ();
1895 /* If something gave back nil as the Lispy event,
1896 it means the event was discarded, so try again. */
1897 if (NILP (obj))
1898 goto retry;
1900 input_pending = readable_events ();
1902 #ifdef MULTI_FRAME
1903 Vlast_event_frame = internal_last_event_frame;
1904 #endif
1906 return (obj);
1910 /* Caches for modify_event_symbol. */
1911 static Lisp_Object func_key_syms;
1912 static Lisp_Object mouse_syms;
1914 /* You'll notice that this table is arranged to be conveniently
1915 indexed by X Windows keysym values. */
1916 static char *lispy_function_keys[] =
1918 /* X Keysym value */
1920 0, 0, 0, 0, 0, 0, 0, 0, /* 0xff00 */
1921 "backspace",
1922 "tab",
1923 "linefeed",
1924 "clear",
1926 "return",
1927 0, 0,
1928 0, 0, 0, /* 0xff10 */
1929 "pause",
1930 0, 0, 0, 0, 0, 0, 0,
1931 "escape",
1932 0, 0, 0, 0,
1933 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* 0xff20...2f */
1934 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* 0xff30...3f */
1935 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* 0xff40...4f */
1937 "home", /* 0xff50 */ /* IsCursorKey */
1938 "left",
1939 "up",
1940 "right",
1941 "down",
1942 "prior",
1943 "next",
1944 "end",
1945 "begin",
1946 0, /* 0xff59 */
1947 0, 0, 0, 0, 0, 0,
1948 "select", /* 0xff60 */ /* IsMiscFunctionKey */
1949 "print",
1950 "execute",
1951 "insert",
1952 0, /* 0xff64 */
1953 "undo",
1954 "redo",
1955 "menu",
1956 "find",
1957 "cancel",
1958 "help",
1959 "break", /* 0xff6b */
1961 /* Here are some keys found mostly on HP keyboards. The X event
1962 handling code will strip bit 29, which flags vendor-specific
1963 keysyms. */
1964 "reset", /* 0x1000ff6c */
1965 "system",
1966 "user",
1967 "clearline",
1968 "insertline",
1969 "deleteline",
1970 "insertchar",
1971 "deletechar",
1972 "backtab",
1973 "kp_backtab", /* 0x1000ff75 */
1974 0, /* 0xff76 */
1975 0, 0, 0, 0, 0, 0, 0, 0, 0, /* 0xff7f */
1976 "kp-space", /* 0xff80 */ /* IsKeypadKey */
1977 0, 0, 0, 0, 0, 0, 0, 0,
1978 "kp-tab", /* 0xff89 */
1979 0, 0, 0,
1980 "kp-enter", /* 0xff8d */
1981 0, 0, 0,
1982 "kp-f1", /* 0xff91 */
1983 "kp-f2",
1984 "kp-f3",
1985 "kp-f4",
1986 0, /* 0xff95 */
1987 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
1988 "kp-multiply", /* 0xffaa */
1989 "kp-add",
1990 "kp-separator",
1991 "kp-subtract",
1992 "kp-decimal",
1993 "kp-divide", /* 0xffaf */
1994 "kp-0", /* 0xffb0 */
1995 "kp-1", "kp-2", "kp-3", "kp-4", "kp-5", "kp-6", "kp-7", "kp-8", "kp-9",
1996 0, /* 0xffba */
1997 0, 0,
1998 "kp-equal", /* 0xffbd */
1999 "f1", /* 0xffbe */ /* IsFunctionKey */
2000 "f2",
2001 "f3", "f4", "f5", "f6", "f7", "f8", "f9", "f10", /* 0xffc0 */
2002 "f11", "f12", "f13", "f14", "f15", "f16", "f17", "f18",
2003 "f19", "f20", "f21", "f22", "f23", "f24", "f25", "f26", /* 0xffd0 */
2004 "f27", "f28", "f29", "f30", "f31", "f32", "f33", "f34",
2005 "f35", 0, 0, 0, 0, 0, 0, 0, /* 0xffe0 */
2006 0, 0, 0, 0, 0, 0, 0, 0,
2007 0, 0, 0, 0, 0, 0, 0, 0, /* 0xfff0 */
2008 0, 0, 0, 0, 0, 0, 0, "delete"
2011 static char *lispy_mouse_names[] =
2013 "mouse-1", "mouse-2", "mouse-3", "mouse-4", "mouse-5"
2016 /* Scroll bar parts. */
2017 Lisp_Object Qabove_handle, Qhandle, Qbelow_handle;
2019 /* An array of scroll bar parts, indexed by an enum scroll_bar_part value. */
2020 Lisp_Object *scroll_bar_parts[] = {
2021 &Qabove_handle, &Qhandle, &Qbelow_handle
2025 /* A vector, indexed by button number, giving the down-going location
2026 of currently depressed buttons, both scroll bar and non-scroll bar.
2028 The elements have the form
2029 (BUTTON-NUMBER MODIFIER-MASK . REST)
2030 where REST is the cdr of a position as it would be reported in the event.
2032 The make_lispy_event function stores positions here to tell the
2033 difference between click and drag events, and to store the starting
2034 location to be included in drag events. */
2036 static Lisp_Object button_down_location;
2038 /* Given a struct input_event, build the lisp event which represents
2039 it. If EVENT is 0, build a mouse movement event from the mouse
2040 movement buffer, which should have a movement event in it.
2042 Note that events must be passed to this function in the order they
2043 are received; this function stores the location of button presses
2044 in order to build drag events when the button is released. */
2046 static Lisp_Object
2047 make_lispy_event (event)
2048 struct input_event *event;
2050 #ifdef SWITCH_ENUM_BUG
2051 switch ((int) event->kind)
2052 #else
2053 switch (event->kind)
2054 #endif
2056 /* A simple keystroke. */
2057 case ascii_keystroke:
2059 int c = XFASTINT (event->code);
2060 /* Include the bits for control and shift
2061 only if the basic ASCII code can't indicate them. */
2062 if ((event->modifiers & ctrl_modifier)
2063 && c >= 040)
2064 c |= ctrl_modifier;
2065 if (XFASTINT (event->code) < 040
2066 && (event->modifiers & shift_modifier))
2067 c |= shift_modifier;
2068 c |= (event->modifiers
2069 & (meta_modifier | alt_modifier
2070 | hyper_modifier | super_modifier));
2071 return c;
2074 /* A function key. The symbol may need to have modifier prefixes
2075 tacked onto it. */
2076 case non_ascii_keystroke:
2077 return modify_event_symbol (XFASTINT (event->code), event->modifiers,
2078 Qfunction_key,
2079 lispy_function_keys, &func_key_syms,
2080 (sizeof (lispy_function_keys)
2081 / sizeof (lispy_function_keys[0])));
2082 break;
2084 /* A mouse click. Figure out where it is, decide whether it's
2085 a press, click or drag, and build the appropriate structure. */
2086 case mouse_click:
2087 case scroll_bar_click:
2089 int button = XFASTINT (event->code);
2090 Lisp_Object position;
2091 Lisp_Object *start_pos_ptr;
2092 Lisp_Object start_pos;
2094 if (button < 0 || button >= NUM_MOUSE_BUTTONS)
2095 abort ();
2097 /* Build the position as appropriate for this mouse click. */
2098 if (event->kind == mouse_click)
2100 int part;
2101 FRAME_PTR f = XFRAME (event->frame_or_window);
2102 Lisp_Object window
2103 = window_from_coordinates (f, XINT (event->x), XINT (event->y),
2104 &part);
2105 Lisp_Object posn;
2107 if (XINT (event->y) < FRAME_MENU_BAR_LINES (f))
2109 int hpos;
2110 Lisp_Object items;
2111 items = FRAME_MENU_BAR_ITEMS (f);
2112 for (; CONSP (items); items = XCONS (items)->cdr)
2114 Lisp_Object pos, string;
2115 pos = Fcdr (Fcdr (Fcar (items)));
2116 string = Fcar (Fcdr (Fcar (items)));
2117 if (XINT (event->x) > XINT (pos)
2118 && XINT (event->x) <= XINT (pos) + XSTRING (string)->size)
2119 break;
2121 position
2122 = Fcons (event->frame_or_window,
2123 Fcons (Qmenu_bar,
2124 Fcons (Fcons (event->x, event->y),
2125 Fcons (make_number (event->timestamp),
2126 Qnil))));
2128 if (CONSP (items))
2129 return Fcons (Fcar (Fcar (items)),
2130 Fcons (position, Qnil));
2131 else
2132 return Fcons (Qnil, Fcons (position, Qnil));
2134 else if (XTYPE (window) != Lisp_Window)
2135 posn = Qnil;
2136 else
2138 XSETINT (event->x,
2139 (XINT (event->x) - XINT (XWINDOW (window)->left)));
2140 XSETINT (event->y,
2141 (XINT (event->y) - XINT (XWINDOW (window)->top)));
2143 if (part == 1)
2144 posn = Qmode_line;
2145 else if (part == 2)
2146 posn = Qvertical_line;
2147 else
2148 XSET (posn, Lisp_Int,
2149 buffer_posn_from_coords (XWINDOW (window),
2150 XINT (event->x),
2151 XINT (event->y)));
2154 position
2155 = Fcons (window,
2156 Fcons (posn,
2157 Fcons (Fcons (event->x, event->y),
2158 Fcons (make_number (event->timestamp),
2159 Qnil))));
2161 else
2163 Lisp_Object window = event->frame_or_window;
2164 Lisp_Object portion_whole = Fcons (event->x, event->y);
2165 Lisp_Object part = *scroll_bar_parts[(int) event->part];
2167 position =
2168 Fcons (window,
2169 Fcons (Qvertical_scroll_bar,
2170 Fcons (portion_whole,
2171 Fcons (make_number (event->timestamp),
2172 Fcons (part,
2173 Qnil)))));
2176 start_pos_ptr = &XVECTOR (button_down_location)->contents[button];
2178 start_pos = *start_pos_ptr;
2179 *start_pos_ptr = Qnil;
2181 /* If this is a button press, squirrel away the location, so
2182 we can decide later whether it was a click or a drag. */
2183 if (event->modifiers & down_modifier)
2184 *start_pos_ptr = Fcopy_alist (position);
2186 /* Now we're releasing a button - check the co-ordinates to
2187 see if this was a click or a drag. */
2188 else if (event->modifiers & up_modifier)
2190 /* If we did not see a down before this up,
2191 ignore the up. Probably this happened because
2192 the down event chose a menu item.
2193 It would be an annoyance to treat the release
2194 of the button that chose the menu item
2195 as a separate event. */
2197 if (XTYPE (start_pos) != Lisp_Cons)
2198 return Qnil;
2200 event->modifiers &= ~up_modifier;
2201 #if 0 /* Formerly we treated an up with no down as a click event. */
2202 if (XTYPE (start_pos) != Lisp_Cons)
2203 event->modifiers |= click_modifier;
2204 else
2205 #endif
2207 /* The third element of every position should be the (x,y)
2208 pair. */
2209 Lisp_Object down = Fnth (make_number (2), start_pos);
2211 event->modifiers |= ((EQ (event->x, XCONS (down)->car)
2212 && EQ (event->y, XCONS (down)->cdr))
2213 ? click_modifier
2214 : drag_modifier);
2217 else
2218 /* Every mouse event should either have the down_modifier or
2219 the up_modifier set. */
2220 abort ();
2223 /* Get the symbol we should use for the mouse click. */
2224 Lisp_Object head
2225 = modify_event_symbol (button,
2226 event->modifiers,
2227 Qmouse_click,
2228 lispy_mouse_names, &mouse_syms,
2229 (sizeof (lispy_mouse_names)
2230 / sizeof (lispy_mouse_names[0])));
2232 if (event->modifiers & drag_modifier)
2233 return Fcons (head,
2234 Fcons (start_pos,
2235 Fcons (position,
2236 Qnil)));
2237 else
2238 return Fcons (head,
2239 Fcons (position,
2240 Qnil));
2244 /* The 'kind' field of the event is something we don't recognize. */
2245 default:
2246 abort ();
2250 static Lisp_Object
2251 make_lispy_movement (frame, bar_window, part, x, y, time)
2252 FRAME_PTR frame;
2253 Lisp_Object bar_window;
2254 enum scroll_bar_part part;
2255 Lisp_Object x, y;
2256 unsigned long time;
2258 /* Is it a scroll bar movement? */
2259 if (frame && ! NILP (bar_window))
2261 Lisp_Object part_sym = *scroll_bar_parts[(int) part];
2263 return Fcons (Qscroll_bar_movement,
2264 (Fcons (Fcons (bar_window,
2265 Fcons (Qvertical_scroll_bar,
2266 Fcons (Fcons (x, y),
2267 Fcons (make_number (time),
2268 Fcons (part_sym,
2269 Qnil))))),
2270 Qnil)));
2273 /* Or is it an ordinary mouse movement? */
2274 else
2276 int area;
2277 Lisp_Object window =
2278 (frame
2279 ? window_from_coordinates (frame, XINT (x), XINT (y), &area)
2280 : Qnil);
2281 Lisp_Object posn;
2283 if (XTYPE (window) == Lisp_Window)
2285 XSETINT (x, XINT (x) - XINT (XWINDOW (window)->left));
2286 XSETINT (y, XINT (y) - XINT (XWINDOW (window)->top));
2288 if (area == 1)
2289 posn = Qmode_line;
2290 else if (area == 2)
2291 posn = Qvertical_line;
2292 else
2293 XSET (posn, Lisp_Int,
2294 buffer_posn_from_coords (XWINDOW (window),
2295 XINT (x), XINT (y)));
2297 else
2299 window = Qnil;
2300 posn = Qnil;
2303 return Fcons (Qmouse_movement,
2304 Fcons (Fcons (window,
2305 Fcons (posn,
2306 Fcons (Fcons (x, y),
2307 Fcons (make_number (time),
2308 Qnil)))),
2309 Qnil));
2313 /* Construct a switch frame event. */
2314 static Lisp_Object
2315 make_lispy_switch_frame (frame)
2316 Lisp_Object frame;
2318 return Fcons (Qswitch_frame, Fcons (frame, Qnil));
2321 /* Manipulating modifiers. */
2323 /* Parse the name of SYMBOL, and return the set of modifiers it contains.
2325 If MODIFIER_END is non-zero, set *MODIFIER_END to the position in
2326 SYMBOL's name of the end of the modifiers; the string from this
2327 position is the unmodified symbol name.
2329 This doesn't use any caches. */
2330 static int
2331 parse_modifiers_uncached (symbol, modifier_end)
2332 Lisp_Object symbol;
2333 int *modifier_end;
2335 struct Lisp_String *name;
2336 int i;
2337 int modifiers;
2339 CHECK_SYMBOL (symbol, 1);
2341 modifiers = 0;
2342 name = XSYMBOL (symbol)->name;
2345 for (i = 0; i+2 <= name->size; )
2346 switch (name->data[i])
2348 #define SINGLE_LETTER_MOD(bit) \
2349 if (name->data[i+1] != '-') \
2350 goto no_more_modifiers; \
2351 modifiers |= bit; \
2352 i += 2;
2354 case 'A':
2355 SINGLE_LETTER_MOD (alt_modifier);
2356 break;
2358 case 'C':
2359 SINGLE_LETTER_MOD (ctrl_modifier);
2360 break;
2362 case 'H':
2363 SINGLE_LETTER_MOD (hyper_modifier);
2364 break;
2366 case 'M':
2367 SINGLE_LETTER_MOD (meta_modifier);
2368 break;
2370 case 'S':
2371 SINGLE_LETTER_MOD (shift_modifier);
2372 break;
2374 case 's':
2375 SINGLE_LETTER_MOD (super_modifier);
2376 break;
2378 case 'd':
2379 if (i + 5 > name->size)
2380 goto no_more_modifiers;
2381 if (! strncmp (name->data + i, "drag-", 5))
2383 modifiers |= drag_modifier;
2384 i += 5;
2386 else if (! strncmp (name->data + i, "down-", 5))
2388 modifiers |= down_modifier;
2389 i += 5;
2391 else
2392 goto no_more_modifiers;
2393 break;
2395 default:
2396 goto no_more_modifiers;
2398 #undef SINGLE_LETTER_MOD
2400 no_more_modifiers:
2402 /* Should we include the `click' modifier? */
2403 if (! (modifiers & (down_modifier | drag_modifier))
2404 && i + 7 == name->size
2405 && strncmp (name->data + i, "mouse-", 6) == 0
2406 && ('0' <= name->data[i + 6] && name->data[i + 6] <= '9'))
2407 modifiers |= click_modifier;
2409 if (modifier_end)
2410 *modifier_end = i;
2412 return modifiers;
2416 /* Return a symbol whose name is the modifier prefixes for MODIFIERS
2417 prepended to the string BASE[0..BASE_LEN-1].
2418 This doesn't use any caches. */
2419 static Lisp_Object
2420 apply_modifiers_uncached (modifiers, base, base_len)
2421 int modifiers;
2422 char *base;
2423 int base_len;
2425 /* Since BASE could contain nulls, we can't use intern here; we have
2426 to use Fintern, which expects a genuine Lisp_String, and keeps a
2427 reference to it. */
2428 char *new_mods =
2429 (char *) alloca (sizeof ("A-C-H-M-S-s-down-drag-"));
2430 int mod_len;
2433 char *p = new_mods;
2435 /* Only the event queue may use the `up' modifier; it should always
2436 be turned into a click or drag event before presented to lisp code. */
2437 if (modifiers & up_modifier)
2438 abort ();
2440 if (modifiers & alt_modifier) { *p++ = 'A'; *p++ = '-'; }
2441 if (modifiers & ctrl_modifier) { *p++ = 'C'; *p++ = '-'; }
2442 if (modifiers & hyper_modifier) { *p++ = 'H'; *p++ = '-'; }
2443 if (modifiers & meta_modifier) { *p++ = 'M'; *p++ = '-'; }
2444 if (modifiers & shift_modifier) { *p++ = 'S'; *p++ = '-'; }
2445 if (modifiers & super_modifier) { *p++ = 's'; *p++ = '-'; }
2446 if (modifiers & down_modifier) { strcpy (p, "down-"); p += 5; }
2447 if (modifiers & drag_modifier) { strcpy (p, "drag-"); p += 5; }
2448 /* The click modifier is denoted by the absence of other modifiers. */
2450 *p = '\0';
2452 mod_len = p - new_mods;
2456 Lisp_Object new_name = make_uninit_string (mod_len + base_len);
2458 bcopy (new_mods, XSTRING (new_name)->data, mod_len);
2459 bcopy (base, XSTRING (new_name)->data + mod_len, base_len);
2461 return Fintern (new_name, Qnil);
2466 static char *modifier_names[] =
2468 "up", 0, 0, 0, 0, 0, 0, "down",
2469 "drag", "click", 0, 0, 0, 0, 0, 0,
2470 0, 0, "alt", "super", "hyper", "shift", "control", "meta"
2473 static Lisp_Object modifier_symbols;
2475 /* Return the list of modifier symbols corresponding to the mask MODIFIERS. */
2476 static Lisp_Object
2477 lispy_modifier_list (modifiers)
2478 int modifiers;
2480 Lisp_Object modifier_list;
2481 int i;
2483 modifier_list = Qnil;
2484 for (i = 0; (1<<i) <= modifiers; i++)
2485 if (modifiers & (1<<i))
2487 if (i >= XVECTOR (modifier_symbols)->size)
2488 abort ();
2489 modifier_list = Fcons (XVECTOR (modifier_symbols)->contents[i],
2490 modifier_list);
2493 return modifier_list;
2497 /* Parse the modifiers on SYMBOL, and return a list like (UNMODIFIED MASK),
2498 where UNMODIFIED is the unmodified form of SYMBOL,
2499 MASK is the set of modifiers present in SYMBOL's name.
2500 This is similar to parse_modifiers_uncached, but uses the cache in
2501 SYMBOL's Qevent_symbol_element_mask property, and maintains the
2502 Qevent_symbol_elements property. */
2503 static Lisp_Object
2504 parse_modifiers (symbol)
2505 Lisp_Object symbol;
2507 Lisp_Object elements = Fget (symbol, Qevent_symbol_element_mask);
2509 if (CONSP (elements))
2510 return elements;
2511 else
2513 int end;
2514 int modifiers = parse_modifiers_uncached (symbol, &end);
2515 Lisp_Object unmodified
2516 = Fintern (make_string (XSYMBOL (symbol)->name->data + end,
2517 XSYMBOL (symbol)->name->size - end),
2518 Qnil);
2519 Lisp_Object mask;
2521 if (modifiers & ~((1<<VALBITS) - 1))
2522 abort ();
2523 XFASTINT (mask) = modifiers;
2524 elements = Fcons (unmodified, Fcons (mask, Qnil));
2526 /* Cache the parsing results on SYMBOL. */
2527 Fput (symbol, Qevent_symbol_element_mask,
2528 elements);
2529 Fput (symbol, Qevent_symbol_elements,
2530 Fcons (unmodified, lispy_modifier_list (modifiers)));
2532 /* Since we know that SYMBOL is modifiers applied to unmodified,
2533 it would be nice to put that in unmodified's cache.
2534 But we can't, since we're not sure that parse_modifiers is
2535 canonical. */
2537 return elements;
2541 /* Apply the modifiers MODIFIERS to the symbol BASE.
2542 BASE must be unmodified.
2544 This is like apply_modifiers_uncached, but uses BASE's
2545 Qmodifier_cache property, if present. It also builds
2546 Qevent_symbol_elements properties, since it has that info anyway.
2548 apply_modifiers copies the value of BASE's Qevent_kind property to
2549 the modified symbol. */
2550 static Lisp_Object
2551 apply_modifiers (modifiers, base)
2552 int modifiers;
2553 Lisp_Object base;
2555 Lisp_Object cache, index, entry, new_symbol;
2557 /* The click modifier never figures into cache indices. */
2558 cache = Fget (base, Qmodifier_cache);
2559 if (modifiers & ~((1<<VALBITS) - 1))
2560 abort ();
2561 XFASTINT (index) = (modifiers & ~click_modifier);
2562 entry = Fassq (index, cache);
2564 if (CONSP (entry))
2565 new_symbol = XCONS (entry)->cdr;
2566 else
2568 /* We have to create the symbol ourselves. */
2569 new_symbol = apply_modifiers_uncached (modifiers,
2570 XSYMBOL (base)->name->data,
2571 XSYMBOL (base)->name->size);
2573 /* Add the new symbol to the base's cache. */
2574 entry = Fcons (index, new_symbol);
2575 Fput (base, Qmodifier_cache, Fcons (entry, cache));
2577 /* We have the parsing info now for free, so add it to the caches. */
2578 if (modifiers & ~((1<<VALBITS) - 1))
2579 abort ();
2580 XFASTINT (index) = modifiers;
2581 Fput (new_symbol, Qevent_symbol_element_mask,
2582 Fcons (base, Fcons (index, Qnil)));
2583 Fput (new_symbol, Qevent_symbol_elements,
2584 Fcons (base, lispy_modifier_list (modifiers)));
2587 /* Make sure this symbol is of the same kind as BASE.
2589 You'd think we could just set this once and for all when we
2590 intern the symbol above, but reorder_modifiers may call us when
2591 BASE's property isn't set right; we can't assume that just
2592 because we found something in the cache it must have its kind set
2593 right. */
2594 if (NILP (Fget (new_symbol, Qevent_kind)))
2596 Lisp_Object kind = Fget (base, Qevent_kind);
2598 if (! NILP (kind))
2599 Fput (new_symbol, Qevent_kind, kind);
2602 return new_symbol;
2606 /* Given a symbol whose name begins with modifiers ("C-", "M-", etc),
2607 return a symbol with the modifiers placed in the canonical order.
2608 Canonical order is alphabetical, except for down and drag, which
2609 always come last. The 'click' modifier is never written out.
2611 Fdefine_key calls this to make sure that (for example) C-M-foo
2612 and M-C-foo end up being equivalent in the keymap. */
2614 Lisp_Object
2615 reorder_modifiers (symbol)
2616 Lisp_Object symbol;
2618 /* It's hopefully okay to write the code this way, since everything
2619 will soon be in caches, and no consing will be done at all. */
2620 Lisp_Object parsed = parse_modifiers (symbol);
2622 return apply_modifiers (XCONS (XCONS (parsed)->cdr)->car,
2623 XCONS (parsed)->car);
2627 /* For handling events, we often want to produce a symbol whose name
2628 is a series of modifier key prefixes ("M-", "C-", etcetera) attached
2629 to some base, like the name of a function key or mouse button.
2630 modify_event_symbol produces symbols of this sort.
2632 NAME_TABLE should point to an array of strings, such that NAME_TABLE[i]
2633 is the name of the i'th symbol. TABLE_SIZE is the number of elements
2634 in the table.
2636 SYMBOL_TABLE should be a pointer to a Lisp_Object whose value will
2637 persist between calls to modify_event_symbol that it can use to
2638 store a cache of the symbols it's generated for this NAME_TABLE
2639 before.
2641 SYMBOL_NUM is the number of the base name we want from NAME_TABLE.
2643 MODIFIERS is a set of modifier bits (as given in struct input_events)
2644 whose prefixes should be applied to the symbol name.
2646 SYMBOL_KIND is the value to be placed in the event_kind property of
2647 the returned symbol.
2649 The symbols we create are supposed to have an
2650 `event-symbol-elements' propery, which lists the modifiers present
2651 in the symbol's name. */
2653 static Lisp_Object
2654 modify_event_symbol (symbol_num, modifiers, symbol_kind, name_table,
2655 symbol_table, table_size)
2656 int symbol_num;
2657 unsigned modifiers;
2658 Lisp_Object symbol_kind;
2659 char **name_table;
2660 Lisp_Object *symbol_table;
2661 int table_size;
2663 Lisp_Object *slot;
2665 /* Is this a request for a valid symbol? */
2666 if (symbol_num < 0 || symbol_num >= table_size)
2667 abort ();
2669 /* If *symbol_table doesn't seem to be initialized properly, fix that.
2670 *symbol_table should be a lisp vector TABLE_SIZE elements long,
2671 where the Nth element is the symbol for NAME_TABLE[N], or nil if
2672 we've never used that symbol before. */
2673 if (XTYPE (*symbol_table) != Lisp_Vector
2674 || XVECTOR (*symbol_table)->size != table_size)
2676 Lisp_Object size;
2678 XFASTINT (size) = table_size;
2679 *symbol_table = Fmake_vector (size, Qnil);
2682 slot = & XVECTOR (*symbol_table)->contents[symbol_num];
2684 /* Have we already used this symbol before? */
2685 if (NILP (*slot))
2687 /* No; let's create it. */
2688 *slot = intern (name_table[symbol_num]);
2690 /* Fill in the cache entries for this symbol; this also
2691 builds the Qevent_symbol_elements property, which the user
2692 cares about. */
2693 apply_modifiers (modifiers & click_modifier, *slot);
2694 Fput (*slot, Qevent_kind, symbol_kind);
2697 /* Apply modifiers to that symbol. */
2698 return apply_modifiers (modifiers, *slot);
2702 /* Store into *addr a value nonzero if terminal input chars are available.
2703 Serves the purpose of ioctl (0, FIONREAD, addr)
2704 but works even if FIONREAD does not exist.
2705 (In fact, this may actually read some input.) */
2707 static void
2708 get_input_pending (addr)
2709 int *addr;
2711 /* First of all, have we already counted some input? */
2712 *addr = !NILP (Vquit_flag) || readable_events ();
2714 /* If input is being read as it arrives, and we have none, there is none. */
2715 if (*addr > 0 || (interrupt_input && ! interrupts_deferred))
2716 return;
2718 /* Try to read some input and see how much we get. */
2719 gobble_input (0);
2720 *addr = !NILP (Vquit_flag) || readable_events ();
2723 /* Interface to read_avail_input, blocking SIGIO if necessary. */
2726 gobble_input (expected)
2727 int expected;
2729 #ifndef VMS
2730 #ifdef SIGIO
2731 if (interrupt_input)
2733 SIGMASKTYPE mask;
2734 mask = sigblockx (SIGIO);
2735 read_avail_input (expected);
2736 sigsetmask (mask);
2738 else
2739 #endif
2740 read_avail_input (expected);
2741 #endif
2744 #ifndef VMS
2746 /* Read any terminal input already buffered up by the system
2747 into the kbd_buffer, but do not wait.
2749 EXPECTED should be nonzero if the caller knows there is some input.
2751 Except on VMS, all input is read by this function.
2752 If interrupt_input is nonzero, this function MUST be called
2753 only when SIGIO is blocked.
2755 Returns the number of keyboard chars read, or -1 meaning
2756 this is a bad time to try to read input. */
2758 static int
2759 read_avail_input (expected)
2760 int expected;
2762 struct input_event buf[KBD_BUFFER_SIZE];
2763 register int i;
2764 int nread;
2766 if (read_socket_hook)
2767 /* No need for FIONREAD or fcntl; just say don't wait. */
2768 nread = (*read_socket_hook) (0, buf, KBD_BUFFER_SIZE, expected, expected);
2769 else
2771 unsigned char cbuf[KBD_BUFFER_SIZE];
2773 #ifdef FIONREAD
2774 /* Find out how much input is available. */
2775 if (ioctl (0, FIONREAD, &nread) < 0)
2776 /* Formerly simply reported no input, but that sometimes led to
2777 a failure of Emacs to terminate.
2778 SIGHUP seems appropriate if we can't reach the terminal. */
2779 /* ??? Is it really right to send the signal just to this process
2780 rather than to the whole process group?
2781 Perhaps on systems with FIONREAD Emacs is alone in its group. */
2782 kill (getpid (), SIGHUP);
2783 if (nread == 0)
2784 return 0;
2785 if (nread > sizeof cbuf)
2786 nread = sizeof cbuf;
2787 #else /* no FIONREAD */
2788 #ifdef USG
2789 /* Read some input if available, but don't wait. */
2790 nread = sizeof cbuf;
2791 fcntl (fileno (stdin), F_SETFL, O_NDELAY);
2792 #else
2793 you lose;
2794 #endif
2795 #endif
2797 /* Now read; for one reason or another, this will not block. */
2798 while (1)
2800 nread = read (fileno (stdin), cbuf, nread);
2801 #ifdef AIX
2802 /* The kernel sometimes fails to deliver SIGHUP for ptys.
2803 This looks incorrect, but it isn't, because _BSD causes
2804 O_NDELAY to be defined in fcntl.h as O_NONBLOCK,
2805 and that causes a value other than 0 when there is no input. */
2806 if (nread == 0)
2807 kill (SIGHUP, 0);
2808 #endif
2809 /* Retry the read if it is interrupted. */
2810 if (nread >= 0
2811 || ! (errno == EAGAIN || errno == EFAULT
2812 #ifdef EBADSLT
2813 || errno == EBADSLT
2814 #endif
2816 break;
2819 #ifndef FIONREAD
2820 #ifdef USG
2821 fcntl (fileno (stdin), F_SETFL, 0);
2822 #endif /* USG */
2823 #endif /* no FIONREAD */
2824 for (i = 0; i < nread; i++)
2826 buf[i].kind = ascii_keystroke;
2827 buf[i].modifiers = 0;
2828 if (meta_key && (cbuf[i] & 0x80))
2829 buf[i].modifiers = meta_modifier;
2830 cbuf[i] &= ~0x80;
2832 XSET (buf[i].code, Lisp_Int, cbuf[i]);
2833 #ifdef MULTI_FRAME
2834 XSET (buf[i].frame_or_window, Lisp_Frame, selected_frame);
2835 #else
2836 buf[i].frame_or_window = Qnil;
2837 #endif
2841 /* Scan the chars for C-g and store them in kbd_buffer. */
2842 for (i = 0; i < nread; i++)
2844 kbd_buffer_store_event (&buf[i]);
2845 /* Don't look at input that follows a C-g too closely.
2846 This reduces lossage due to autorepeat on C-g. */
2847 if (buf[i].kind == ascii_keystroke
2848 && XINT(buf[i].code) == quit_char)
2849 break;
2852 return nread;
2854 #endif /* not VMS */
2856 #ifdef SIGIO /* for entire page */
2857 /* Note SIGIO has been undef'd if FIONREAD is missing. */
2859 SIGTYPE
2860 input_available_signal (signo)
2861 int signo;
2863 /* Must preserve main program's value of errno. */
2864 int old_errno = errno;
2865 #ifdef BSD4_1
2866 extern int select_alarmed;
2867 #endif
2869 #ifdef USG
2870 /* USG systems forget handlers when they are used;
2871 must reestablish each time */
2872 signal (signo, input_available_signal);
2873 #endif /* USG */
2875 #ifdef BSD4_1
2876 sigisheld (SIGIO);
2877 #endif
2879 if (input_available_clear_time)
2880 EMACS_SET_SECS_USECS (*input_available_clear_time, 0, 0);
2882 while (1)
2884 int nread;
2885 nread = read_avail_input (1);
2886 /* -1 means it's not ok to read the input now.
2887 UNBLOCK_INPUT will read it later; now, avoid infinite loop.
2888 0 means there was no keyboard input available. */
2889 if (nread <= 0)
2890 break;
2892 #ifdef BSD4_1
2893 select_alarmed = 1; /* Force the select emulator back to life */
2894 #endif
2897 #ifdef BSD4_1
2898 sigfree ();
2899 #endif
2900 errno = old_errno;
2902 #endif /* SIGIO */
2904 /* Return the prompt-string of a sparse keymap.
2905 This is the first element which is a string.
2906 Return nil if there is none. */
2908 Lisp_Object
2909 map_prompt (map)
2910 Lisp_Object map;
2912 while (CONSP (map))
2914 register Lisp_Object tem;
2915 tem = Fcar (map);
2916 if (XTYPE (tem) == Lisp_String)
2917 return tem;
2918 map = Fcdr (map);
2920 return Qnil;
2923 static Lisp_Object menu_bar_item ();
2924 static Lisp_Object menu_bar_one_keymap ();
2926 /* Return a list of menu items for a menu bar, appropriate
2927 to the current buffer.
2928 The elements have the form (KEY STRING . nil). */
2930 Lisp_Object
2931 menu_bar_items ()
2933 /* The number of keymaps we're scanning right now, and the number of
2934 keymaps we have allocated space for. */
2935 int nmaps;
2937 /* maps[0..nmaps-1] are the prefix definitions of KEYBUF[0..t-1]
2938 in the current keymaps, or nil where it is not a prefix. */
2939 Lisp_Object *maps;
2941 Lisp_Object def, tem;
2943 Lisp_Object result;
2945 int mapno;
2947 /* Build our list of keymaps.
2948 If we recognize a function key and replace its escape sequence in
2949 keybuf with its symbol, or if the sequence starts with a mouse
2950 click and we need to switch buffers, we jump back here to rebuild
2951 the initial keymaps from the current buffer. */
2953 Lisp_Object *tmaps;
2955 nmaps = current_minor_maps (0, &tmaps) + 2;
2956 maps = (Lisp_Object *) alloca (nmaps * sizeof (maps[0]));
2957 bcopy (tmaps, maps, (nmaps - 2) * sizeof (maps[0]));
2958 #ifdef USE_TEXT_PROPERTIES
2959 maps[nmaps-2] = get_local_map (PT, current_buffer);
2960 #else
2961 maps[nmaps-2] = current_buffer->local_map;
2962 #endif
2963 maps[nmaps-1] = global_map;
2966 /* Look up in each map the dummy prefix key `menu-bar'. */
2968 result = Qnil;
2970 for (mapno = 0; mapno < nmaps; mapno++)
2972 if (! NILP (maps[mapno]))
2973 def = get_keyelt (access_keymap (maps[mapno], Qmenu_bar, 1));
2974 else
2975 def = Qnil;
2977 tem = Fkeymapp (def);
2978 if (!NILP (tem))
2979 result = menu_bar_one_keymap (def, result);
2982 return Fnreverse (result);
2985 /* Scan one map KEYMAP, accumulating any menu items it defines
2986 that have not yet been seen in RESULT. Return the updated RESULT. */
2988 static Lisp_Object
2989 menu_bar_one_keymap (keymap, result)
2990 Lisp_Object keymap, result;
2992 Lisp_Object tail, item, key, binding, item_string, table;
2994 /* Loop over all keymap entries that have menu strings. */
2995 for (tail = keymap; XTYPE (tail) == Lisp_Cons; tail = XCONS (tail)->cdr)
2997 item = XCONS (tail)->car;
2998 if (XTYPE (item) == Lisp_Cons)
3000 key = XCONS (item)->car;
3001 binding = XCONS (item)->cdr;
3002 if (XTYPE (binding) == Lisp_Cons)
3004 item_string = XCONS (binding)->car;
3005 if (XTYPE (item_string) == Lisp_String)
3006 result = menu_bar_item (key, item_string,
3007 Fcdr (binding), result);
3010 else if (XTYPE (item) == Lisp_Vector)
3012 /* Loop over the char values represented in the vector. */
3013 int len = XVECTOR (item)->size;
3014 int c;
3015 for (c = 0; c < len; c++)
3017 Lisp_Object character;
3018 XFASTINT (character) = c;
3019 binding = XVECTOR (item)->contents[c];
3020 if (XTYPE (binding) == Lisp_Cons)
3022 item_string = XCONS (binding)->car;
3023 if (XTYPE (item_string) == Lisp_String)
3024 result = menu_bar_item (key, item_string,
3025 Fcdr (binding), result);
3031 return result;
3034 static Lisp_Object
3035 menu_bar_item (key, item_string, def, result)
3036 Lisp_Object key, item_string, def, result;
3038 Lisp_Object tem, elt;
3039 Lisp_Object enabled;
3041 /* See if this entry is enabled. */
3042 enabled = Qt;
3044 if (XTYPE (def) == Lisp_Symbol)
3046 /* No property, or nil, means enable.
3047 Otherwise, enable if value is not nil. */
3048 tem = Fget (def, Qmenu_enable);
3049 if (!NILP (tem))
3050 enabled = Feval (tem);
3053 /* Add an entry for this key and string
3054 if there is none yet. */
3055 elt = Fassq (key, result);
3056 if (!NILP (enabled) && NILP (elt))
3057 result = Fcons (Fcons (key, Fcons (item_string, Qnil)), result);
3059 return result;
3062 static int echo_flag;
3063 static int echo_now;
3065 /* Read a character like read_char but optionally prompt based on maps
3066 in the array MAPS. NMAPS is the length of MAPS. Return nil if we
3067 decided not to read a character, because there are no menu items in
3068 MAPS.
3070 PREV_EVENT is the previous input event, or nil if we are reading
3071 the first event of a key sequence.
3073 If USED_MOUSE_MENU is non-zero, then we set *USED_MOUSE_MENU to 1
3074 if we used a mouse menu to read the input, or zero otherwise. If
3075 USED_MOUSE_MENU is zero, *USED_MOUSE_MENU is left alone.
3077 The prompting is done based on the prompt-string of the map
3078 and the strings associated with various map elements. */
3080 Lisp_Object
3081 read_char_menu_prompt (nmaps, maps, prev_event, used_mouse_menu)
3082 int nmaps;
3083 Lisp_Object *maps;
3084 Lisp_Object prev_event;
3085 int *used_mouse_menu;
3087 int mapno;
3088 register Lisp_Object name;
3089 int nlength;
3090 int width = FRAME_WIDTH (selected_frame) - 4;
3091 char *menu = (char *) alloca (width + 4);
3092 int idx = -1;
3093 Lisp_Object rest, vector;
3095 if (used_mouse_menu)
3096 *used_mouse_menu = 0;
3098 /* Use local over global Menu maps */
3100 if (! menu_prompting)
3101 return Qnil;
3103 /* Get the menu name from the first map that has one (a prompt string). */
3104 for (mapno = 0; mapno < nmaps; mapno++)
3106 name = map_prompt (maps[mapno]);
3107 if (!NILP (name))
3108 break;
3111 /* If we don't have any menus, just read a character normally. */
3112 if (mapno >= nmaps)
3113 return Qnil;
3115 #ifdef HAVE_X_WINDOWS
3116 #ifdef HAVE_X_MENU
3117 /* If we got to this point via a mouse click,
3118 use a real menu for mouse selection. */
3119 if (EVENT_HAS_PARAMETERS (prev_event))
3121 /* Display the menu and get the selection. */
3122 Lisp_Object *realmaps
3123 = (Lisp_Object *) alloca (nmaps * sizeof (Lisp_Object));
3124 Lisp_Object value;
3125 int nmaps1 = 0;
3127 /* Use the maps that are not nil. */
3128 for (mapno = 0; mapno < nmaps; mapno++)
3129 if (!NILP (maps[mapno]))
3130 realmaps[nmaps1++] = maps[mapno];
3132 value = Fx_popup_menu (prev_event, Flist (nmaps1, realmaps));
3133 if (NILP (value))
3134 XSET (value, Lisp_Int, quit_char);
3135 if (used_mouse_menu)
3136 *used_mouse_menu = 1;
3137 return value;
3139 #endif /* HAVE_X_MENU */
3140 #endif /* HAVE_X_WINDOWS */
3142 /* Prompt string always starts with map's prompt, and a space. */
3143 strcpy (menu, XSTRING (name)->data);
3144 nlength = XSTRING (name)->size;
3145 menu[nlength++] = ':';
3146 menu[nlength++] = ' ';
3147 menu[nlength] = 0;
3149 /* Start prompting at start of first map. */
3150 mapno = 0;
3151 rest = maps[mapno];
3153 /* Present the documented bindings, a line at a time. */
3154 while (1)
3156 int notfirst = 0;
3157 int i = nlength;
3158 Lisp_Object obj;
3159 int ch;
3161 /* Loop over elements of map. */
3162 while (i < width)
3164 Lisp_Object s, elt;
3166 /* If reached end of map, start at beginning of next map. */
3167 if (NILP (rest))
3169 mapno++;
3170 /* At end of last map, wrap around to first map if just starting,
3171 or end this line if already have something on it. */
3172 if (mapno == nmaps)
3174 if (notfirst)
3175 break;
3176 else
3177 mapno = 0;
3179 rest = maps[mapno];
3182 /* Look at the next element of the map. */
3183 if (idx >= 0)
3184 elt = XVECTOR (vector)->contents[idx];
3185 else
3186 elt = Fcar_safe (rest);
3188 if (idx < 0 && XTYPE (elt) == Lisp_Vector)
3190 /* If we found a dense table in the keymap,
3191 advanced past it, but start scanning its contents. */
3192 rest = Fcdr_safe (rest);
3193 vector = elt;
3194 idx = 0;
3196 else
3198 /* An ordinary element. */
3199 s = Fcar_safe (Fcdr_safe (elt));
3200 if (XTYPE (s) != Lisp_String)
3201 /* Ignore the element if it has no prompt string. */
3203 /* If we have room for the prompt string, add it to this line.
3204 If this is the first on the line, always add it. */
3205 else if (XSTRING (s)->size + i < width
3206 || !notfirst)
3208 int thiswidth;
3210 /* Punctuate between strings. */
3211 if (notfirst)
3213 strcpy (menu + i, ", ");
3214 i += 2;
3216 notfirst = 1;
3218 /* Add as much of string as fits. */
3219 thiswidth = XSTRING (s)->size;
3220 if (thiswidth + i > width)
3221 thiswidth = width - i;
3222 bcopy (XSTRING (s)->data, menu + i, thiswidth);
3223 i += thiswidth;
3225 else
3227 /* If this element does not fit, end the line now,
3228 and save the element for the next line. */
3229 strcpy (menu + i, "...");
3230 break;
3233 /* Move past this element. */
3234 if (idx >= 0 && idx + 1 >= XVECTOR (rest)->size)
3235 /* Handle reaching end of dense table. */
3236 idx = -1;
3237 if (idx >= 0)
3238 idx++;
3239 else
3240 rest = Fcdr_safe (rest);
3244 /* Prompt with that and read response. */
3245 message1 (menu);
3246 obj = read_char (1, 0, 0, Qnil, 0);
3248 if (XTYPE (obj) != Lisp_Int)
3249 return obj;
3250 else
3251 ch = XINT (obj);
3253 if (! EQ (obj, menu_prompt_more_char)
3254 && (XTYPE (menu_prompt_more_char) != Lisp_Int
3255 || ! EQ (obj, make_number (Ctl (XINT (menu_prompt_more_char))))))
3256 return obj;
3260 /* Reading key sequences. */
3262 /* Follow KEY in the maps in CURRENT[0..NMAPS-1], placing its bindings
3263 in DEFS[0..NMAPS-1]. Set NEXT[i] to DEFS[i] if DEFS[i] is a
3264 keymap, or nil otherwise. Return the index of the first keymap in
3265 which KEY has any binding, or NMAPS if no map has a binding.
3267 If KEY is a meta ASCII character, treat it like meta-prefix-char
3268 followed by the corresponding non-meta character. Keymaps in
3269 CURRENT with non-prefix bindings for meta-prefix-char become nil in
3270 NEXT.
3272 When KEY is not defined in any of the keymaps, if it is an upper
3273 case letter and there are bindings for the corresponding lower-case
3274 letter, return the bindings for the lower-case letter.
3276 If KEY has no bindings in any of the CURRENT maps, NEXT is left
3277 unmodified.
3279 NEXT may == CURRENT. */
3281 static int
3282 follow_key (key, nmaps, current, defs, next)
3283 Lisp_Object key;
3284 Lisp_Object *current, *defs, *next;
3285 int nmaps;
3287 int i, first_binding;
3289 /* If KEY is a meta ASCII character, treat it like meta-prefix-char
3290 followed by the corresponding non-meta character. */
3291 if (XTYPE (key) == Lisp_Int && (XINT (key) & CHAR_META))
3293 for (i = 0; i < nmaps; i++)
3294 if (! NILP (current[i]))
3296 next[i] =
3297 get_keyelt (access_keymap (current[i], meta_prefix_char, 1));
3299 /* Note that since we pass the resulting bindings through
3300 get_keymap_1, non-prefix bindings for meta-prefix-char
3301 disappear. */
3302 next[i] = get_keymap_1 (next[i], 0, 1);
3304 else
3305 next[i] = Qnil;
3307 current = next;
3308 XSET (key, Lisp_Int, XFASTINT (key) & ~CHAR_META);
3311 first_binding = nmaps;
3312 for (i = nmaps - 1; i >= 0; i--)
3314 if (! NILP (current[i]))
3316 defs[i] = get_keyelt (access_keymap (current[i], key, 1));
3317 if (! NILP (defs[i]))
3318 first_binding = i;
3320 else
3321 defs[i] = Qnil;
3324 /* When KEY is not defined in any of the keymaps, if it is an upper
3325 case letter and there are bindings for the corresponding
3326 lower-case letter, return the bindings for the lower-case letter. */
3327 if (first_binding == nmaps
3328 && XTYPE (key) == Lisp_Int
3329 && (UPPERCASEP (XINT (key) & 0x3ffff)
3330 || (XINT (key) & shift_modifier)))
3332 if (XINT (key) & shift_modifier)
3333 XSETINT (key, XINT (key) & ~shift_modifier);
3334 else
3335 XSETINT (key, DOWNCASE (XINT (key)));
3337 first_binding = nmaps;
3338 for (i = nmaps - 1; i >= 0; i--)
3340 if (! NILP (current[i]))
3342 defs[i] = get_keyelt (access_keymap (current[i], key, 1));
3343 if (! NILP (defs[i]))
3344 first_binding = i;
3346 else
3347 defs[i] = Qnil;
3351 /* Given the set of bindings we've found, produce the next set of maps. */
3352 if (first_binding < nmaps)
3353 for (i = 0; i < nmaps; i++)
3354 next[i] = NILP (defs[i]) ? Qnil : get_keymap_1 (defs[i], 0, 1);
3356 return first_binding;
3359 /* Read a sequence of keys that ends with a non prefix character,
3360 storing it in KEYBUF, a buffer of size BUFSIZE.
3361 Prompt with PROMPT.
3362 Return the length of the key sequence stored.
3364 Echo starting immediately unless `prompt' is 0.
3366 Where a key sequence ends depends on the currently active keymaps.
3367 These include any minor mode keymaps active in the current buffer,
3368 the current buffer's local map, and the global map.
3370 If a key sequence has no other bindings, we check Vfunction_key_map
3371 to see if some trailing subsequence might be the beginning of a
3372 function key's sequence. If so, we try to read the whole function
3373 key, and substitute its symbolic name into the key sequence.
3375 We ignore unbound `down-' mouse clicks. We turn unbound `drag-'
3376 events into similar click events, if that would make them bound.
3378 If we get a mouse click in a mode line, vertical divider, or other
3379 non-text area, we treat the click as if it were prefixed by the
3380 symbol denoting that area - `mode-line', `vertical-line', or
3381 whatever.
3383 If the sequence starts with a mouse click, we read the key sequence
3384 with respect to the buffer clicked on, not the current buffer.
3386 If the user switches frames in the midst of a key sequence, we put
3387 off the switch-frame event until later; the next call to
3388 read_char will return it. */
3390 static int
3391 read_key_sequence (keybuf, bufsize, prompt)
3392 Lisp_Object *keybuf;
3393 int bufsize;
3394 char *prompt;
3396 int count = specpdl_ptr - specpdl;
3398 /* How many keys there are in the current key sequence. */
3399 int t;
3401 /* The length of the echo buffer when we started reading, and
3402 the length of this_command_keys when we started reading. */
3403 int echo_start;
3404 int keys_start;
3406 /* The number of keymaps we're scanning right now, and the number of
3407 keymaps we have allocated space for. */
3408 int nmaps;
3409 int nmaps_allocated = 0;
3411 /* defs[0..nmaps-1] are the definitions of KEYBUF[0..t-1] in
3412 the current keymaps. */
3413 Lisp_Object *defs;
3415 /* submaps[0..nmaps-1] are the prefix definitions of KEYBUF[0..t-1]
3416 in the current keymaps, or nil where it is not a prefix. */
3417 Lisp_Object *submaps;
3419 /* The index in defs[] of the first keymap that has a binding for
3420 this key sequence. In other words, the lowest i such that
3421 defs[i] is non-nil. */
3422 int first_binding;
3424 /* If t < mock_input, then KEYBUF[t] should be read as the next
3425 input key.
3427 We use this to recover after recognizing a function key. Once we
3428 realize that a suffix of the current key sequence is actually a
3429 function key's escape sequence, we replace the suffix with the
3430 function key's binding from Vfunction_key_map. Now keybuf
3431 contains a new and different key sequence, so the echo area,
3432 this_command_keys, and the submaps and defs arrays are wrong. In
3433 this situation, we set mock_input to t, set t to 0, and jump to
3434 restart_sequence; the loop will read keys from keybuf up until
3435 mock_input, thus rebuilding the state; and then it will resume
3436 reading characters from the keyboard. */
3437 int mock_input = 0;
3439 /* If the sequence is unbound in submaps[], then
3440 keybuf[fkey_start..fkey_end-1] is a prefix in Vfunction_key_map,
3441 and fkey_map is its binding.
3443 These might be > t, indicating that all function key scanning
3444 should hold off until t reaches them. We do this when we've just
3445 recognized a function key, to avoid searching for the function
3446 key's again in Vfunction_key_map. */
3447 int fkey_start = 0, fkey_end = 0;
3448 Lisp_Object fkey_map = Vfunction_key_map;
3450 /* If we receive a ``switch-frame'' event in the middle of a key sequence,
3451 we put it off for later. While we're reading, we keep the event here. */
3452 Lisp_Object delayed_switch_frame = Qnil;
3455 /* If there is no function key map, turn off function key scanning. */
3456 if (NILP (Fkeymapp (Vfunction_key_map)))
3457 fkey_start = fkey_end = bufsize + 1;
3459 /* We need to save the current buffer in case we switch buffers to
3460 find the right binding for a mouse click. Note that we can't use
3461 save_excursion_{save,restore} here, because they save point as
3462 well as the current buffer; we don't want to save point, because
3463 redisplay may change it, to accomodate a Fset_window_start or
3464 something. */
3465 record_unwind_protect (Fset_buffer, Fcurrent_buffer ());
3467 last_nonmenu_event = Qnil;
3469 if (INTERACTIVE)
3471 if (prompt)
3472 echo_prompt (prompt);
3473 else if (cursor_in_echo_area)
3474 /* This doesn't put in a dash if the echo buffer is empty, so
3475 you don't always see a dash hanging out in the minibuffer. */
3476 echo_dash ();
3479 /* Record the initial state of the echo area and this_command_keys;
3480 we will need to restore them if we replay a key sequence. */
3481 if (INTERACTIVE)
3482 echo_start = echo_length ();
3483 keys_start = this_command_key_count;
3485 /* We jump here when the key sequence has been thoroughly changed, and
3486 we need to rescan it starting from the beginning. When we jump here,
3487 keybuf[0..mock_input] holds the sequence we should reread. */
3488 replay_sequence:
3490 /* Build our list of keymaps.
3491 If we recognize a function key and replace its escape sequence in
3492 keybuf with its symbol, or if the sequence starts with a mouse
3493 click and we need to switch buffers, we jump back here to rebuild
3494 the initial keymaps from the current buffer. */
3496 Lisp_Object *maps;
3498 nmaps = current_minor_maps (0, &maps) + 2;
3499 if (nmaps > nmaps_allocated)
3501 submaps = (Lisp_Object *) alloca (nmaps * sizeof (submaps[0]));
3502 defs = (Lisp_Object *) alloca (nmaps * sizeof (defs[0]));
3503 nmaps_allocated = nmaps;
3505 bcopy (maps, submaps, (nmaps - 2) * sizeof (submaps[0]));
3506 #ifdef USE_TEXT_PROPERTIES
3507 submaps[nmaps-2] = get_local_map (PT, current_buffer);
3508 #else
3509 submaps[nmaps-2] = current_buffer->local_map;
3510 #endif
3511 submaps[nmaps-1] = global_map;
3514 /* Find an accurate initial value for first_binding. */
3515 for (first_binding = 0; first_binding < nmaps; first_binding++)
3516 if (! NILP (submaps[first_binding]))
3517 break;
3519 /* We jump here when a function key substitution has forced us to
3520 reprocess the current key sequence. keybuf[0..mock_input] is the
3521 sequence we want to reread. */
3522 t = 0;
3524 /* These are no-ops the first time through, but if we restart, they
3525 revert the echo area and this_command_keys to their original state. */
3526 this_command_key_count = keys_start;
3527 if (INTERACTIVE)
3528 echo_truncate (echo_start);
3530 /* If the best binding for the current key sequence is a keymap,
3531 or we may be looking at a function key's escape sequence, keep
3532 on reading. */
3533 while ((first_binding < nmaps && ! NILP (submaps[first_binding]))
3534 || (first_binding >= nmaps && fkey_start < t))
3536 Lisp_Object key;
3537 int used_mouse_menu = 0;
3539 /* Where the last real key started. If we need to throw away a
3540 key that has expanded into more than one element of keybuf
3541 (say, a mouse click on the mode line which is being treated
3542 as [mode-line (mouse-...)], then we backtrack to this point
3543 of keybuf. */
3544 int last_real_key_start;
3546 /* These variables are analogous to echo_start and keys_start;
3547 while those allow us to restart the entire key sequence,
3548 echo_local_start and keys_local_start allow us to throw away
3549 just one key. */
3550 int echo_local_start, keys_local_start, local_first_binding;
3552 if (t >= bufsize)
3553 error ("key sequence too long");
3555 if (INTERACTIVE)
3556 echo_local_start = echo_length ();
3557 keys_local_start = this_command_key_count;
3558 local_first_binding = first_binding;
3560 replay_key:
3561 /* These are no-ops, unless we throw away a keystroke below and
3562 jumped back up to replay_key; in that case, these restore the
3563 variables to their original state, allowing us to replay the
3564 loop. */
3565 if (INTERACTIVE)
3566 echo_truncate (echo_local_start);
3567 this_command_key_count = keys_local_start;
3568 first_binding = local_first_binding;
3570 /* Does mock_input indicate that we are re-reading a key sequence? */
3571 if (t < mock_input)
3573 key = keybuf[t];
3574 add_command_key (key);
3575 echo_char (key);
3578 /* If not, we should actually read a character. */
3579 else
3581 last_real_key_start = t;
3583 key = read_char (!prompt, nmaps, submaps, last_nonmenu_event,
3584 &used_mouse_menu);
3586 /* read_char returns -1 at the end of a macro.
3587 Emacs 18 handles this by returning immediately with a
3588 zero, so that's what we'll do. */
3589 if (XTYPE (key) == Lisp_Int && XINT (key) == -1)
3591 t = 0;
3592 goto done;
3595 Vquit_flag = Qnil;
3597 /* Clicks in non-text areas get prefixed by the symbol
3598 in their CHAR-ADDRESS field. For example, a click on
3599 the mode line is prefixed by the symbol `mode-line'.
3601 Furthermore, key sequences beginning with mouse clicks
3602 are read using the keymaps of the buffer clicked on, not
3603 the current buffer. So we may have to switch the buffer
3604 here. */
3605 if (EVENT_HAS_PARAMETERS (key))
3607 Lisp_Object kind = EVENT_HEAD_KIND (EVENT_HEAD (key));
3609 if (EQ (kind, Qmouse_click))
3611 Lisp_Object window = POSN_WINDOW (EVENT_START (key));
3612 Lisp_Object posn = POSN_BUFFER_POSN (EVENT_START (key));
3614 /* Key sequences beginning with mouse clicks are
3615 read using the keymaps in the buffer clicked on,
3616 not the current buffer. If we're at the
3617 beginning of a key sequence, switch buffers. */
3618 if (t == 0
3619 && XTYPE (window) == Lisp_Window
3620 && XTYPE (XWINDOW (window)->buffer) == Lisp_Buffer
3621 && XBUFFER (XWINDOW (window)->buffer) != current_buffer)
3623 if (XTYPE (posn) == Lisp_Symbol)
3625 if (t + 1 >= bufsize)
3626 error ("key sequence too long");
3627 keybuf[t] = posn;
3628 keybuf[t+1] = key;
3629 mock_input = t + 2;
3631 else
3633 keybuf[t] = key;
3634 mock_input = t + 1;
3637 set_buffer_internal (XBUFFER (XWINDOW (window)->buffer));
3638 goto replay_sequence;
3640 else if (XTYPE (posn) == Lisp_Symbol)
3642 if (t + 1 >= bufsize)
3643 error ("key sequence too long");
3644 keybuf[t] = posn;
3645 keybuf[t+1] = key;
3646 mock_input = t + 2;
3648 goto replay_key;
3651 else if (EQ (kind, Qswitch_frame))
3653 /* If we're at the beginning of a key sequence, go
3654 ahead and return this event. If we're in the
3655 midst of a key sequence, delay it until the end. */
3656 if (t > 0)
3658 delayed_switch_frame = key;
3659 goto replay_key;
3662 else
3664 Lisp_Object posn = POSN_BUFFER_POSN (EVENT_START (key));
3666 /* Handle menu-bar events:
3667 insert the dummy prefix char `menu-bar'. */
3668 if (EQ (posn, Qmenu_bar))
3670 if (t + 1 >= bufsize)
3671 error ("key sequence too long");
3672 /* Run the Lucid hook. */
3673 call1 (Vrun_hooks, Qactivate_menubar_hook);
3674 /* If it has changed current-menubar from previous value,
3675 really recompute the menubar from the value. */
3676 if (! NILP (Vlucid_menu_bar_dirty_flag))
3677 call0 (Qrecompute_lucid_menubar);
3678 keybuf[t] = posn;
3679 keybuf[t+1] = key;
3680 mock_input = t + 2;
3681 goto replay_sequence;
3687 /* We have finally decided that KEY is something we might want
3688 to look up. */
3689 first_binding = (follow_key (key,
3690 nmaps - first_binding,
3691 submaps + first_binding,
3692 defs + first_binding,
3693 submaps + first_binding)
3694 + first_binding);
3696 /* If KEY wasn't bound, we'll try some fallbacks. */
3697 if (first_binding >= nmaps)
3699 Lisp_Object head = EVENT_HEAD (key);
3701 if (XTYPE (head) == Lisp_Symbol)
3703 Lisp_Object breakdown = parse_modifiers (head);
3704 Lisp_Object modifiers =
3705 XINT (XCONS (XCONS (breakdown)->cdr)->car);
3707 /* We drop unbound `down-' events altogether. */
3708 if (modifiers & down_modifier)
3710 /* Dispose of this event by simply jumping back to
3711 replay_key, to get another event.
3713 Note that if this event came from mock input,
3714 then just jumping back to replay_key will just
3715 hand it to us again. So we have to wipe out any
3716 mock input.
3718 We could delete keybuf[t] and shift everything
3719 after that to the left by one spot, but we'd also
3720 have to fix up any variable that points into
3721 keybuf, and shifting isn't really necessary
3722 anyway.
3724 Adding prefixes for non-textual mouse clicks
3725 creates two characters of mock input, and both
3726 must be thrown away. If we're only looking at
3727 the prefix now, we can just jump back to
3728 replay_key. On the other hand, if we've already
3729 processed the prefix, and now the actual click
3730 itself is giving us trouble, then we've lost the
3731 state of the keymaps we want to backtrack to, and
3732 we need to replay the whole sequence to rebuild
3735 Beyond that, only function key expansion could
3736 create more than two keys, but that should never
3737 generate mouse events, so it's okay to zero
3738 mock_input in that case too.
3740 Isn't this just the most wonderful code ever? */
3741 if (t == last_real_key_start)
3743 mock_input = 0;
3744 goto replay_key;
3746 else
3748 mock_input = last_real_key_start;
3749 goto replay_sequence;
3753 /* We turn unbound `drag-' events into `click-'
3754 events, if the click would be bound. */
3755 else if (modifiers & drag_modifier)
3757 Lisp_Object new_head =
3758 apply_modifiers (modifiers & ~drag_modifier,
3759 XCONS (breakdown)->car);
3760 Lisp_Object new_click =
3761 Fcons (new_head, Fcons (EVENT_START (key), Qnil));
3763 /* Look for a binding for this new key. follow_key
3764 promises that it didn't munge submaps the
3765 last time we called it, since key was unbound. */
3766 first_binding =
3767 (follow_key (new_click,
3768 nmaps - local_first_binding,
3769 submaps + local_first_binding,
3770 defs + local_first_binding,
3771 submaps + local_first_binding)
3772 + local_first_binding);
3774 /* If that click is bound, go for it. */
3775 if (first_binding < nmaps)
3776 key = new_click;
3777 /* Otherwise, we'll leave key set to the drag event. */
3782 keybuf[t++] = key;
3783 /* Normally, last_nonmenu_event gets the previous key we read.
3784 But when a mouse popup menu is being used,
3785 we don't update last_nonmenu_event; it continues to hold the mouse
3786 event that preceded the first level of menu. */
3787 if (!used_mouse_menu)
3788 last_nonmenu_event = key;
3790 /* If the sequence is unbound, see if we can hang a function key
3791 off the end of it. We only want to scan real keyboard input
3792 for function key sequences, so if mock_input says that we're
3793 re-reading old events, don't examine it. */
3794 if (first_binding >= nmaps
3795 && t >= mock_input)
3797 Lisp_Object fkey_next;
3799 /* Scan from fkey_end until we find a bound suffix. */
3800 while (fkey_end < t)
3802 Lisp_Object key;
3804 key = keybuf[fkey_end++];
3805 /* Look up meta-characters by prefixing them
3806 with meta_prefix_char. I hate this. */
3807 if (XTYPE (key) == Lisp_Int && XINT (key) & meta_modifier)
3809 fkey_next =
3810 get_keymap_1
3811 (get_keyelt
3812 (access_keymap
3813 (fkey_map, meta_prefix_char, 1)),
3814 0, 1);
3815 XFASTINT (key) = XFASTINT (key) & ~meta_modifier;
3817 else
3818 fkey_next = fkey_map;
3820 fkey_next =
3821 get_keyelt (access_keymap (fkey_next, key, 1));
3823 /* If keybuf[fkey_start..fkey_end] is bound in the
3824 function key map and it's a suffix of the current
3825 sequence (i.e. fkey_end == t), replace it with
3826 the binding and restart with fkey_start at the end. */
3827 if (XTYPE (fkey_next) == Lisp_Vector
3828 && fkey_end == t)
3830 t = fkey_start + XVECTOR (fkey_next)->size;
3831 if (t >= bufsize)
3832 error ("key sequence too long");
3834 bcopy (XVECTOR (fkey_next)->contents,
3835 keybuf + fkey_start,
3836 (t - fkey_start) * sizeof (keybuf[0]));
3838 mock_input = t;
3839 fkey_start = fkey_end = t;
3841 goto replay_sequence;
3844 fkey_map = get_keymap_1 (fkey_next, 0, 1);
3846 /* If we no longer have a bound suffix, try a new positions for
3847 fkey_start. */
3848 if (NILP (fkey_map))
3850 fkey_end = ++fkey_start;
3851 fkey_map = Vfunction_key_map;
3857 read_key_sequence_cmd = (first_binding < nmaps
3858 ? defs[first_binding]
3859 : Qnil);
3861 done:
3862 unread_switch_frame = delayed_switch_frame;
3863 unbind_to (count, Qnil);
3864 return t;
3867 DEFUN ("read-key-sequence", Fread_key_sequence, Sread_key_sequence, 1, 2, 0,
3868 "Read a sequence of keystrokes and return as a string or vector.\n\
3869 The sequence is sufficient to specify a non-prefix command in the\n\
3870 current local and global maps.\n\
3872 First arg PROMPT is a prompt string. If nil, do not prompt specially.\n\
3873 Second (optional) arg CONTINUE-ECHO, if non-nil, means this key echos\n\
3874 as a continuation of the previous key.\n\
3876 A C-g typed while in this function is treated like any other character,\n\
3877 and `quit-flag' is not set.\n\
3879 If the key sequence starts with a mouse click, then the sequence is read\n\
3880 using the keymaps of the buffer of the window clicked in, not the buffer\n\
3881 of the selected window as normal.\n\
3883 `read-key-sequence' drops unbound button-down events, since you normally\n\
3884 only care about the click or drag events which follow them. If a drag\n\
3885 event is unbound, but the corresponding click event would be bound,\n\
3886 `read-key-sequence' turns the drag event into a click event at the\n\
3887 drag's starting position. This means that you don't have to distinguish\n\
3888 between click and drag events unless you want to.\n\
3890 `read-key-sequence' prefixes mouse events on mode lines, the vertical\n\
3891 lines separating windows, and scroll bars with imaginary keys\n\
3892 `mode-line', `vertical-line', and `vertical-scroll-bar'.\n\
3894 If the user switches frames in the middle of a key sequence, the\n\
3895 frame-switch event is put off until after the current key sequence.\n\
3897 `read-key-sequence' checks `function-key-map' for function key\n\
3898 sequences, where they wouldn't conflict with ordinary bindings. See\n\
3899 `function-key-map' for more details.")
3900 (prompt, continue_echo)
3901 Lisp_Object prompt, continue_echo;
3903 Lisp_Object keybuf[30];
3904 register int i;
3905 struct gcpro gcpro1, gcpro2;
3907 if (!NILP (prompt))
3908 CHECK_STRING (prompt, 0);
3909 QUIT;
3911 bzero (keybuf, sizeof keybuf);
3912 GCPRO1 (keybuf[0]);
3913 gcpro1.nvars = (sizeof keybuf/sizeof (keybuf[0]));
3915 if (NILP (continue_echo))
3916 this_command_key_count = 0;
3918 i = read_key_sequence (keybuf, (sizeof keybuf/sizeof (keybuf[0])),
3919 NILP (prompt) ? 0 : XSTRING (prompt)->data);
3921 UNGCPRO;
3922 return make_event_array (i, keybuf);
3925 DEFUN ("command-execute", Fcommand_execute, Scommand_execute, 1, 2, 0,
3926 "Execute CMD as an editor command.\n\
3927 CMD must be a symbol that satisfies the `commandp' predicate.\n\
3928 Optional second arg RECORD-FLAG non-nil\n\
3929 means unconditionally put this command in `command-history'.\n\
3930 Otherwise, that is done only if an arg is read using the minibuffer.")
3931 (cmd, record)
3932 Lisp_Object cmd, record;
3934 register Lisp_Object final;
3935 register Lisp_Object tem;
3936 Lisp_Object prefixarg;
3937 struct backtrace backtrace;
3938 extern int debug_on_next_call;
3940 prefixarg = Vprefix_arg, Vprefix_arg = Qnil;
3941 Vcurrent_prefix_arg = prefixarg;
3942 debug_on_next_call = 0;
3944 if (XTYPE (cmd) == Lisp_Symbol)
3946 tem = Fget (cmd, Qdisabled);
3947 if (!NILP (tem))
3948 return call1 (Vrun_hooks, Vdisabled_command_hook);
3951 while (1)
3953 final = Findirect_function (cmd);
3955 if (CONSP (final) && (tem = Fcar (final), EQ (tem, Qautoload)))
3956 do_autoload (final, cmd);
3957 else
3958 break;
3961 if (XTYPE (final) == Lisp_String
3962 || XTYPE (final) == Lisp_Vector)
3964 /* If requested, place the macro in the command history. For
3965 other sorts of commands, call-interactively takes care of
3966 this. */
3967 if (!NILP (record))
3968 Vcommand_history
3969 = Fcons (Fcons (Qexecute_kbd_macro,
3970 Fcons (final, Fcons (prefixarg, Qnil))),
3971 Vcommand_history);
3973 return Fexecute_kbd_macro (final, prefixarg);
3975 if (CONSP (final) || XTYPE (final) == Lisp_Subr
3976 || XTYPE (final) == Lisp_Compiled)
3978 backtrace.next = backtrace_list;
3979 backtrace_list = &backtrace;
3980 backtrace.function = &Qcall_interactively;
3981 backtrace.args = &cmd;
3982 backtrace.nargs = 1;
3983 backtrace.evalargs = 0;
3985 tem = Fcall_interactively (cmd, record);
3987 backtrace_list = backtrace.next;
3988 return tem;
3990 return Qnil;
3993 DEFUN ("execute-extended-command", Fexecute_extended_command, Sexecute_extended_command,
3994 1, 1, "P",
3995 "Read function name, then read its arguments and call it.")
3996 (prefixarg)
3997 Lisp_Object prefixarg;
3999 Lisp_Object function;
4000 char buf[40];
4001 Lisp_Object saved_keys;
4002 struct gcpro gcpro1;
4004 saved_keys = Fthis_command_keys ();
4005 buf[0] = 0;
4006 GCPRO1 (saved_keys);
4008 if (EQ (prefixarg, Qminus))
4009 strcpy (buf, "- ");
4010 else if (CONSP (prefixarg) && XINT (XCONS (prefixarg)->car) == 4)
4011 strcpy (buf, "C-u ");
4012 else if (CONSP (prefixarg) && XTYPE (XCONS (prefixarg)->car) == Lisp_Int)
4013 sprintf (buf, "%d ", XINT (XCONS (prefixarg)->car));
4014 else if (XTYPE (prefixarg) == Lisp_Int)
4015 sprintf (buf, "%d ", XINT (prefixarg));
4017 /* This isn't strictly correct if execute-extended-command
4018 is bound to anything else. Perhaps it should use
4019 this_command_keys? */
4020 strcat (buf, "M-x ");
4022 /* Prompt with buf, and then read a string, completing from and
4023 restricting to the set of all defined commands. Don't provide
4024 any initial input. The last Qnil says not to perform a
4025 peculiar hack on the initial input. */
4026 function = Fcompleting_read (build_string (buf),
4027 Vobarray, Qcommandp,
4028 Qt, Qnil, Qnil);
4030 /* Set this_command_keys to the concatenation of saved_keys and
4031 function, followed by a RET. */
4033 struct Lisp_String *str;
4034 int i;
4035 Lisp_Object tem;
4037 this_command_key_count = 0;
4039 str = XSTRING (saved_keys);
4040 for (i = 0; i < str->size; i++)
4042 XFASTINT (tem) = str->data[i];
4043 add_command_key (tem);
4046 str = XSTRING (function);
4047 for (i = 0; i < str->size; i++)
4049 XFASTINT (tem) = str->data[i];
4050 add_command_key (tem);
4053 XFASTINT (tem) = '\015';
4054 add_command_key (tem);
4057 UNGCPRO;
4059 function = Fintern (function, Qnil);
4060 Vprefix_arg = prefixarg;
4061 this_command = function;
4063 return Fcommand_execute (function, Qt);
4067 detect_input_pending ()
4069 if (!input_pending)
4070 get_input_pending (&input_pending);
4072 return input_pending;
4075 /* This is called in some cases before a possible quit.
4076 It cases the next call to detect_input_pending to recompute input_pending.
4077 So calling this function unnecessarily can't do any harm. */
4078 clear_input_pending ()
4080 input_pending = 0;
4083 DEFUN ("input-pending-p", Finput_pending_p, Sinput_pending_p, 0, 0, 0,
4084 "T if command input is currently available with no waiting.\n\
4085 Actually, the value is nil only if we can be sure that no input is available.")
4088 if (!NILP (unread_command_events) || unread_command_char != -1)
4089 return (Qt);
4091 return detect_input_pending () ? Qt : Qnil;
4094 DEFUN ("recent-keys", Frecent_keys, Srecent_keys, 0, 0, 0,
4095 "Return vector of last 100 events, not counting those from keyboard macros.")
4098 Lisp_Object *keys = XVECTOR (recent_keys)->contents;
4099 Lisp_Object val;
4101 if (total_keys < NUM_RECENT_KEYS)
4102 return Fvector (total_keys, keys);
4103 else
4105 val = Fvector (NUM_RECENT_KEYS, keys);
4106 bcopy (keys + recent_keys_index,
4107 XVECTOR (val)->contents,
4108 (NUM_RECENT_KEYS - recent_keys_index) * sizeof (Lisp_Object));
4109 bcopy (keys,
4110 XVECTOR (val)->contents + NUM_RECENT_KEYS - recent_keys_index,
4111 recent_keys_index * sizeof (Lisp_Object));
4112 return val;
4116 DEFUN ("this-command-keys", Fthis_command_keys, Sthis_command_keys, 0, 0, 0,
4117 "Return string of the keystrokes that invoked this command.")
4120 return make_event_array (this_command_key_count,
4121 XVECTOR (this_command_keys)->contents);
4124 DEFUN ("recursion-depth", Frecursion_depth, Srecursion_depth, 0, 0, 0,
4125 "Return the current depth in recursive edits.")
4128 Lisp_Object temp;
4129 XFASTINT (temp) = command_loop_level + minibuf_level;
4130 return temp;
4133 DEFUN ("open-dribble-file", Fopen_dribble_file, Sopen_dribble_file, 1, 1,
4134 "FOpen dribble file: ",
4135 "Start writing all keyboard characters to a dribble file called FILE.\n\
4136 If FILE is nil, close any open dribble file.")
4137 (file)
4138 Lisp_Object file;
4140 if (NILP (file))
4142 fclose (dribble);
4143 dribble = 0;
4145 else
4147 file = Fexpand_file_name (file, Qnil);
4148 dribble = fopen (XSTRING (file)->data, "w");
4150 return Qnil;
4153 DEFUN ("discard-input", Fdiscard_input, Sdiscard_input, 0, 0, 0,
4154 "Discard the contents of the terminal input buffer.\n\
4155 Also cancel any kbd macro being defined.")
4158 defining_kbd_macro = 0;
4159 update_mode_lines++;
4161 unread_command_events = Qnil;
4162 unread_command_char = -1;
4164 discard_tty_input ();
4166 /* Without the cast, GCC complains that this assignment loses the
4167 volatile qualifier of kbd_store_ptr. Is there anything wrong
4168 with that? */
4169 kbd_fetch_ptr = (struct input_event *) kbd_store_ptr;
4170 Ffillarray (kbd_buffer_frame_or_window, Qnil);
4171 input_pending = 0;
4173 return Qnil;
4176 DEFUN ("suspend-emacs", Fsuspend_emacs, Ssuspend_emacs, 0, 1, "",
4177 "Stop Emacs and return to superior process. You can resume later.\n\
4178 On systems that don't have job control, run a subshell instead.\n\n\
4179 If optional arg STUFFSTRING is non-nil, its characters are stuffed\n\
4180 to be read as terminal input by Emacs's parent, after suspension.\n\
4182 Before suspending, call the functions in `suspend-hooks' with no args.\n\
4183 If any of them returns nil, don't call the rest and don't suspend.\n\
4184 Otherwise, suspend normally and after resumption run the normal hook\n\
4185 `suspend-resume-hook' if that is bound and non-nil.\n\
4187 Some operating systems cannot stop the Emacs process and resume it later.\n\
4188 On such systems, Emacs starts a subshell instead of suspending.")
4189 (stuffstring)
4190 Lisp_Object stuffstring;
4192 Lisp_Object tem;
4193 int count = specpdl_ptr - specpdl;
4194 int old_height, old_width;
4195 int width, height;
4196 struct gcpro gcpro1, gcpro2;
4197 extern init_sys_modes ();
4199 if (!NILP (stuffstring))
4200 CHECK_STRING (stuffstring, 0);
4202 /* Run the functions in suspend-hook. */
4203 if (!NILP (Vrun_hooks))
4204 call1 (Vrun_hooks, intern ("suspend-hook"));
4206 GCPRO1 (stuffstring);
4207 get_frame_size (&old_width, &old_height);
4208 reset_sys_modes ();
4209 /* sys_suspend can get an error if it tries to fork a subshell
4210 and the system resources aren't available for that. */
4211 record_unwind_protect (init_sys_modes, 0);
4212 stuff_buffered_input (stuffstring);
4213 sys_suspend ();
4214 unbind_to (count, Qnil);
4216 /* Check if terminal/window size has changed.
4217 Note that this is not useful when we are running directly
4218 with a window system; but suspend should be disabled in that case. */
4219 get_frame_size (&width, &height);
4220 if (width != old_width || height != old_height)
4221 change_frame_size (0, height, width, 0, 0);
4223 /* Run suspend-resume-hook. */
4224 if (!NILP (Vrun_hooks))
4225 call1 (Vrun_hooks, intern ("suspend-resume-hook"));
4227 UNGCPRO;
4228 return Qnil;
4231 /* If STUFFSTRING is a string, stuff its contents as pending terminal input.
4232 Then in any case stuff anthing Emacs has read ahead and not used. */
4234 stuff_buffered_input (stuffstring)
4235 Lisp_Object stuffstring;
4237 register unsigned char *p;
4239 /* stuff_char works only in BSD, versions 4.2 and up. */
4240 #ifdef BSD
4241 #ifndef BSD4_1
4242 if (XTYPE (stuffstring) == Lisp_String)
4244 register int count;
4246 p = XSTRING (stuffstring)->data;
4247 count = XSTRING (stuffstring)->size;
4248 while (count-- > 0)
4249 stuff_char (*p++);
4250 stuff_char ('\n');
4252 /* Anything we have read ahead, put back for the shell to read. */
4253 while (kbd_fetch_ptr != kbd_store_ptr)
4255 if (kbd_fetch_ptr == kbd_buffer + KBD_BUFFER_SIZE)
4256 kbd_fetch_ptr = kbd_buffer;
4257 if (kbd_fetch_ptr->kind == ascii_keystroke)
4258 stuff_char (XINT (kbd_fetch_ptr->code));
4259 kbd_fetch_ptr->kind = no_event;
4260 (XVECTOR (kbd_buffer_frame_or_window)->contents[kbd_fetch_ptr
4261 - kbd_buffer]
4262 = Qnil);
4263 kbd_fetch_ptr++;
4265 input_pending = 0;
4266 #endif
4267 #endif /* BSD and not BSD4_1 */
4270 set_waiting_for_input (time_to_clear)
4271 EMACS_TIME *time_to_clear;
4273 input_available_clear_time = time_to_clear;
4275 /* Tell interrupt_signal to throw back to read_char, */
4276 waiting_for_input = 1;
4278 /* If interrupt_signal was called before and buffered a C-g,
4279 make it run again now, to avoid timing error. */
4280 if (!NILP (Vquit_flag))
4281 quit_throw_to_read_char ();
4283 /* If alarm has gone off already, echo now. */
4284 if (echo_flag)
4286 echo ();
4287 echo_flag = 0;
4291 clear_waiting_for_input ()
4293 /* Tell interrupt_signal not to throw back to read_char, */
4294 waiting_for_input = 0;
4295 input_available_clear_time = 0;
4298 /* This routine is called at interrupt level in response to C-G.
4299 If interrupt_input, this is the handler for SIGINT.
4300 Otherwise, it is called from kbd_buffer_store_event,
4301 in handling SIGIO or SIGTINT.
4303 If `waiting_for_input' is non zero, then unless `echoing' is nonzero,
4304 immediately throw back to read_char.
4306 Otherwise it sets the Lisp variable quit-flag not-nil.
4307 This causes eval to throw, when it gets a chance.
4308 If quit-flag is already non-nil, it stops the job right away. */
4310 SIGTYPE
4311 interrupt_signal ()
4313 char c;
4314 /* Must preserve main program's value of errno. */
4315 int old_errno = errno;
4317 #ifdef USG
4318 /* USG systems forget handlers when they are used;
4319 must reestablish each time */
4320 signal (SIGINT, interrupt_signal);
4321 signal (SIGQUIT, interrupt_signal);
4322 #endif /* USG */
4324 cancel_echoing ();
4326 if (!NILP (Vquit_flag) && FRAME_TERMCAP_P (selected_frame))
4328 fflush (stdout);
4329 reset_sys_modes ();
4330 sigfree ();
4331 #ifdef SIGTSTP /* Support possible in later USG versions */
4333 * On systems which can suspend the current process and return to the original
4334 * shell, this command causes the user to end up back at the shell.
4335 * The "Auto-save" and "Abort" questions are not asked until
4336 * the user elects to return to emacs, at which point he can save the current
4337 * job and either dump core or continue.
4339 sys_suspend ();
4340 #else
4341 #ifdef VMS
4342 if (sys_suspend () == -1)
4344 printf ("Not running as a subprocess;\n");
4345 printf ("you can continue or abort.\n");
4347 #else /* not VMS */
4348 /* Perhaps should really fork an inferior shell?
4349 But that would not provide any way to get back
4350 to the original shell, ever. */
4351 printf ("No support for stopping a process on this operating system;\n");
4352 printf ("you can continue or abort.\n");
4353 #endif /* not VMS */
4354 #endif /* not SIGTSTP */
4355 printf ("Auto-save? (y or n) ");
4356 fflush (stdout);
4357 if (((c = getchar ()) & ~040) == 'Y')
4358 Fdo_auto_save (Qnil, Qnil);
4359 while (c != '\n') c = getchar ();
4360 #ifdef VMS
4361 printf ("Abort (and enter debugger)? (y or n) ");
4362 #else /* not VMS */
4363 printf ("Abort (and dump core)? (y or n) ");
4364 #endif /* not VMS */
4365 fflush (stdout);
4366 if (((c = getchar ()) & ~040) == 'Y')
4367 abort ();
4368 while (c != '\n') c = getchar ();
4369 printf ("Continuing...\n");
4370 fflush (stdout);
4371 init_sys_modes ();
4373 else
4375 /* If executing a function that wants to be interrupted out of
4376 and the user has not deferred quitting by binding `inhibit-quit'
4377 then quit right away. */
4378 if (immediate_quit && NILP (Vinhibit_quit))
4380 immediate_quit = 0;
4381 sigfree ();
4382 Fsignal (Qquit, Qnil);
4384 else
4385 /* Else request quit when it's safe */
4386 Vquit_flag = Qt;
4389 if (waiting_for_input && !echoing)
4390 quit_throw_to_read_char ();
4392 errno = old_errno;
4395 /* Handle a C-g by making read_char return C-g. */
4397 quit_throw_to_read_char ()
4399 quit_error_check ();
4400 sigfree ();
4401 /* Prevent another signal from doing this before we finish. */
4402 clear_waiting_for_input ();
4403 input_pending = 0;
4405 unread_command_events = Qnil;
4406 unread_command_char = -1;
4408 #ifdef POLL_FOR_INPUT
4409 /* May be > 1 if in recursive minibuffer. */
4410 if (poll_suppress_count == 0)
4411 abort ();
4412 #endif
4414 _longjmp (getcjmp, 1);
4417 DEFUN ("set-input-mode", Fset_input_mode, Sset_input_mode, 3, 4, 0,
4418 "Set mode of reading keyboard input.\n\
4419 First arg INTERRUPT non-nil means use input interrupts;\n\
4420 nil means use CBREAK mode.\n\
4421 Second arg FLOW non-nil means use ^S/^Q flow control for output to terminal\n\
4422 (no effect except in CBREAK mode).\n\
4423 Third arg META non-nil means accept 8-bit input (for a Meta key).\n\
4424 Otherwise, the top bit is ignored, on the assumption it is parity.\n\
4425 Optional fourth arg QUIT if non-nil specifies character to use for quitting.")
4426 (interrupt, flow, meta, quit)
4427 Lisp_Object interrupt, flow, meta, quit;
4429 if (!NILP (quit)
4430 && (XTYPE (quit) != Lisp_Int
4431 || XINT (quit) < 0 || XINT (quit) > 0400))
4432 error ("set-input-mode: QUIT must be an ASCII character.");
4434 reset_sys_modes ();
4435 #ifdef SIGIO
4436 /* Note SIGIO has been undef'd if FIONREAD is missing. */
4437 #ifdef NO_SOCK_SIGIO
4438 if (read_socket_hook)
4439 interrupt_input = 0; /* No interrupts if reading from a socket. */
4440 else
4441 #endif /* NO_SOCK_SIGIO */
4442 interrupt_input = !NILP (interrupt);
4443 #else /* not SIGIO */
4444 interrupt_input = 0;
4445 #endif /* not SIGIO */
4446 /* Our VMS input only works by interrupts, as of now. */
4447 #ifdef VMS
4448 interrupt_input = 1;
4449 #endif
4450 flow_control = !NILP (flow);
4451 meta_key = !NILP (meta);
4452 if (!NILP (quit))
4453 /* Don't let this value be out of range. */
4454 quit_char = XINT (quit) & (meta_key ? 0377 : 0177);
4456 init_sys_modes ();
4457 return Qnil;
4460 init_keyboard ()
4462 /* This is correct before outermost invocation of the editor loop */
4463 command_loop_level = -1;
4464 immediate_quit = 0;
4465 quit_char = Ctl ('g');
4466 unread_command_events = Qnil;
4467 unread_command_char = -1;
4468 total_keys = 0;
4469 recent_keys_index = 0;
4470 kbd_fetch_ptr = kbd_buffer;
4471 kbd_store_ptr = kbd_buffer;
4472 do_mouse_tracking = 0;
4473 input_pending = 0;
4475 #ifdef MULTI_FRAME
4476 /* This means that command_loop_1 won't try to select anything the first
4477 time through. */
4478 internal_last_event_frame = Qnil;
4479 Vlast_event_frame = internal_last_event_frame;
4480 #endif
4482 /* If we're running a dumped Emacs, we need to clear out
4483 kbd_buffer_frame_or_window, in case some events got into it
4484 before we dumped.
4486 If we're running an undumped Emacs, it hasn't been initialized by
4487 syms_of_keyboard yet. */
4488 if (initialized)
4489 Ffillarray (kbd_buffer_frame_or_window, Qnil);
4491 if (!noninteractive)
4493 signal (SIGINT, interrupt_signal);
4494 #if defined (HAVE_TERMIO) || defined (HAVE_TERMIOS)
4495 /* For systems with SysV TERMIO, C-g is set up for both SIGINT and
4496 SIGQUIT and we can't tell which one it will give us. */
4497 signal (SIGQUIT, interrupt_signal);
4498 #endif /* HAVE_TERMIO */
4499 /* Note SIGIO has been undef'd if FIONREAD is missing. */
4500 #ifdef SIGIO
4501 signal (SIGIO, input_available_signal);
4502 #endif /* SIGIO */
4505 /* Use interrupt input by default, if it works and noninterrupt input
4506 has deficiencies. */
4508 #ifdef INTERRUPT_INPUT
4509 interrupt_input = 1;
4510 #else
4511 interrupt_input = 0;
4512 #endif
4514 /* Our VMS input only works by interrupts, as of now. */
4515 #ifdef VMS
4516 interrupt_input = 1;
4517 #endif
4519 sigfree ();
4520 dribble = 0;
4522 if (keyboard_init_hook)
4523 (*keyboard_init_hook) ();
4525 #ifdef POLL_FOR_INPUT
4526 poll_suppress_count = 1;
4527 start_polling ();
4528 #endif
4531 /* This type's only use is in syms_of_keyboard, to initialize the
4532 event header symbols and put properties on them. */
4533 struct event_head {
4534 Lisp_Object *var;
4535 char *name;
4536 Lisp_Object *kind;
4539 struct event_head head_table[] = {
4540 &Qmouse_movement, "mouse-movement", &Qmouse_movement,
4541 &Qscroll_bar_movement, "scroll-bar-movement", &Qmouse_movement,
4542 &Qswitch_frame, "switch-frame", &Qswitch_frame,
4545 syms_of_keyboard ()
4547 Qself_insert_command = intern ("self-insert-command");
4548 staticpro (&Qself_insert_command);
4550 Qforward_char = intern ("forward-char");
4551 staticpro (&Qforward_char);
4553 Qbackward_char = intern ("backward-char");
4554 staticpro (&Qbackward_char);
4556 Qdisabled = intern ("disabled");
4557 staticpro (&Qdisabled);
4559 Qpre_command_hook = intern ("pre-command-hook");
4560 staticpro (&Qpre_command_hook);
4562 Qpost_command_hook = intern ("post-command-hook");
4563 staticpro (&Qpost_command_hook);
4565 Qfunction_key = intern ("function-key");
4566 staticpro (&Qfunction_key);
4567 Qmouse_click = intern ("mouse-click");
4568 staticpro (&Qmouse_click);
4570 Qmenu_enable = intern ("menu-enable");
4571 staticpro (&Qmenu_enable);
4573 Qmode_line = intern ("mode-line");
4574 staticpro (&Qmode_line);
4575 Qvertical_line = intern ("vertical-line");
4576 staticpro (&Qvertical_line);
4577 Qvertical_scroll_bar = intern ("vertical-scroll-bar");
4578 staticpro (&Qvertical_scroll_bar);
4579 Qmenu_bar = intern ("menu-bar");
4580 staticpro (&Qmenu_bar);
4582 Qabove_handle = intern ("above-handle");
4583 staticpro (&Qabove_handle);
4584 Qhandle = intern ("handle");
4585 staticpro (&Qhandle);
4586 Qbelow_handle = intern ("below-handle");
4587 staticpro (&Qbelow_handle);
4589 Qevent_kind = intern ("event-kind");
4590 staticpro (&Qevent_kind);
4591 Qevent_symbol_elements = intern ("event-symbol-elements");
4592 staticpro (&Qevent_symbol_elements);
4593 Qevent_symbol_element_mask = intern ("event-symbol-element-mask");
4594 staticpro (&Qevent_symbol_element_mask);
4595 Qmodifier_cache = intern ("modifier-cache");
4596 staticpro (&Qmodifier_cache);
4598 Qrecompute_lucid_menubar = intern ("recompute-lucid-menubar");
4599 staticpro (&Qrecompute_lucid_menubar);
4600 Qactivate_menubar_hook = intern ("activate-menubar-hook");
4601 staticpro (&Qactivate_menubar_hook);
4604 struct event_head *p;
4606 for (p = head_table;
4607 p < head_table + (sizeof (head_table) / sizeof (head_table[0]));
4608 p++)
4610 *p->var = intern (p->name);
4611 staticpro (p->var);
4612 Fput (*p->var, Qevent_kind, *p->kind);
4613 Fput (*p->var, Qevent_symbol_elements, Fcons (*p->var, Qnil));
4617 button_down_location = Fmake_vector (make_number (NUM_MOUSE_BUTTONS), Qnil);
4618 staticpro (&button_down_location);
4621 int i;
4622 int len = sizeof (modifier_names) / sizeof (modifier_names[0]);
4624 modifier_symbols = Fmake_vector (make_number (len), Qnil);
4625 for (i = 0; i < len; i++)
4626 if (modifier_names[i])
4627 XVECTOR (modifier_symbols)->contents[i] = intern (modifier_names[i]);
4628 staticpro (&modifier_symbols);
4631 recent_keys = Fmake_vector (make_number (NUM_RECENT_KEYS), Qnil);
4632 staticpro (&recent_keys);
4634 this_command_keys = Fmake_vector (make_number (40), Qnil);
4635 staticpro (&this_command_keys);
4637 kbd_buffer_frame_or_window
4638 = Fmake_vector (make_number (KBD_BUFFER_SIZE), Qnil);
4639 staticpro (&kbd_buffer_frame_or_window);
4641 func_key_syms = Qnil;
4642 staticpro (&func_key_syms);
4644 mouse_syms = Qnil;
4645 staticpro (&mouse_syms);
4647 unread_switch_frame = Qnil;
4648 staticpro (&unread_switch_frame);
4650 defsubr (&Sread_key_sequence);
4651 defsubr (&Srecursive_edit);
4652 defsubr (&Strack_mouse);
4653 defsubr (&Sinput_pending_p);
4654 defsubr (&Scommand_execute);
4655 defsubr (&Srecent_keys);
4656 defsubr (&Sthis_command_keys);
4657 defsubr (&Ssuspend_emacs);
4658 defsubr (&Sabort_recursive_edit);
4659 defsubr (&Sexit_recursive_edit);
4660 defsubr (&Srecursion_depth);
4661 defsubr (&Stop_level);
4662 defsubr (&Sdiscard_input);
4663 defsubr (&Sopen_dribble_file);
4664 defsubr (&Sset_input_mode);
4665 defsubr (&Sexecute_extended_command);
4667 DEFVAR_LISP ("disabled-command-hook", &Vdisabled_command_hook,
4668 "Value is called instead of any command that is disabled\n\
4669 \(has a non-nil `disabled' property).");
4671 DEFVAR_LISP ("last-command-char", &last_command_char,
4672 "Last input event that was part of a command.");
4674 DEFVAR_LISP ("last-command-event", &last_command_char,
4675 "Last input event that was part of a command.");
4677 DEFVAR_LISP ("last-nonmenu-event", &last_nonmenu_event,
4678 "Last input event in a command, except for mouse menu events.\n\
4679 Mouse menus give back keys that don't look like mouse events;\n\
4680 this variable holds the actual mouse event that led to the menu,\n\
4681 so that you can determine whether the command was run by mouse or not.");
4683 DEFVAR_LISP ("last-input-char", &last_input_char,
4684 "Last input event.");
4686 DEFVAR_LISP ("last-input-event", &last_input_char,
4687 "Last input event.");
4689 DEFVAR_LISP ("unread-command-events", &unread_command_events,
4690 "List of objects to be read as next command input events.");
4692 DEFVAR_INT ("unread-command-char", &unread_command_char,
4693 "If not -1, an object to be read as next command input event.");
4695 DEFVAR_LISP ("meta-prefix-char", &meta_prefix_char,
4696 "Meta-prefix character code. Meta-foo as command input\n\
4697 turns into this character followed by foo.");
4698 XSET (meta_prefix_char, Lisp_Int, 033);
4700 DEFVAR_LISP ("last-command", &last_command,
4701 "The last command executed. Normally a symbol with a function definition,\n\
4702 but can be whatever was found in the keymap, or whatever the variable\n\
4703 `this-command' was set to by that command.");
4704 last_command = Qnil;
4706 DEFVAR_LISP ("this-command", &this_command,
4707 "The command now being executed.\n\
4708 The command can set this variable; whatever is put here\n\
4709 will be in `last-command' during the following command.");
4710 this_command = Qnil;
4712 DEFVAR_INT ("auto-save-interval", &auto_save_interval,
4713 "*Number of keyboard input characters between auto-saves.\n\
4714 Zero means disable autosaving due to number of characters typed.");
4715 auto_save_interval = 300;
4717 DEFVAR_LISP ("auto-save-timeout", &Vauto_save_timeout,
4718 "*Number of seconds idle time before auto-save.\n\
4719 Zero or nil means disable auto-saving due to idleness.\n\
4720 After auto-saving due to this many seconds of idle time,\n\
4721 Emacs also does a garbage collection if that seems to be warranted.");
4722 XFASTINT (Vauto_save_timeout) = 30;
4724 DEFVAR_INT ("echo-keystrokes", &echo_keystrokes,
4725 "*Nonzero means echo unfinished commands after this many seconds of pause.");
4726 echo_keystrokes = 1;
4728 DEFVAR_INT ("polling-period", &polling_period,
4729 "*Interval between polling for input during Lisp execution.\n\
4730 The reason for polling is to make C-g work to stop a running program.\n\
4731 Polling is needed only when using X windows and SIGIO does not work.\n\
4732 Polling is automatically disabled in all other cases.");
4733 polling_period = 2;
4735 DEFVAR_INT ("num-input-keys", &num_input_keys,
4736 "*Number of complete keys read from the keyboard so far.");
4737 num_input_keys = 0;
4739 #ifdef MULTI_FRAME
4740 DEFVAR_LISP ("last-event-frame", &Vlast_event_frame,
4741 "*The frame in which the most recently read event occurred.\n\
4742 If the last event came from a keyboard macro, this is set to `macro'.");
4743 Vlast_event_frame = Qnil;
4744 #endif
4746 DEFVAR_LISP ("help-char", &help_char,
4747 "Character to recognize as meaning Help.\n\
4748 When it is read, do `(eval help-form)', and display result if it's a string.\n\
4749 If the value of `help-form' is nil, this char can be read normally.");
4750 XSET (help_char, Lisp_Int, Ctl ('H'));
4752 DEFVAR_LISP ("help-form", &Vhelp_form,
4753 "Form to execute when character help-char is read.\n\
4754 If the form returns a string, that string is displayed.\n\
4755 If `help-form' is nil, the help char is not recognized.");
4756 Vhelp_form = Qnil;
4758 DEFVAR_LISP ("top-level", &Vtop_level,
4759 "Form to evaluate when Emacs starts up.\n\
4760 Useful to set before you dump a modified Emacs.");
4761 Vtop_level = Qnil;
4763 DEFVAR_LISP ("keyboard-translate-table", &Vkeyboard_translate_table,
4764 "String used as translate table for keyboard input, or nil.\n\
4765 Each character is looked up in this string and the contents used instead.\n\
4766 If string is of length N, character codes N and up are untranslated.");
4767 Vkeyboard_translate_table = Qnil;
4769 DEFVAR_BOOL ("menu-prompting", &menu_prompting,
4770 "Non-nil means prompt with menus when appropriate.\n\
4771 This is done when reading from a keymap that has a prompt string,\n\
4772 for elements that have prompt strings.\n\
4773 The menu is displayed on the screen\n\
4774 if X menus were enabled at configuration\n\
4775 time and the previous event was a mouse click prefix key.\n\
4776 Otherwise, menu prompting uses the echo area.");
4777 menu_prompting = 1;
4779 DEFVAR_LISP ("menu-prompt-more-char", &menu_prompt_more_char,
4780 "Character to see next line of menu prompt.\n\
4781 Type this character while in a menu prompt to rotate around the lines of it.");
4782 XSET (menu_prompt_more_char, Lisp_Int, ' ');
4784 DEFVAR_INT ("extra-keyboard-modifiers", &extra_keyboard_modifiers,
4785 "A mask of additional modifier keys to use with every keyboard character.\n\
4786 These bits follow the convention for X windows,\n\
4787 but the control and meta bits work even when you are not using X:\n\
4788 1 -- shift bit 2 -- lock bit\n\
4789 4 -- control bit 8 -- meta bit.");
4790 extra_keyboard_modifiers = 0;
4792 DEFVAR_LISP ("deactivate-mark", &Vdeactivate_mark,
4793 "If an editing command sets this to t, deactivate the mark afterward.\n\
4794 The command loop sets this to nil before each command,\n\
4795 and tests the value when the command returns.\n\
4796 Buffer modification stores t in this variable.");
4797 Vdeactivate_mark = Qnil;
4799 DEFVAR_LISP ("pre-command-hook", &Vpre_command_hook,
4800 "Normal hook run before each command is executed.");
4801 Vpre_command_hook = Qnil;
4803 DEFVAR_LISP ("post-command-hook", &Vpost_command_hook,
4804 "Normal hook run before each command is executed.");
4805 Vpost_command_hook = Qnil;
4807 DEFVAR_LISP ("lucid-menu-bar-dirty-flag", &Vlucid_menu_bar_dirty_flag,
4808 "t means menu bar, specified Lucid style, needs to be recomputed.");
4809 Vlucid_menu_bar_dirty_flag = Qnil;
4812 keys_of_keyboard ()
4814 initial_define_key (global_map, Ctl ('Z'), "suspend-emacs");
4815 initial_define_key (control_x_map, Ctl ('Z'), "suspend-emacs");
4816 initial_define_key (meta_map, Ctl ('C'), "exit-recursive-edit");
4817 initial_define_key (global_map, Ctl (']'), "abort-recursive-edit");
4818 initial_define_key (meta_map, 'x', "execute-extended-command");