Merge branch 'master' into xwidget
[emacs.git] / src / keyboard.c
blob215b6ea3f70ea8fe5bfb4b1a77f4024730ee898d
1 /* Keyboard and mouse input; editor command loop.
3 Copyright (C) 1985-1989, 1993-1997, 1999-2014 Free Software Foundation, Inc.
5 This file is part of GNU Emacs.
7 GNU Emacs is free software: you can redistribute it and/or modify
8 it under the terms of the GNU General Public License as published by
9 the Free Software Foundation, either version 3 of the License, or
10 (at your option) any later version.
12 GNU Emacs is distributed in the hope that it will be useful,
13 but WITHOUT ANY WARRANTY; without even the implied warranty of
14 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15 GNU General Public License for more details.
17 You should have received a copy of the GNU General Public License
18 along with GNU Emacs. If not, see <http://www.gnu.org/licenses/>. */
20 #include <config.h>
22 #include "sysstdio.h"
23 #include <sys/stat.h>
25 #include "lisp.h"
26 #include "termchar.h"
27 #include "termopts.h"
28 #include "frame.h"
29 #include "termhooks.h"
30 #include "macros.h"
31 #include "keyboard.h"
32 #include "window.h"
33 #include "commands.h"
34 #include "character.h"
35 #include "buffer.h"
36 #include "disptab.h"
37 #include "dispextern.h"
38 #include "syntax.h"
39 #include "intervals.h"
40 #include "keymap.h"
41 #include "blockinput.h"
42 #include "puresize.h"
43 #include "systime.h"
44 #include "atimer.h"
45 #include "process.h"
46 #include <errno.h>
48 #ifdef HAVE_PTHREAD
49 #include <pthread.h>
50 #endif
51 #ifdef MSDOS
52 #include "msdos.h"
53 #include <time.h>
54 #else /* not MSDOS */
55 #include <sys/ioctl.h>
56 #endif /* not MSDOS */
58 #if defined USABLE_FIONREAD && defined USG5_4
59 # include <sys/filio.h>
60 #endif
62 #include "syssignal.h"
64 #include <sys/types.h>
65 #include <unistd.h>
66 #include <fcntl.h>
68 #ifdef HAVE_WINDOW_SYSTEM
69 #include TERM_HEADER
70 #endif /* HAVE_WINDOW_SYSTEM */
72 /* Variables for blockinput.h: */
74 /* Positive if interrupt input is blocked right now. */
75 volatile int interrupt_input_blocked;
77 /* True means an input interrupt or alarm signal has arrived.
78 The QUIT macro checks this. */
79 volatile bool pending_signals;
81 #define KBD_BUFFER_SIZE 4096
83 KBOARD *initial_kboard;
84 KBOARD *current_kboard;
85 static KBOARD *all_kboards;
87 /* True in the single-kboard state, false in the any-kboard state. */
88 static bool single_kboard;
90 /* Non-nil disable property on a command means
91 do not execute it; call disabled-command-function's value instead. */
92 Lisp_Object Qdisabled;
93 static Lisp_Object Qdisabled_command_function;
95 #define NUM_RECENT_KEYS (300)
97 /* Index for storing next element into recent_keys. */
98 static int recent_keys_index;
100 /* Total number of elements stored into recent_keys. */
101 static int total_keys;
103 /* This vector holds the last NUM_RECENT_KEYS keystrokes. */
104 static Lisp_Object recent_keys;
106 /* Vector holding the key sequence that invoked the current command.
107 It is reused for each command, and it may be longer than the current
108 sequence; this_command_key_count indicates how many elements
109 actually mean something.
110 It's easier to staticpro a single Lisp_Object than an array. */
111 Lisp_Object this_command_keys;
112 ptrdiff_t this_command_key_count;
114 /* True after calling Freset_this_command_lengths.
115 Usually it is false. */
116 static bool this_command_key_count_reset;
118 /* This vector is used as a buffer to record the events that were actually read
119 by read_key_sequence. */
120 static Lisp_Object raw_keybuf;
121 static int raw_keybuf_count;
123 #define GROW_RAW_KEYBUF \
124 if (raw_keybuf_count == ASIZE (raw_keybuf)) \
125 raw_keybuf = larger_vector (raw_keybuf, 1, -1)
127 /* Number of elements of this_command_keys
128 that precede this key sequence. */
129 static ptrdiff_t this_single_command_key_start;
131 /* Record values of this_command_key_count and echo_length ()
132 before this command was read. */
133 static ptrdiff_t before_command_key_count;
134 static ptrdiff_t before_command_echo_length;
136 #ifdef HAVE_STACK_OVERFLOW_HANDLING
138 /* For longjmp to recover from C stack overflow. */
139 sigjmp_buf return_to_command_loop;
141 /* Message displayed by Vtop_level when recovering from C stack overflow. */
142 static Lisp_Object recover_top_level_message;
144 #endif /* HAVE_STACK_OVERFLOW_HANDLING */
146 /* Message normally displayed by Vtop_level. */
147 static Lisp_Object regular_top_level_message;
149 /* For longjmp to where kbd input is being done. */
151 static sys_jmp_buf getcjmp;
153 /* True while doing kbd input. */
154 bool waiting_for_input;
156 /* True while displaying for echoing. Delays C-g throwing. */
158 static bool echoing;
160 /* Non-null means we can start echoing at the next input pause even
161 though there is something in the echo area. */
163 static struct kboard *ok_to_echo_at_next_pause;
165 /* The kboard last echoing, or null for none. Reset to 0 in
166 cancel_echoing. If non-null, and a current echo area message
167 exists, and echo_message_buffer is eq to the current message
168 buffer, we know that the message comes from echo_kboard. */
170 struct kboard *echo_kboard;
172 /* The buffer used for echoing. Set in echo_now, reset in
173 cancel_echoing. */
175 Lisp_Object echo_message_buffer;
177 /* True means C-g should cause immediate error-signal. */
178 bool immediate_quit;
180 /* Character that causes a quit. Normally C-g.
182 If we are running on an ordinary terminal, this must be an ordinary
183 ASCII char, since we want to make it our interrupt character.
185 If we are not running on an ordinary terminal, it still needs to be
186 an ordinary ASCII char. This character needs to be recognized in
187 the input interrupt handler. At this point, the keystroke is
188 represented as a struct input_event, while the desired quit
189 character is specified as a lispy event. The mapping from struct
190 input_events to lispy events cannot run in an interrupt handler,
191 and the reverse mapping is difficult for anything but ASCII
192 keystrokes.
194 FOR THESE ELABORATE AND UNSATISFYING REASONS, quit_char must be an
195 ASCII character. */
196 int quit_char;
198 /* Current depth in recursive edits. */
199 EMACS_INT command_loop_level;
201 /* If not Qnil, this is a switch-frame event which we decided to put
202 off until the end of a key sequence. This should be read as the
203 next command input, after any unread_command_events.
205 read_key_sequence uses this to delay switch-frame events until the
206 end of the key sequence; Fread_char uses it to put off switch-frame
207 events until a non-ASCII event is acceptable as input. */
208 Lisp_Object unread_switch_frame;
210 /* Last size recorded for a current buffer which is not a minibuffer. */
211 static ptrdiff_t last_non_minibuf_size;
213 /* Total number of times read_char has returned, modulo UINTMAX_MAX + 1. */
214 uintmax_t num_input_events;
216 /* Value of num_nonmacro_input_events as of last auto save. */
218 static EMACS_INT last_auto_save;
220 /* The value of point when the last command was started. */
221 static ptrdiff_t last_point_position;
223 /* The frame in which the last input event occurred, or Qmacro if the
224 last event came from a macro. We use this to determine when to
225 generate switch-frame events. This may be cleared by functions
226 like Fselect_frame, to make sure that a switch-frame event is
227 generated by the next character.
229 FIXME: This is modified by a signal handler so it should be volatile.
230 It's exported to Lisp, though, so it can't simply be marked
231 'volatile' here. */
232 Lisp_Object internal_last_event_frame;
234 static Lisp_Object Qgui_set_selection, Qhandle_switch_frame;
235 static Lisp_Object Qhandle_select_window;
236 Lisp_Object QPRIMARY;
238 static Lisp_Object Qself_insert_command;
239 static Lisp_Object Qforward_char;
240 static Lisp_Object Qbackward_char;
241 Lisp_Object Qundefined;
242 static Lisp_Object Qtimer_event_handler;
244 /* `read_key_sequence' stores here the command definition of the
245 key sequence that it reads. */
246 static Lisp_Object read_key_sequence_cmd;
247 static Lisp_Object read_key_sequence_remapped;
249 static Lisp_Object Qinput_method_function;
251 static Lisp_Object Qdeactivate_mark;
253 Lisp_Object Qrecompute_lucid_menubar, Qactivate_menubar_hook;
255 static Lisp_Object Qecho_area_clear_hook;
257 /* Hooks to run before and after each command. */
258 static Lisp_Object Qpre_command_hook;
259 static Lisp_Object Qpost_command_hook;
261 static Lisp_Object Qdeferred_action_function;
263 static Lisp_Object Qdelayed_warnings_hook;
265 static Lisp_Object Qinput_method_exit_on_first_char;
266 static Lisp_Object Qinput_method_use_echo_area;
268 static Lisp_Object Qhelp_form_show;
270 /* File in which we write all commands we read. */
271 static FILE *dribble;
273 /* True if input is available. */
274 bool input_pending;
276 /* True if more input was available last time we read an event.
278 Since redisplay can take a significant amount of time and is not
279 indispensible to perform the user's commands, when input arrives
280 "too fast", Emacs skips redisplay. More specifically, if the next
281 command has already been input when we finish the previous command,
282 we skip the intermediate redisplay.
284 This is useful to try and make sure Emacs keeps up with fast input
285 rates, such as auto-repeating keys. But in some cases, this proves
286 too conservative: we may end up disabling redisplay for the whole
287 duration of a key repetition, even though we could afford to
288 redisplay every once in a while.
290 So we "sample" the input_pending flag before running a command and
291 use *that* value after running the command to decide whether to
292 skip redisplay or not. This way, we only skip redisplay if we
293 really can't keep up with the repeat rate.
295 This only makes a difference if the next input arrives while running the
296 command, which is very unlikely if the command is executed quickly.
297 IOW this tends to avoid skipping redisplay after a long running command
298 (which is a case where skipping redisplay is not very useful since the
299 redisplay time is small compared to the time it took to run the command).
301 A typical use case is when scrolling. Scrolling time can be split into:
302 - Time to do jit-lock on the newly displayed portion of buffer.
303 - Time to run the actual scroll command.
304 - Time to perform the redisplay.
305 Jit-lock can happen either during the command or during the redisplay.
306 In the most painful cases, the jit-lock time is the one that dominates.
307 Also jit-lock can be tweaked (via jit-lock-defer) to delay its job, at the
308 cost of temporary inaccuracy in display and scrolling.
309 So without input_was_pending, what typically happens is the following:
310 - when the command starts, there's no pending input (yet).
311 - the scroll command triggers jit-lock.
312 - during the long jit-lock time the next input arrives.
313 - at the end of the command, we check input_pending and hence decide to
314 skip redisplay.
315 - we read the next input and start over.
316 End result: all the hard work of jit-locking is "wasted" since redisplay
317 doesn't actually happens (at least not before the input rate slows down).
318 With input_was_pending redisplay is still skipped if Emacs can't keep up
319 with the input rate, but if it can keep up just enough that there's no
320 input_pending when we begin the command, then redisplay is not skipped
321 which results in better feedback to the user. */
322 static bool input_was_pending;
324 /* Circular buffer for pre-read keyboard input. */
326 static struct input_event kbd_buffer[KBD_BUFFER_SIZE];
328 /* Pointer to next available character in kbd_buffer.
329 If kbd_fetch_ptr == kbd_store_ptr, the buffer is empty.
330 This may be kbd_buffer + KBD_BUFFER_SIZE, meaning that the
331 next available char is in kbd_buffer[0]. */
332 static struct input_event *kbd_fetch_ptr;
334 /* Pointer to next place to store character in kbd_buffer. This
335 may be kbd_buffer + KBD_BUFFER_SIZE, meaning that the next
336 character should go in kbd_buffer[0]. */
337 static struct input_event * volatile kbd_store_ptr;
339 /* The above pair of variables forms a "queue empty" flag. When we
340 enqueue a non-hook event, we increment kbd_store_ptr. When we
341 dequeue a non-hook event, we increment kbd_fetch_ptr. We say that
342 there is input available if the two pointers are not equal.
344 Why not just have a flag set and cleared by the enqueuing and
345 dequeuing functions? Such a flag could be screwed up by interrupts
346 at inopportune times. */
348 /* Symbols to head events. */
349 static Lisp_Object Qmouse_movement;
350 static Lisp_Object Qscroll_bar_movement;
351 Lisp_Object Qswitch_frame;
352 static Lisp_Object Qfocus_in, Qfocus_out;
353 static Lisp_Object Qdelete_frame;
354 static Lisp_Object Qiconify_frame;
355 static Lisp_Object Qmake_frame_visible;
356 static Lisp_Object Qselect_window;
357 Lisp_Object Qhelp_echo;
359 static Lisp_Object Qmouse_fixup_help_message;
361 /* Symbols to denote kinds of events. */
362 static Lisp_Object Qfunction_key;
363 Lisp_Object Qmouse_click;
364 #ifdef HAVE_NTGUI
365 Lisp_Object Qlanguage_change;
366 #endif
367 static Lisp_Object Qdrag_n_drop;
368 static Lisp_Object Qsave_session;
369 #ifdef HAVE_DBUS
370 static Lisp_Object Qdbus_event;
371 #endif
372 #ifdef HAVE_XWIDGETS
373 Lisp_Object Qxwidget_event;
374 #endif
375 #ifdef USE_FILE_NOTIFY
376 static Lisp_Object Qfile_notify;
377 #endif /* USE_FILE_NOTIFY */
378 static Lisp_Object Qconfig_changed_event;
380 /* Lisp_Object Qmouse_movement; - also an event header */
382 /* Properties of event headers. */
383 Lisp_Object Qevent_kind;
384 static Lisp_Object Qevent_symbol_elements;
386 /* Menu and tool bar item parts. */
387 static Lisp_Object Qmenu_enable;
388 static Lisp_Object QCenable, QCvisible, QChelp, QCkeys, QCkey_sequence;
389 Lisp_Object QCfilter;
391 /* Non-nil disable property on a command means
392 do not execute it; call disabled-command-function's value instead. */
393 Lisp_Object QCtoggle, QCradio;
394 static Lisp_Object QCbutton, QClabel;
396 static Lisp_Object QCvert_only;
398 /* An event header symbol HEAD may have a property named
399 Qevent_symbol_element_mask, which is of the form (BASE MODIFIERS);
400 BASE is the base, unmodified version of HEAD, and MODIFIERS is the
401 mask of modifiers applied to it. If present, this is used to help
402 speed up parse_modifiers. */
403 Lisp_Object Qevent_symbol_element_mask;
405 /* An unmodified event header BASE may have a property named
406 Qmodifier_cache, which is an alist mapping modifier masks onto
407 modified versions of BASE. If present, this helps speed up
408 apply_modifiers. */
409 static Lisp_Object Qmodifier_cache;
411 /* Symbols to use for parts of windows. */
412 Lisp_Object Qmode_line;
413 Lisp_Object Qvertical_line;
414 Lisp_Object Qright_divider, Qbottom_divider;
415 Lisp_Object Qmenu_bar;
417 static Lisp_Object Qecho_keystrokes;
419 static void recursive_edit_unwind (Lisp_Object buffer);
420 static Lisp_Object command_loop (void);
421 static Lisp_Object Qcommand_execute;
423 static void echo_now (void);
424 static ptrdiff_t echo_length (void);
426 static Lisp_Object Qpolling_period;
428 /* Incremented whenever a timer is run. */
429 unsigned timers_run;
431 /* Address (if not 0) of struct timespec to zero out if a SIGIO interrupt
432 happens. */
433 struct timespec *input_available_clear_time;
435 /* True means use SIGIO interrupts; false means use CBREAK mode.
436 Default is true if INTERRUPT_INPUT is defined. */
437 bool interrupt_input;
439 /* Nonzero while interrupts are temporarily deferred during redisplay. */
440 bool interrupts_deferred;
442 /* The time when Emacs started being idle. */
444 static struct timespec timer_idleness_start_time;
446 /* After Emacs stops being idle, this saves the last value
447 of timer_idleness_start_time from when it was idle. */
449 static struct timespec timer_last_idleness_start_time;
452 /* Global variable declarations. */
454 /* Flags for readable_events. */
455 #define READABLE_EVENTS_DO_TIMERS_NOW (1 << 0)
456 #define READABLE_EVENTS_FILTER_EVENTS (1 << 1)
457 #define READABLE_EVENTS_IGNORE_SQUEEZABLES (1 << 2)
459 /* Function for init_keyboard to call with no args (if nonzero). */
460 static void (*keyboard_init_hook) (void);
462 static bool get_input_pending (int);
463 static bool readable_events (int);
464 static Lisp_Object read_char_x_menu_prompt (Lisp_Object,
465 Lisp_Object, bool *);
466 static Lisp_Object read_char_minibuf_menu_prompt (int, Lisp_Object);
467 static Lisp_Object make_lispy_event (struct input_event *);
468 static Lisp_Object make_lispy_movement (struct frame *, Lisp_Object,
469 enum scroll_bar_part,
470 Lisp_Object, Lisp_Object,
471 Time);
472 static Lisp_Object modify_event_symbol (ptrdiff_t, int, Lisp_Object,
473 Lisp_Object, const char *const *,
474 Lisp_Object *, ptrdiff_t);
475 static Lisp_Object make_lispy_switch_frame (Lisp_Object);
476 static Lisp_Object make_lispy_focus_in (Lisp_Object);
477 #ifdef HAVE_WINDOW_SYSTEM
478 static Lisp_Object make_lispy_focus_out (Lisp_Object);
479 #endif /* HAVE_WINDOW_SYSTEM */
480 static bool help_char_p (Lisp_Object);
481 static void save_getcjmp (sys_jmp_buf);
482 static void restore_getcjmp (sys_jmp_buf);
483 static Lisp_Object apply_modifiers (int, Lisp_Object);
484 static void clear_event (struct input_event *);
485 static void restore_kboard_configuration (int);
486 #ifdef USABLE_SIGIO
487 static void deliver_input_available_signal (int signo);
488 #endif
489 static void handle_interrupt (bool);
490 static _Noreturn void quit_throw_to_read_char (bool);
491 static void process_special_events (void);
492 static void timer_start_idle (void);
493 static void timer_stop_idle (void);
494 static void timer_resume_idle (void);
495 static void deliver_user_signal (int);
496 static char *find_user_signal_name (int);
497 static void store_user_signal_events (void);
499 /* These setters are used only in this file, so they can be private. */
500 static void
501 kset_echo_string (struct kboard *kb, Lisp_Object val)
503 kb->INTERNAL_FIELD (echo_string) = val;
505 static void
506 kset_kbd_queue (struct kboard *kb, Lisp_Object val)
508 kb->INTERNAL_FIELD (kbd_queue) = val;
510 static void
511 kset_keyboard_translate_table (struct kboard *kb, Lisp_Object val)
513 kb->INTERNAL_FIELD (Vkeyboard_translate_table) = val;
515 static void
516 kset_last_prefix_arg (struct kboard *kb, Lisp_Object val)
518 kb->INTERNAL_FIELD (Vlast_prefix_arg) = val;
520 static void
521 kset_last_repeatable_command (struct kboard *kb, Lisp_Object val)
523 kb->INTERNAL_FIELD (Vlast_repeatable_command) = val;
525 static void
526 kset_local_function_key_map (struct kboard *kb, Lisp_Object val)
528 kb->INTERNAL_FIELD (Vlocal_function_key_map) = val;
530 static void
531 kset_overriding_terminal_local_map (struct kboard *kb, Lisp_Object val)
533 kb->INTERNAL_FIELD (Voverriding_terminal_local_map) = val;
535 static void
536 kset_real_last_command (struct kboard *kb, Lisp_Object val)
538 kb->INTERNAL_FIELD (Vreal_last_command) = val;
540 static void
541 kset_system_key_syms (struct kboard *kb, Lisp_Object val)
543 kb->INTERNAL_FIELD (system_key_syms) = val;
547 /* Add C to the echo string, without echoing it immediately. C can be
548 a character, which is pretty-printed, or a symbol, whose name is
549 printed. */
551 static void
552 echo_add_key (Lisp_Object c)
554 char initbuf[KEY_DESCRIPTION_SIZE + 100];
555 ptrdiff_t size = sizeof initbuf;
556 char *buffer = initbuf;
557 char *ptr = buffer;
558 Lisp_Object echo_string;
559 USE_SAFE_ALLOCA;
561 echo_string = KVAR (current_kboard, echo_string);
563 /* If someone has passed us a composite event, use its head symbol. */
564 c = EVENT_HEAD (c);
566 if (INTEGERP (c))
567 ptr = push_key_description (XINT (c), ptr);
568 else if (SYMBOLP (c))
570 Lisp_Object name = SYMBOL_NAME (c);
571 ptrdiff_t nbytes = SBYTES (name);
573 if (size - (ptr - buffer) < nbytes)
575 ptrdiff_t offset = ptr - buffer;
576 size = max (2 * size, size + nbytes);
577 buffer = SAFE_ALLOCA (size);
578 ptr = buffer + offset;
581 ptr += copy_text (SDATA (name), (unsigned char *) ptr, nbytes,
582 STRING_MULTIBYTE (name), 1);
585 if ((NILP (echo_string) || SCHARS (echo_string) == 0)
586 && help_char_p (c))
588 static const char text[] = " (Type ? for further options)";
589 int len = sizeof text - 1;
591 if (size - (ptr - buffer) < len)
593 ptrdiff_t offset = ptr - buffer;
594 size += len;
595 buffer = SAFE_ALLOCA (size);
596 ptr = buffer + offset;
599 memcpy (ptr, text, len);
600 ptr += len;
603 /* Replace a dash from echo_dash with a space, otherwise add a space
604 at the end as a separator between keys. */
605 AUTO_STRING (space, " ");
606 if (STRINGP (echo_string) && SCHARS (echo_string) > 1)
608 Lisp_Object last_char, prev_char, idx;
610 idx = make_number (SCHARS (echo_string) - 2);
611 prev_char = Faref (echo_string, idx);
613 idx = make_number (SCHARS (echo_string) - 1);
614 last_char = Faref (echo_string, idx);
616 /* We test PREV_CHAR to make sure this isn't the echoing of a
617 minus-sign. */
618 if (XINT (last_char) == '-' && XINT (prev_char) != ' ')
619 Faset (echo_string, idx, make_number (' '));
620 else
621 echo_string = concat2 (echo_string, space);
623 else if (STRINGP (echo_string) && SCHARS (echo_string) > 0)
624 echo_string = concat2 (echo_string, space);
626 kset_echo_string
627 (current_kboard,
628 concat2 (echo_string, make_string (buffer, ptr - buffer)));
629 SAFE_FREE ();
632 /* Add C to the echo string, if echoing is going on. C can be a
633 character or a symbol. */
635 static void
636 echo_char (Lisp_Object c)
638 if (current_kboard->immediate_echo)
640 echo_add_key (c);
641 echo_now ();
645 /* Temporarily add a dash to the end of the echo string if it's not
646 empty, so that it serves as a mini-prompt for the very next
647 character. */
649 static void
650 echo_dash (void)
652 /* Do nothing if not echoing at all. */
653 if (NILP (KVAR (current_kboard, echo_string)))
654 return;
656 if (this_command_key_count == 0)
657 return;
659 if (!current_kboard->immediate_echo
660 && SCHARS (KVAR (current_kboard, echo_string)) == 0)
661 return;
663 /* Do nothing if we just printed a prompt. */
664 if (current_kboard->echo_after_prompt
665 == SCHARS (KVAR (current_kboard, echo_string)))
666 return;
668 /* Do nothing if we have already put a dash at the end. */
669 if (SCHARS (KVAR (current_kboard, echo_string)) > 1)
671 Lisp_Object last_char, prev_char, idx;
673 idx = make_number (SCHARS (KVAR (current_kboard, echo_string)) - 2);
674 prev_char = Faref (KVAR (current_kboard, echo_string), idx);
676 idx = make_number (SCHARS (KVAR (current_kboard, echo_string)) - 1);
677 last_char = Faref (KVAR (current_kboard, echo_string), idx);
679 if (XINT (last_char) == '-' && XINT (prev_char) != ' ')
680 return;
683 /* Put a dash at the end of the buffer temporarily,
684 but make it go away when the next character is added. */
685 AUTO_STRING (dash, "-");
686 kset_echo_string (current_kboard,
687 concat2 (KVAR (current_kboard, echo_string), dash));
688 echo_now ();
691 /* Display the current echo string, and begin echoing if not already
692 doing so. */
694 static void
695 echo_now (void)
697 if (!current_kboard->immediate_echo)
699 ptrdiff_t i;
700 current_kboard->immediate_echo = 1;
702 for (i = 0; i < this_command_key_count; i++)
704 Lisp_Object c;
706 /* Set before_command_echo_length to the value that would
707 have been saved before the start of this subcommand in
708 command_loop_1, if we had already been echoing then. */
709 if (i == this_single_command_key_start)
710 before_command_echo_length = echo_length ();
712 c = AREF (this_command_keys, i);
713 if (! (EVENT_HAS_PARAMETERS (c)
714 && EQ (EVENT_HEAD_KIND (EVENT_HEAD (c)), Qmouse_movement)))
715 echo_char (c);
718 /* Set before_command_echo_length to the value that would
719 have been saved before the start of this subcommand in
720 command_loop_1, if we had already been echoing then. */
721 if (this_command_key_count == this_single_command_key_start)
722 before_command_echo_length = echo_length ();
724 /* Put a dash at the end to invite the user to type more. */
725 echo_dash ();
728 echoing = 1;
729 /* FIXME: Use call (Qmessage) so it can be advised (e.g. emacspeak). */
730 message3_nolog (KVAR (current_kboard, echo_string));
731 echoing = 0;
733 /* Record in what buffer we echoed, and from which kboard. */
734 echo_message_buffer = echo_area_buffer[0];
735 echo_kboard = current_kboard;
737 if (waiting_for_input && !NILP (Vquit_flag))
738 quit_throw_to_read_char (0);
741 /* Turn off echoing, for the start of a new command. */
743 void
744 cancel_echoing (void)
746 current_kboard->immediate_echo = 0;
747 current_kboard->echo_after_prompt = -1;
748 kset_echo_string (current_kboard, Qnil);
749 ok_to_echo_at_next_pause = NULL;
750 echo_kboard = NULL;
751 echo_message_buffer = Qnil;
754 /* Return the length of the current echo string. */
756 static ptrdiff_t
757 echo_length (void)
759 return (STRINGP (KVAR (current_kboard, echo_string))
760 ? SCHARS (KVAR (current_kboard, echo_string))
761 : 0);
764 /* Truncate the current echo message to its first LEN chars.
765 This and echo_char get used by read_key_sequence when the user
766 switches frames while entering a key sequence. */
768 static void
769 echo_truncate (ptrdiff_t nchars)
771 if (STRINGP (KVAR (current_kboard, echo_string)))
772 kset_echo_string (current_kboard,
773 Fsubstring (KVAR (current_kboard, echo_string),
774 make_number (0), make_number (nchars)));
775 truncate_echo_area (nchars);
779 /* Functions for manipulating this_command_keys. */
780 static void
781 add_command_key (Lisp_Object key)
783 #if 0 /* Not needed after we made Freset_this_command_lengths
784 do the job immediately. */
785 /* If reset-this-command-length was called recently, obey it now.
786 See the doc string of that function for an explanation of why. */
787 if (before_command_restore_flag)
789 this_command_key_count = before_command_key_count_1;
790 if (this_command_key_count < this_single_command_key_start)
791 this_single_command_key_start = this_command_key_count;
792 echo_truncate (before_command_echo_length_1);
793 before_command_restore_flag = 0;
795 #endif
797 if (this_command_key_count >= ASIZE (this_command_keys))
798 this_command_keys = larger_vector (this_command_keys, 1, -1);
800 ASET (this_command_keys, this_command_key_count, key);
801 ++this_command_key_count;
805 Lisp_Object
806 recursive_edit_1 (void)
808 ptrdiff_t count = SPECPDL_INDEX ();
809 Lisp_Object val;
811 if (command_loop_level > 0)
813 specbind (Qstandard_output, Qt);
814 specbind (Qstandard_input, Qt);
817 #ifdef HAVE_WINDOW_SYSTEM
818 /* The command loop has started an hourglass timer, so we have to
819 cancel it here, otherwise it will fire because the recursive edit
820 can take some time. Do not check for display_hourglass_p here,
821 because it could already be nil. */
822 cancel_hourglass ();
823 #endif
825 /* This function may have been called from a debugger called from
826 within redisplay, for instance by Edebugging a function called
827 from fontification-functions. We want to allow redisplay in
828 the debugging session.
830 The recursive edit is left with a `(throw exit ...)'. The `exit'
831 tag is not caught anywhere in redisplay, i.e. when we leave the
832 recursive edit, the original redisplay leading to the recursive
833 edit will be unwound. The outcome should therefore be safe. */
834 specbind (Qinhibit_redisplay, Qnil);
835 redisplaying_p = 0;
837 val = command_loop ();
838 if (EQ (val, Qt))
839 Fsignal (Qquit, Qnil);
840 /* Handle throw from read_minibuf when using minibuffer
841 while it's active but we're in another window. */
842 if (STRINGP (val))
843 xsignal1 (Qerror, val);
845 return unbind_to (count, Qnil);
848 /* When an auto-save happens, record the "time", and don't do again soon. */
850 void
851 record_auto_save (void)
853 last_auto_save = num_nonmacro_input_events;
856 /* Make an auto save happen as soon as possible at command level. */
858 #ifdef SIGDANGER
859 void
860 force_auto_save_soon (void)
862 last_auto_save = - auto_save_interval - 1;
864 record_asynch_buffer_change ();
866 #endif
868 DEFUN ("recursive-edit", Frecursive_edit, Srecursive_edit, 0, 0, "",
869 doc: /* Invoke the editor command loop recursively.
870 To get out of the recursive edit, a command can throw to `exit' -- for
871 instance `(throw 'exit nil)'.
872 If you throw a value other than t, `recursive-edit' returns normally
873 to the function that called it. Throwing a t value causes
874 `recursive-edit' to quit, so that control returns to the command loop
875 one level up.
877 This function is called by the editor initialization to begin editing. */)
878 (void)
880 ptrdiff_t count = SPECPDL_INDEX ();
881 Lisp_Object buffer;
883 /* If we enter while input is blocked, don't lock up here.
884 This may happen through the debugger during redisplay. */
885 if (input_blocked_p ())
886 return Qnil;
888 if (command_loop_level >= 0
889 && current_buffer != XBUFFER (XWINDOW (selected_window)->contents))
890 buffer = Fcurrent_buffer ();
891 else
892 buffer = Qnil;
894 /* Don't do anything interesting between the increment and the
895 record_unwind_protect! Otherwise, we could get distracted and
896 never decrement the counter again. */
897 command_loop_level++;
898 update_mode_lines = 17;
899 record_unwind_protect (recursive_edit_unwind, buffer);
901 /* If we leave recursive_edit_1 below with a `throw' for instance,
902 like it is done in the splash screen display, we have to
903 make sure that we restore single_kboard as command_loop_1
904 would have done if it were left normally. */
905 if (command_loop_level > 0)
906 temporarily_switch_to_single_kboard (SELECTED_FRAME ());
908 recursive_edit_1 ();
909 return unbind_to (count, Qnil);
912 void
913 recursive_edit_unwind (Lisp_Object buffer)
915 if (BUFFERP (buffer))
916 Fset_buffer (buffer);
918 command_loop_level--;
919 update_mode_lines = 18;
923 #if 0 /* These two functions are now replaced with
924 temporarily_switch_to_single_kboard. */
925 static void
926 any_kboard_state ()
928 #if 0 /* Theory: if there's anything in Vunread_command_events,
929 it will right away be read by read_key_sequence,
930 and then if we do switch KBOARDS, it will go into the side
931 queue then. So we don't need to do anything special here -- rms. */
932 if (CONSP (Vunread_command_events))
934 current_kboard->kbd_queue
935 = nconc2 (Vunread_command_events, current_kboard->kbd_queue);
936 current_kboard->kbd_queue_has_data = 1;
938 Vunread_command_events = Qnil;
939 #endif
940 single_kboard = 0;
943 /* Switch to the single-kboard state, making current_kboard
944 the only KBOARD from which further input is accepted. */
946 void
947 single_kboard_state ()
949 single_kboard = 1;
951 #endif
953 /* If we're in single_kboard state for kboard KBOARD,
954 get out of it. */
956 void
957 not_single_kboard_state (KBOARD *kboard)
959 if (kboard == current_kboard)
960 single_kboard = 0;
963 /* Maintain a stack of kboards, so other parts of Emacs
964 can switch temporarily to the kboard of a given frame
965 and then revert to the previous status. */
967 struct kboard_stack
969 KBOARD *kboard;
970 struct kboard_stack *next;
973 static struct kboard_stack *kboard_stack;
975 void
976 push_kboard (struct kboard *k)
978 struct kboard_stack *p = xmalloc (sizeof *p);
980 p->next = kboard_stack;
981 p->kboard = current_kboard;
982 kboard_stack = p;
984 current_kboard = k;
987 void
988 pop_kboard (void)
990 struct terminal *t;
991 struct kboard_stack *p = kboard_stack;
992 bool found = 0;
993 for (t = terminal_list; t; t = t->next_terminal)
995 if (t->kboard == p->kboard)
997 current_kboard = p->kboard;
998 found = 1;
999 break;
1002 if (!found)
1004 /* The terminal we remembered has been deleted. */
1005 current_kboard = FRAME_KBOARD (SELECTED_FRAME ());
1006 single_kboard = 0;
1008 kboard_stack = p->next;
1009 xfree (p);
1012 /* Switch to single_kboard mode, making current_kboard the only KBOARD
1013 from which further input is accepted. If F is non-nil, set its
1014 KBOARD as the current keyboard.
1016 This function uses record_unwind_protect_int to return to the previous
1017 state later.
1019 If Emacs is already in single_kboard mode, and F's keyboard is
1020 locked, then this function will throw an error. */
1022 void
1023 temporarily_switch_to_single_kboard (struct frame *f)
1025 bool was_locked = single_kboard;
1026 if (was_locked)
1028 if (f != NULL && FRAME_KBOARD (f) != current_kboard)
1029 /* We can not switch keyboards while in single_kboard mode.
1030 In rare cases, Lisp code may call `recursive-edit' (or
1031 `read-minibuffer' or `y-or-n-p') after it switched to a
1032 locked frame. For example, this is likely to happen
1033 when server.el connects to a new terminal while Emacs is in
1034 single_kboard mode. It is best to throw an error instead
1035 of presenting the user with a frozen screen. */
1036 error ("Terminal %d is locked, cannot read from it",
1037 FRAME_TERMINAL (f)->id);
1038 else
1039 /* This call is unnecessary, but helps
1040 `restore_kboard_configuration' discover if somebody changed
1041 `current_kboard' behind our back. */
1042 push_kboard (current_kboard);
1044 else if (f != NULL)
1045 current_kboard = FRAME_KBOARD (f);
1046 single_kboard = 1;
1047 record_unwind_protect_int (restore_kboard_configuration, was_locked);
1050 #if 0 /* This function is not needed anymore. */
1051 void
1052 record_single_kboard_state ()
1054 if (single_kboard)
1055 push_kboard (current_kboard);
1056 record_unwind_protect_int (restore_kboard_configuration, single_kboard);
1058 #endif
1060 static void
1061 restore_kboard_configuration (int was_locked)
1063 single_kboard = was_locked;
1064 if (was_locked)
1066 struct kboard *prev = current_kboard;
1067 pop_kboard ();
1068 /* The pop should not change the kboard. */
1069 if (single_kboard && current_kboard != prev)
1070 emacs_abort ();
1075 /* Handle errors that are not handled at inner levels
1076 by printing an error message and returning to the editor command loop. */
1078 static Lisp_Object
1079 cmd_error (Lisp_Object data)
1081 Lisp_Object old_level, old_length;
1082 char macroerror[sizeof "After..kbd macro iterations: "
1083 + INT_STRLEN_BOUND (EMACS_INT)];
1085 #ifdef HAVE_WINDOW_SYSTEM
1086 if (display_hourglass_p)
1087 cancel_hourglass ();
1088 #endif
1090 if (!NILP (executing_kbd_macro))
1092 if (executing_kbd_macro_iterations == 1)
1093 sprintf (macroerror, "After 1 kbd macro iteration: ");
1094 else
1095 sprintf (macroerror, "After %"pI"d kbd macro iterations: ",
1096 executing_kbd_macro_iterations);
1098 else
1099 *macroerror = 0;
1101 Vstandard_output = Qt;
1102 Vstandard_input = Qt;
1103 Vexecuting_kbd_macro = Qnil;
1104 executing_kbd_macro = Qnil;
1105 kset_prefix_arg (current_kboard, Qnil);
1106 kset_last_prefix_arg (current_kboard, Qnil);
1107 cancel_echoing ();
1109 /* Avoid unquittable loop if data contains a circular list. */
1110 old_level = Vprint_level;
1111 old_length = Vprint_length;
1112 XSETFASTINT (Vprint_level, 10);
1113 XSETFASTINT (Vprint_length, 10);
1114 cmd_error_internal (data, macroerror);
1115 Vprint_level = old_level;
1116 Vprint_length = old_length;
1118 Vquit_flag = Qnil;
1119 Vinhibit_quit = Qnil;
1121 return make_number (0);
1124 /* Take actions on handling an error. DATA is the data that describes
1125 the error.
1127 CONTEXT is a C-string containing ASCII characters only which
1128 describes the context in which the error happened. If we need to
1129 generalize CONTEXT to allow multibyte characters, make it a Lisp
1130 string. */
1132 void
1133 cmd_error_internal (Lisp_Object data, const char *context)
1135 /* The immediate context is not interesting for Quits,
1136 since they are asynchronous. */
1137 if (EQ (XCAR (data), Qquit))
1138 Vsignaling_function = Qnil;
1140 Vquit_flag = Qnil;
1141 Vinhibit_quit = Qt;
1143 /* Use user's specified output function if any. */
1144 if (!NILP (Vcommand_error_function))
1145 call3 (Vcommand_error_function, data,
1146 context ? build_string (context) : empty_unibyte_string,
1147 Vsignaling_function);
1149 Vsignaling_function = Qnil;
1152 DEFUN ("command-error-default-function", Fcommand_error_default_function,
1153 Scommand_error_default_function, 3, 3, 0,
1154 doc: /* Produce default output for unhandled error message.
1155 Default value of `command-error-function'. */)
1156 (Lisp_Object data, Lisp_Object context, Lisp_Object signal)
1158 struct frame *sf = SELECTED_FRAME ();
1160 CHECK_STRING (context);
1162 /* If the window system or terminal frame hasn't been initialized
1163 yet, or we're not interactive, write the message to stderr and exit. */
1164 if (!sf->glyphs_initialized_p
1165 /* The initial frame is a special non-displaying frame. It
1166 will be current in daemon mode when there are no frames
1167 to display, and in non-daemon mode before the real frame
1168 has finished initializing. If an error is thrown in the
1169 latter case while creating the frame, then the frame
1170 will never be displayed, so the safest thing to do is
1171 write to stderr and quit. In daemon mode, there are
1172 many other potential errors that do not prevent frames
1173 from being created, so continuing as normal is better in
1174 that case. */
1175 || (!IS_DAEMON && FRAME_INITIAL_P (sf))
1176 || noninteractive)
1178 print_error_message (data, Qexternal_debugging_output,
1179 SSDATA (context), signal);
1180 Fterpri (Qexternal_debugging_output, Qnil);
1181 Fkill_emacs (make_number (-1));
1183 else
1185 clear_message (1, 0);
1186 Fdiscard_input ();
1187 message_log_maybe_newline ();
1188 bitch_at_user ();
1190 print_error_message (data, Qt, SSDATA (context), signal);
1192 return Qnil;
1195 static Lisp_Object command_loop_2 (Lisp_Object);
1196 static Lisp_Object top_level_1 (Lisp_Object);
1198 /* Entry to editor-command-loop.
1199 This level has the catches for exiting/returning to editor command loop.
1200 It returns nil to exit recursive edit, t to abort it. */
1202 Lisp_Object
1203 command_loop (void)
1205 #ifdef HAVE_STACK_OVERFLOW_HANDLING
1206 /* At least on GNU/Linux, saving signal mask is important here. */
1207 if (sigsetjmp (return_to_command_loop, 1) != 0)
1209 /* Comes here from handle_sigsegv, see sysdep.c. */
1210 init_eval ();
1211 Vinternal__top_level_message = recover_top_level_message;
1213 else
1214 Vinternal__top_level_message = regular_top_level_message;
1215 #endif /* HAVE_STACK_OVERFLOW_HANDLING */
1216 if (command_loop_level > 0 || minibuf_level > 0)
1218 Lisp_Object val;
1219 val = internal_catch (Qexit, command_loop_2, Qnil);
1220 executing_kbd_macro = Qnil;
1221 return val;
1223 else
1224 while (1)
1226 internal_catch (Qtop_level, top_level_1, Qnil);
1227 internal_catch (Qtop_level, command_loop_2, Qnil);
1228 executing_kbd_macro = Qnil;
1230 /* End of file in -batch run causes exit here. */
1231 if (noninteractive)
1232 Fkill_emacs (Qt);
1236 /* Here we catch errors in execution of commands within the
1237 editing loop, and reenter the editing loop.
1238 When there is an error, cmd_error runs and returns a non-nil
1239 value to us. A value of nil means that command_loop_1 itself
1240 returned due to end of file (or end of kbd macro). */
1242 static Lisp_Object
1243 command_loop_2 (Lisp_Object ignore)
1245 register Lisp_Object val;
1248 val = internal_condition_case (command_loop_1, Qerror, cmd_error);
1249 while (!NILP (val));
1251 return Qnil;
1254 static Lisp_Object
1255 top_level_2 (void)
1257 return Feval (Vtop_level, Qnil);
1260 static Lisp_Object
1261 top_level_1 (Lisp_Object ignore)
1263 /* On entry to the outer level, run the startup file. */
1264 if (!NILP (Vtop_level))
1265 internal_condition_case (top_level_2, Qerror, cmd_error);
1266 else if (!NILP (Vpurify_flag))
1267 message1 ("Bare impure Emacs (standard Lisp code not loaded)");
1268 else
1269 message1 ("Bare Emacs (standard Lisp code not loaded)");
1270 return Qnil;
1273 DEFUN ("top-level", Ftop_level, Stop_level, 0, 0, "",
1274 doc: /* Exit all recursive editing levels.
1275 This also exits all active minibuffers. */)
1276 (void)
1278 #ifdef HAVE_WINDOW_SYSTEM
1279 if (display_hourglass_p)
1280 cancel_hourglass ();
1281 #endif
1283 /* Unblock input if we enter with input blocked. This may happen if
1284 redisplay traps e.g. during tool-bar update with input blocked. */
1285 totally_unblock_input ();
1287 Fthrow (Qtop_level, Qnil);
1290 static _Noreturn void
1291 user_error (const char *msg)
1293 xsignal1 (Quser_error, build_string (msg));
1296 /* _Noreturn will be added to prototype by make-docfile. */
1297 DEFUN ("exit-recursive-edit", Fexit_recursive_edit, Sexit_recursive_edit, 0, 0, "",
1298 doc: /* Exit from the innermost recursive edit or minibuffer. */)
1299 (void)
1301 if (command_loop_level > 0 || minibuf_level > 0)
1302 Fthrow (Qexit, Qnil);
1304 user_error ("No recursive edit is in progress");
1307 /* _Noreturn will be added to prototype by make-docfile. */
1308 DEFUN ("abort-recursive-edit", Fabort_recursive_edit, Sabort_recursive_edit, 0, 0, "",
1309 doc: /* Abort the command that requested this recursive edit or minibuffer input. */)
1310 (void)
1312 if (command_loop_level > 0 || minibuf_level > 0)
1313 Fthrow (Qexit, Qt);
1315 user_error ("No recursive edit is in progress");
1318 /* Restore mouse tracking enablement. See Ftrack_mouse for the only use
1319 of this function. */
1321 static void
1322 tracking_off (Lisp_Object old_value)
1324 do_mouse_tracking = old_value;
1325 if (NILP (old_value))
1327 /* Redisplay may have been preempted because there was input
1328 available, and it assumes it will be called again after the
1329 input has been processed. If the only input available was
1330 the sort that we have just disabled, then we need to call
1331 redisplay. */
1332 if (!readable_events (READABLE_EVENTS_DO_TIMERS_NOW))
1334 redisplay_preserve_echo_area (6);
1335 get_input_pending (READABLE_EVENTS_DO_TIMERS_NOW);
1340 DEFUN ("internal--track-mouse", Ftrack_mouse, Strack_mouse, 1, 1, 0,
1341 doc: /* Call BODYFUN with mouse movement events enabled. */)
1342 (Lisp_Object bodyfun)
1344 ptrdiff_t count = SPECPDL_INDEX ();
1345 Lisp_Object val;
1347 record_unwind_protect (tracking_off, do_mouse_tracking);
1349 do_mouse_tracking = Qt;
1351 val = call0 (bodyfun);
1352 return unbind_to (count, val);
1355 /* If mouse has moved on some frame, return one of those frames.
1357 Return 0 otherwise.
1359 If ignore_mouse_drag_p is non-zero, ignore (implicit) mouse movement
1360 after resizing the tool-bar window. */
1362 bool ignore_mouse_drag_p;
1364 static struct frame *
1365 some_mouse_moved (void)
1367 Lisp_Object tail, frame;
1369 if (ignore_mouse_drag_p)
1371 /* ignore_mouse_drag_p = 0; */
1372 return 0;
1375 FOR_EACH_FRAME (tail, frame)
1377 if (XFRAME (frame)->mouse_moved)
1378 return XFRAME (frame);
1381 return 0;
1385 /* This is the actual command reading loop,
1386 sans error-handling encapsulation. */
1388 static int read_key_sequence (Lisp_Object *, int, Lisp_Object,
1389 bool, bool, bool, bool);
1390 static void adjust_point_for_property (ptrdiff_t, bool);
1392 /* The last boundary auto-added to buffer-undo-list. */
1393 Lisp_Object last_undo_boundary;
1395 /* FIXME: This is wrong rather than test window-system, we should call
1396 a new set-selection, which will then dispatch to x-set-selection, or
1397 tty-set-selection, or w32-set-selection, ... */
1399 Lisp_Object
1400 command_loop_1 (void)
1402 Lisp_Object cmd;
1403 Lisp_Object keybuf[30];
1404 int i;
1405 EMACS_INT prev_modiff = 0;
1406 struct buffer *prev_buffer = NULL;
1407 bool already_adjusted = 0;
1409 kset_prefix_arg (current_kboard, Qnil);
1410 kset_last_prefix_arg (current_kboard, Qnil);
1411 Vdeactivate_mark = Qnil;
1412 waiting_for_input = 0;
1413 cancel_echoing ();
1415 this_command_key_count = 0;
1416 this_command_key_count_reset = 0;
1417 this_single_command_key_start = 0;
1419 if (NILP (Vmemory_full))
1421 /* Make sure this hook runs after commands that get errors and
1422 throw to top level. */
1423 /* Note that the value cell will never directly contain nil
1424 if the symbol is a local variable. */
1425 if (!NILP (Vpost_command_hook) && !NILP (Vrun_hooks))
1426 safe_run_hooks (Qpost_command_hook);
1428 /* If displaying a message, resize the echo area window to fit
1429 that message's size exactly. */
1430 if (!NILP (echo_area_buffer[0]))
1431 resize_echo_area_exactly ();
1433 /* If there are warnings waiting, process them. */
1434 if (!NILP (Vdelayed_warnings_list))
1435 safe_run_hooks (Qdelayed_warnings_hook);
1437 if (!NILP (Vdeferred_action_list))
1438 safe_run_hooks (Qdeferred_action_function);
1441 /* Do this after running Vpost_command_hook, for consistency. */
1442 kset_last_command (current_kboard, Vthis_command);
1443 kset_real_last_command (current_kboard, Vreal_this_command);
1444 if (!CONSP (last_command_event))
1445 kset_last_repeatable_command (current_kboard, Vreal_this_command);
1447 while (1)
1449 if (! FRAME_LIVE_P (XFRAME (selected_frame)))
1450 Fkill_emacs (Qnil);
1452 /* Make sure the current window's buffer is selected. */
1453 set_buffer_internal (XBUFFER (XWINDOW (selected_window)->contents));
1455 /* Display any malloc warning that just came out. Use while because
1456 displaying one warning can cause another. */
1458 while (pending_malloc_warning)
1459 display_malloc_warning ();
1461 Vdeactivate_mark = Qnil;
1463 /* Don't ignore mouse movements for more than a single command
1464 loop. (This flag is set in xdisp.c whenever the tool bar is
1465 resized, because the resize moves text up or down, and would
1466 generate false mouse drag events if we don't ignore them.) */
1467 ignore_mouse_drag_p = 0;
1469 /* If minibuffer on and echo area in use,
1470 wait a short time and redraw minibuffer. */
1472 if (minibuf_level
1473 && !NILP (echo_area_buffer[0])
1474 && EQ (minibuf_window, echo_area_window)
1475 && NUMBERP (Vminibuffer_message_timeout))
1477 /* Bind inhibit-quit to t so that C-g gets read in
1478 rather than quitting back to the minibuffer. */
1479 ptrdiff_t count = SPECPDL_INDEX ();
1480 specbind (Qinhibit_quit, Qt);
1482 sit_for (Vminibuffer_message_timeout, 0, 2);
1484 /* Clear the echo area. */
1485 message1 (0);
1486 safe_run_hooks (Qecho_area_clear_hook);
1488 unbind_to (count, Qnil);
1490 /* If a C-g came in before, treat it as input now. */
1491 if (!NILP (Vquit_flag))
1493 Vquit_flag = Qnil;
1494 Vunread_command_events = list1 (make_number (quit_char));
1498 /* If it has changed current-menubar from previous value,
1499 really recompute the menubar from the value. */
1500 if (! NILP (Vlucid_menu_bar_dirty_flag)
1501 && !NILP (Ffboundp (Qrecompute_lucid_menubar)))
1502 call0 (Qrecompute_lucid_menubar);
1504 before_command_key_count = this_command_key_count;
1505 before_command_echo_length = echo_length ();
1507 Vthis_command = Qnil;
1508 Vreal_this_command = Qnil;
1509 Vthis_original_command = Qnil;
1510 Vthis_command_keys_shift_translated = Qnil;
1512 /* Read next key sequence; i gets its length. */
1513 i = read_key_sequence (keybuf, ARRAYELTS (keybuf),
1514 Qnil, 0, 1, 1, 0);
1516 /* A filter may have run while we were reading the input. */
1517 if (! FRAME_LIVE_P (XFRAME (selected_frame)))
1518 Fkill_emacs (Qnil);
1519 set_buffer_internal (XBUFFER (XWINDOW (selected_window)->contents));
1521 ++num_input_keys;
1523 /* Now we have read a key sequence of length I,
1524 or else I is 0 and we found end of file. */
1526 if (i == 0) /* End of file -- happens only in */
1527 return Qnil; /* a kbd macro, at the end. */
1528 /* -1 means read_key_sequence got a menu that was rejected.
1529 Just loop around and read another command. */
1530 if (i == -1)
1532 cancel_echoing ();
1533 this_command_key_count = 0;
1534 this_command_key_count_reset = 0;
1535 this_single_command_key_start = 0;
1536 goto finalize;
1539 last_command_event = keybuf[i - 1];
1541 /* If the previous command tried to force a specific window-start,
1542 forget about that, in case this command moves point far away
1543 from that position. But also throw away beg_unchanged and
1544 end_unchanged information in that case, so that redisplay will
1545 update the whole window properly. */
1546 if (XWINDOW (selected_window)->force_start)
1548 struct buffer *b;
1549 XWINDOW (selected_window)->force_start = 0;
1550 b = XBUFFER (XWINDOW (selected_window)->contents);
1551 BUF_BEG_UNCHANGED (b) = BUF_END_UNCHANGED (b) = 0;
1554 cmd = read_key_sequence_cmd;
1555 if (!NILP (Vexecuting_kbd_macro))
1557 if (!NILP (Vquit_flag))
1559 Vexecuting_kbd_macro = Qt;
1560 QUIT; /* Make some noise. */
1561 /* Will return since macro now empty. */
1565 /* Do redisplay processing after this command except in special
1566 cases identified below. */
1567 prev_buffer = current_buffer;
1568 prev_modiff = MODIFF;
1569 last_point_position = PT;
1571 /* By default, we adjust point to a boundary of a region that
1572 has such a property that should be treated intangible
1573 (e.g. composition, display). But, some commands will set
1574 this variable differently. */
1575 Vdisable_point_adjustment = Qnil;
1577 /* Process filters and timers may have messed with deactivate-mark.
1578 reset it before we execute the command. */
1579 Vdeactivate_mark = Qnil;
1581 /* Remap command through active keymaps. */
1582 Vthis_original_command = cmd;
1583 if (!NILP (read_key_sequence_remapped))
1584 cmd = read_key_sequence_remapped;
1586 /* Execute the command. */
1589 total_keys += total_keys < NUM_RECENT_KEYS;
1590 ASET (recent_keys, recent_keys_index,
1591 Fcons (Qnil, cmd));
1592 if (++recent_keys_index >= NUM_RECENT_KEYS)
1593 recent_keys_index = 0;
1595 Vthis_command = cmd;
1596 Vreal_this_command = cmd;
1597 safe_run_hooks (Qpre_command_hook);
1599 already_adjusted = 0;
1601 if (NILP (Vthis_command))
1602 /* nil means key is undefined. */
1603 call0 (Qundefined);
1604 else
1606 /* Here for a command that isn't executed directly. */
1608 #ifdef HAVE_WINDOW_SYSTEM
1609 ptrdiff_t scount = SPECPDL_INDEX ();
1611 if (display_hourglass_p
1612 && NILP (Vexecuting_kbd_macro))
1614 record_unwind_protect_void (cancel_hourglass);
1615 start_hourglass ();
1617 #endif
1619 if (NILP (KVAR (current_kboard, Vprefix_arg))) /* FIXME: Why? --Stef */
1621 Lisp_Object undo = BVAR (current_buffer, undo_list);
1622 Fundo_boundary ();
1623 last_undo_boundary
1624 = (EQ (undo, BVAR (current_buffer, undo_list))
1625 ? Qnil : BVAR (current_buffer, undo_list));
1627 call1 (Qcommand_execute, Vthis_command);
1629 #ifdef HAVE_WINDOW_SYSTEM
1630 /* Do not check display_hourglass_p here, because
1631 `command-execute' could change it, but we should cancel
1632 hourglass cursor anyway.
1633 But don't cancel the hourglass within a macro
1634 just because a command in the macro finishes. */
1635 if (NILP (Vexecuting_kbd_macro))
1636 unbind_to (scount, Qnil);
1637 #endif
1639 kset_last_prefix_arg (current_kboard, Vcurrent_prefix_arg);
1641 safe_run_hooks (Qpost_command_hook);
1643 /* If displaying a message, resize the echo area window to fit
1644 that message's size exactly. */
1645 if (!NILP (echo_area_buffer[0]))
1646 resize_echo_area_exactly ();
1648 /* If there are warnings waiting, process them. */
1649 if (!NILP (Vdelayed_warnings_list))
1650 safe_run_hooks (Qdelayed_warnings_hook);
1652 safe_run_hooks (Qdeferred_action_function);
1654 /* If there is a prefix argument,
1655 1) We don't want Vlast_command to be ``universal-argument''
1656 (that would be dumb), so don't set Vlast_command,
1657 2) we want to leave echoing on so that the prefix will be
1658 echoed as part of this key sequence, so don't call
1659 cancel_echoing, and
1660 3) we want to leave this_command_key_count non-zero, so that
1661 read_char will realize that it is re-reading a character, and
1662 not echo it a second time.
1664 If the command didn't actually create a prefix arg,
1665 but is merely a frame event that is transparent to prefix args,
1666 then the above doesn't apply. */
1667 if (NILP (KVAR (current_kboard, Vprefix_arg))
1668 || CONSP (last_command_event))
1670 kset_last_command (current_kboard, Vthis_command);
1671 kset_real_last_command (current_kboard, Vreal_this_command);
1672 if (!CONSP (last_command_event))
1673 kset_last_repeatable_command (current_kboard, Vreal_this_command);
1674 cancel_echoing ();
1675 this_command_key_count = 0;
1676 this_command_key_count_reset = 0;
1677 this_single_command_key_start = 0;
1680 if (!NILP (BVAR (current_buffer, mark_active))
1681 && !NILP (Vrun_hooks))
1683 /* In Emacs 22, setting transient-mark-mode to `only' was a
1684 way of turning it on for just one command. This usage is
1685 obsolete, but support it anyway. */
1686 if (EQ (Vtransient_mark_mode, Qidentity))
1687 Vtransient_mark_mode = Qnil;
1688 else if (EQ (Vtransient_mark_mode, Qonly))
1689 Vtransient_mark_mode = Qidentity;
1691 if (!NILP (Vdeactivate_mark))
1692 /* If `select-active-regions' is non-nil, this call to
1693 `deactivate-mark' also sets the PRIMARY selection. */
1694 call0 (Qdeactivate_mark);
1695 else
1697 /* Even if not deactivating the mark, set PRIMARY if
1698 `select-active-regions' is non-nil. */
1699 if (!NILP (Fwindow_system (Qnil))
1700 /* Even if mark_active is non-nil, the actual buffer
1701 marker may not have been set yet (Bug#7044). */
1702 && XMARKER (BVAR (current_buffer, mark))->buffer
1703 && (EQ (Vselect_active_regions, Qonly)
1704 ? EQ (CAR_SAFE (Vtransient_mark_mode), Qonly)
1705 : (!NILP (Vselect_active_regions)
1706 && !NILP (Vtransient_mark_mode)))
1707 && NILP (Fmemq (Vthis_command,
1708 Vselection_inhibit_update_commands)))
1710 Lisp_Object txt
1711 = call1 (Fsymbol_value (Qregion_extract_function), Qnil);
1712 if (XINT (Flength (txt)) > 0)
1713 /* Don't set empty selections. */
1714 call2 (Qgui_set_selection, QPRIMARY, txt);
1717 if (current_buffer != prev_buffer || MODIFF != prev_modiff)
1719 Lisp_Object hook = intern ("activate-mark-hook");
1720 Frun_hooks (1, &hook);
1724 Vsaved_region_selection = Qnil;
1727 finalize:
1729 if (current_buffer == prev_buffer
1730 && last_point_position != PT
1731 && NILP (Vdisable_point_adjustment)
1732 && NILP (Vglobal_disable_point_adjustment))
1734 if (last_point_position > BEGV
1735 && last_point_position < ZV
1736 && (composition_adjust_point (last_point_position,
1737 last_point_position)
1738 != last_point_position))
1739 /* The last point was temporarily set within a grapheme
1740 cluster to prevent automatic composition. To recover
1741 the automatic composition, we must update the
1742 display. */
1743 windows_or_buffers_changed = 21;
1744 if (!already_adjusted)
1745 adjust_point_for_property (last_point_position,
1746 MODIFF != prev_modiff);
1749 /* Install chars successfully executed in kbd macro. */
1751 if (!NILP (KVAR (current_kboard, defining_kbd_macro))
1752 && NILP (KVAR (current_kboard, Vprefix_arg)))
1753 finalize_kbd_macro_chars ();
1757 Lisp_Object
1758 read_menu_command (void)
1760 Lisp_Object keybuf[30];
1761 ptrdiff_t count = SPECPDL_INDEX ();
1762 int i;
1764 /* We don't want to echo the keystrokes while navigating the
1765 menus. */
1766 specbind (Qecho_keystrokes, make_number (0));
1768 i = read_key_sequence (keybuf, ARRAYELTS (keybuf),
1769 Qnil, 0, 1, 1, 1);
1771 unbind_to (count, Qnil);
1773 if (! FRAME_LIVE_P (XFRAME (selected_frame)))
1774 Fkill_emacs (Qnil);
1775 if (i == 0 || i == -1)
1776 return Qt;
1778 return read_key_sequence_cmd;
1781 /* Adjust point to a boundary of a region that has such a property
1782 that should be treated intangible. For the moment, we check
1783 `composition', `display' and `invisible' properties.
1784 LAST_PT is the last position of point. */
1786 static void
1787 adjust_point_for_property (ptrdiff_t last_pt, bool modified)
1789 ptrdiff_t beg, end;
1790 Lisp_Object val, overlay, tmp;
1791 /* When called after buffer modification, we should temporarily
1792 suppress the point adjustment for automatic composition so that a
1793 user can keep inserting another character at point or keep
1794 deleting characters around point. */
1795 bool check_composition = ! modified, check_display = 1, check_invisible = 1;
1796 ptrdiff_t orig_pt = PT;
1798 /* FIXME: cycling is probably not necessary because these properties
1799 can't be usefully combined anyway. */
1800 while (check_composition || check_display || check_invisible)
1802 /* FIXME: check `intangible'. */
1803 if (check_composition
1804 && PT > BEGV && PT < ZV
1805 && (beg = composition_adjust_point (last_pt, PT)) != PT)
1807 SET_PT (beg);
1808 check_display = check_invisible = 1;
1810 check_composition = 0;
1811 if (check_display
1812 && PT > BEGV && PT < ZV
1813 && !NILP (val = get_char_property_and_overlay
1814 (make_number (PT), Qdisplay, Qnil, &overlay))
1815 && display_prop_intangible_p (val, overlay, PT, PT_BYTE)
1816 && (!OVERLAYP (overlay)
1817 ? get_property_and_range (PT, Qdisplay, &val, &beg, &end, Qnil)
1818 : (beg = OVERLAY_POSITION (OVERLAY_START (overlay)),
1819 end = OVERLAY_POSITION (OVERLAY_END (overlay))))
1820 && (beg < PT /* && end > PT <- It's always the case. */
1821 || (beg <= PT && STRINGP (val) && SCHARS (val) == 0)))
1823 eassert (end > PT);
1824 SET_PT (PT < last_pt
1825 ? (STRINGP (val) && SCHARS (val) == 0
1826 ? max (beg - 1, BEGV)
1827 : beg)
1828 : end);
1829 check_composition = check_invisible = 1;
1831 check_display = 0;
1832 if (check_invisible && PT > BEGV && PT < ZV)
1834 int inv;
1835 bool ellipsis = 0;
1836 beg = end = PT;
1838 /* Find boundaries `beg' and `end' of the invisible area, if any. */
1839 while (end < ZV
1840 #if 0
1841 /* FIXME: We should stop if we find a spot between
1842 two runs of `invisible' where inserted text would
1843 be visible. This is important when we have two
1844 invisible boundaries that enclose an area: if the
1845 area is empty, we need this test in order to make
1846 it possible to place point in the middle rather
1847 than skip both boundaries. However, this code
1848 also stops anywhere in a non-sticky text-property,
1849 which breaks (e.g.) Org mode. */
1850 && (val = Fget_pos_property (make_number (end),
1851 Qinvisible, Qnil),
1852 TEXT_PROP_MEANS_INVISIBLE (val))
1853 #endif
1854 && !NILP (val = get_char_property_and_overlay
1855 (make_number (end), Qinvisible, Qnil, &overlay))
1856 && (inv = TEXT_PROP_MEANS_INVISIBLE (val)))
1858 ellipsis = ellipsis || inv > 1
1859 || (OVERLAYP (overlay)
1860 && (!NILP (Foverlay_get (overlay, Qafter_string))
1861 || !NILP (Foverlay_get (overlay, Qbefore_string))));
1862 tmp = Fnext_single_char_property_change
1863 (make_number (end), Qinvisible, Qnil, Qnil);
1864 end = NATNUMP (tmp) ? XFASTINT (tmp) : ZV;
1866 while (beg > BEGV
1867 #if 0
1868 && (val = Fget_pos_property (make_number (beg),
1869 Qinvisible, Qnil),
1870 TEXT_PROP_MEANS_INVISIBLE (val))
1871 #endif
1872 && !NILP (val = get_char_property_and_overlay
1873 (make_number (beg - 1), Qinvisible, Qnil, &overlay))
1874 && (inv = TEXT_PROP_MEANS_INVISIBLE (val)))
1876 ellipsis = ellipsis || inv > 1
1877 || (OVERLAYP (overlay)
1878 && (!NILP (Foverlay_get (overlay, Qafter_string))
1879 || !NILP (Foverlay_get (overlay, Qbefore_string))));
1880 tmp = Fprevious_single_char_property_change
1881 (make_number (beg), Qinvisible, Qnil, Qnil);
1882 beg = NATNUMP (tmp) ? XFASTINT (tmp) : BEGV;
1885 /* Move away from the inside area. */
1886 if (beg < PT && end > PT)
1888 SET_PT ((orig_pt == PT && (last_pt < beg || last_pt > end))
1889 /* We haven't moved yet (so we don't need to fear
1890 infinite-looping) and we were outside the range
1891 before (so either end of the range still corresponds
1892 to a move in the right direction): pretend we moved
1893 less than we actually did, so that we still have
1894 more freedom below in choosing which end of the range
1895 to go to. */
1896 ? (orig_pt = -1, PT < last_pt ? end : beg)
1897 /* We either have moved already or the last point
1898 was already in the range: we don't get to choose
1899 which end of the range we have to go to. */
1900 : (PT < last_pt ? beg : end));
1901 check_composition = check_display = 1;
1903 #if 0 /* This assertion isn't correct, because SET_PT may end up setting
1904 the point to something other than its argument, due to
1905 point-motion hooks, intangibility, etc. */
1906 eassert (PT == beg || PT == end);
1907 #endif
1909 /* Pretend the area doesn't exist if the buffer is not
1910 modified. */
1911 if (!modified && !ellipsis && beg < end)
1913 if (last_pt == beg && PT == end && end < ZV)
1914 (check_composition = check_display = 1, SET_PT (end + 1));
1915 else if (last_pt == end && PT == beg && beg > BEGV)
1916 (check_composition = check_display = 1, SET_PT (beg - 1));
1917 else if (PT == ((PT < last_pt) ? beg : end))
1918 /* We've already moved as far as we can. Trying to go
1919 to the other end would mean moving backwards and thus
1920 could lead to an infinite loop. */
1922 else if (val = Fget_pos_property (make_number (PT),
1923 Qinvisible, Qnil),
1924 TEXT_PROP_MEANS_INVISIBLE (val)
1925 && (val = (Fget_pos_property
1926 (make_number (PT == beg ? end : beg),
1927 Qinvisible, Qnil)),
1928 !TEXT_PROP_MEANS_INVISIBLE (val)))
1929 (check_composition = check_display = 1,
1930 SET_PT (PT == beg ? end : beg));
1933 check_invisible = 0;
1937 /* Subroutine for safe_run_hooks: run the hook, which is ARGS[1]. */
1939 static Lisp_Object
1940 safe_run_hooks_1 (ptrdiff_t nargs, Lisp_Object *args)
1942 eassert (nargs == 2);
1943 return call0 (args[1]);
1946 /* Subroutine for safe_run_hooks: handle an error by clearing out the function
1947 from the hook. */
1949 static Lisp_Object
1950 safe_run_hooks_error (Lisp_Object error, ptrdiff_t nargs, Lisp_Object *args)
1952 eassert (nargs == 2);
1953 AUTO_STRING (format, "Error in %s (%S): %S");
1954 Lisp_Object hook = args[0];
1955 Lisp_Object fun = args[1];
1956 Fmessage (4, (Lisp_Object []) {format, hook, fun, error});
1958 if (SYMBOLP (hook))
1960 Lisp_Object val;
1961 bool found = 0;
1962 Lisp_Object newval = Qnil;
1963 for (val = find_symbol_value (hook); CONSP (val); val = XCDR (val))
1964 if (EQ (fun, XCAR (val)))
1965 found = 1;
1966 else
1967 newval = Fcons (XCAR (val), newval);
1968 if (found)
1969 return Fset (hook, Fnreverse (newval));
1970 /* Not found in the local part of the hook. Let's look at the global
1971 part. */
1972 newval = Qnil;
1973 for (val = (NILP (Fdefault_boundp (hook)) ? Qnil
1974 : Fdefault_value (hook));
1975 CONSP (val); val = XCDR (val))
1976 if (EQ (fun, XCAR (val)))
1977 found = 1;
1978 else
1979 newval = Fcons (XCAR (val), newval);
1980 if (found)
1981 return Fset_default (hook, Fnreverse (newval));
1983 return Qnil;
1986 static Lisp_Object
1987 safe_run_hook_funcall (ptrdiff_t nargs, Lisp_Object *args)
1989 Lisp_Object iargs[2];
1991 eassert (nargs == 2);
1992 /* Yes, run_hook_with_args works this way. */
1993 iargs[0] = args[1];
1994 iargs[1] = args[0];
1995 internal_condition_case_n (safe_run_hooks_1, 2, iargs,
1996 Qt, safe_run_hooks_error);
1997 return Qnil;
2000 /* If we get an error while running the hook, cause the hook variable
2001 to be nil. Also inhibit quits, so that C-g won't cause the hook
2002 to mysteriously evaporate. */
2004 void
2005 safe_run_hooks (Lisp_Object hook)
2007 Lisp_Object args[2];
2008 struct gcpro gcpro1;
2009 ptrdiff_t count = SPECPDL_INDEX ();
2011 args[0] = hook;
2012 args[1] = hook;
2014 GCPRO1 (hook);
2015 specbind (Qinhibit_quit, Qt);
2016 run_hook_with_args (2, args, safe_run_hook_funcall);
2017 unbind_to (count, Qnil);
2018 UNGCPRO;
2022 /* Nonzero means polling for input is temporarily suppressed. */
2024 int poll_suppress_count;
2027 #ifdef POLL_FOR_INPUT
2029 /* Asynchronous timer for polling. */
2031 static struct atimer *poll_timer;
2033 /* Poll for input, so that we catch a C-g if it comes in. */
2034 void
2035 poll_for_input_1 (void)
2037 if (! input_blocked_p ()
2038 && !waiting_for_input)
2039 gobble_input ();
2042 /* Timer callback function for poll_timer. TIMER is equal to
2043 poll_timer. */
2045 static void
2046 poll_for_input (struct atimer *timer)
2048 if (poll_suppress_count == 0)
2049 pending_signals = 1;
2052 #endif /* POLL_FOR_INPUT */
2054 /* Begin signals to poll for input, if they are appropriate.
2055 This function is called unconditionally from various places. */
2057 void
2058 start_polling (void)
2060 #ifdef POLL_FOR_INPUT
2061 /* XXX This condition was (read_socket_hook && !interrupt_input),
2062 but read_socket_hook is not global anymore. Let's pretend that
2063 it's always set. */
2064 if (!interrupt_input)
2066 /* Turn alarm handling on unconditionally. It might have
2067 been turned off in process.c. */
2068 turn_on_atimers (1);
2070 /* If poll timer doesn't exist, or we need one with
2071 a different interval, start a new one. */
2072 if (poll_timer == NULL
2073 || poll_timer->interval.tv_sec != polling_period)
2075 time_t period = max (1, min (polling_period, TYPE_MAXIMUM (time_t)));
2076 struct timespec interval = make_timespec (period, 0);
2078 if (poll_timer)
2079 cancel_atimer (poll_timer);
2081 poll_timer = start_atimer (ATIMER_CONTINUOUS, interval,
2082 poll_for_input, NULL);
2085 /* Let the timer's callback function poll for input
2086 if this becomes zero. */
2087 --poll_suppress_count;
2089 #endif
2092 /* True if we are using polling to handle input asynchronously. */
2094 bool
2095 input_polling_used (void)
2097 #ifdef POLL_FOR_INPUT
2098 /* XXX This condition was (read_socket_hook && !interrupt_input),
2099 but read_socket_hook is not global anymore. Let's pretend that
2100 it's always set. */
2101 return !interrupt_input;
2102 #else
2103 return 0;
2104 #endif
2107 /* Turn off polling. */
2109 void
2110 stop_polling (void)
2112 #ifdef POLL_FOR_INPUT
2113 /* XXX This condition was (read_socket_hook && !interrupt_input),
2114 but read_socket_hook is not global anymore. Let's pretend that
2115 it's always set. */
2116 if (!interrupt_input)
2117 ++poll_suppress_count;
2118 #endif
2121 /* Set the value of poll_suppress_count to COUNT
2122 and start or stop polling accordingly. */
2124 void
2125 set_poll_suppress_count (int count)
2127 #ifdef POLL_FOR_INPUT
2128 if (count == 0 && poll_suppress_count != 0)
2130 poll_suppress_count = 1;
2131 start_polling ();
2133 else if (count != 0 && poll_suppress_count == 0)
2135 stop_polling ();
2137 poll_suppress_count = count;
2138 #endif
2141 /* Bind polling_period to a value at least N.
2142 But don't decrease it. */
2144 void
2145 bind_polling_period (int n)
2147 #ifdef POLL_FOR_INPUT
2148 EMACS_INT new = polling_period;
2150 if (n > new)
2151 new = n;
2153 stop_other_atimers (poll_timer);
2154 stop_polling ();
2155 specbind (Qpolling_period, make_number (new));
2156 /* Start a new alarm with the new period. */
2157 start_polling ();
2158 #endif
2161 /* Apply the control modifier to CHARACTER. */
2164 make_ctrl_char (int c)
2166 /* Save the upper bits here. */
2167 int upper = c & ~0177;
2169 if (! ASCII_CHAR_P (c))
2170 return c |= ctrl_modifier;
2172 c &= 0177;
2174 /* Everything in the columns containing the upper-case letters
2175 denotes a control character. */
2176 if (c >= 0100 && c < 0140)
2178 int oc = c;
2179 c &= ~0140;
2180 /* Set the shift modifier for a control char
2181 made from a shifted letter. But only for letters! */
2182 if (oc >= 'A' && oc <= 'Z')
2183 c |= shift_modifier;
2186 /* The lower-case letters denote control characters too. */
2187 else if (c >= 'a' && c <= 'z')
2188 c &= ~0140;
2190 /* Include the bits for control and shift
2191 only if the basic ASCII code can't indicate them. */
2192 else if (c >= ' ')
2193 c |= ctrl_modifier;
2195 /* Replace the high bits. */
2196 c |= (upper & ~ctrl_modifier);
2198 return c;
2201 /* Display the help-echo property of the character after the mouse pointer.
2202 Either show it in the echo area, or call show-help-function to display
2203 it by other means (maybe in a tooltip).
2205 If HELP is nil, that means clear the previous help echo.
2207 If HELP is a string, display that string. If HELP is a function,
2208 call it with OBJECT and POS as arguments; the function should
2209 return a help string or nil for none. For all other types of HELP,
2210 evaluate it to obtain a string.
2212 WINDOW is the window in which the help was generated, if any.
2213 It is nil if not in a window.
2215 If OBJECT is a buffer, POS is the position in the buffer where the
2216 `help-echo' text property was found.
2218 If OBJECT is an overlay, that overlay has a `help-echo' property,
2219 and POS is the position in the overlay's buffer under the mouse.
2221 If OBJECT is a string (an overlay string or a string displayed with
2222 the `display' property). POS is the position in that string under
2223 the mouse.
2225 Note: this function may only be called with HELP nil or a string
2226 from X code running asynchronously. */
2228 void
2229 show_help_echo (Lisp_Object help, Lisp_Object window, Lisp_Object object,
2230 Lisp_Object pos)
2232 if (!NILP (help) && !STRINGP (help))
2234 if (FUNCTIONP (help))
2235 help = safe_call (4, help, window, object, pos);
2236 else
2237 help = safe_eval (help);
2239 if (!STRINGP (help))
2240 return;
2243 if (!noninteractive && STRINGP (help))
2245 /* The mouse-fixup-help-message Lisp function can call
2246 mouse_position_hook, which resets the mouse_moved flags.
2247 This causes trouble if we are trying to read a mouse motion
2248 event (i.e., if we are inside a `track-mouse' form), so we
2249 restore the mouse_moved flag. */
2250 struct frame *f = NILP (do_mouse_tracking) ? NULL : some_mouse_moved ();
2251 help = call1 (Qmouse_fixup_help_message, help);
2252 if (f)
2253 f->mouse_moved = 1;
2256 if (STRINGP (help) || NILP (help))
2258 if (!NILP (Vshow_help_function))
2259 call1 (Vshow_help_function, help);
2260 help_echo_showing_p = STRINGP (help);
2266 /* Input of single characters from keyboard. */
2268 static Lisp_Object kbd_buffer_get_event (KBOARD **kbp, bool *used_mouse_menu,
2269 struct timespec *end_time);
2270 static void record_char (Lisp_Object c);
2272 static Lisp_Object help_form_saved_window_configs;
2273 static void
2274 read_char_help_form_unwind (void)
2276 Lisp_Object window_config = XCAR (help_form_saved_window_configs);
2277 help_form_saved_window_configs = XCDR (help_form_saved_window_configs);
2278 if (!NILP (window_config))
2279 Fset_window_configuration (window_config);
2282 #define STOP_POLLING \
2283 do { if (! polling_stopped_here) stop_polling (); \
2284 polling_stopped_here = 1; } while (0)
2286 #define RESUME_POLLING \
2287 do { if (polling_stopped_here) start_polling (); \
2288 polling_stopped_here = 0; } while (0)
2290 static Lisp_Object
2291 read_event_from_main_queue (struct timespec *end_time,
2292 sys_jmp_buf local_getcjmp,
2293 bool *used_mouse_menu)
2295 Lisp_Object c = Qnil;
2296 sys_jmp_buf save_jump;
2297 KBOARD *kb IF_LINT (= NULL);
2299 start:
2301 /* Read from the main queue, and if that gives us something we can't use yet,
2302 we put it on the appropriate side queue and try again. */
2304 if (end_time && timespec_cmp (*end_time, current_timespec ()) <= 0)
2305 return c;
2307 /* Actually read a character, waiting if necessary. */
2308 save_getcjmp (save_jump);
2309 restore_getcjmp (local_getcjmp);
2310 if (!end_time)
2311 timer_start_idle ();
2312 c = kbd_buffer_get_event (&kb, used_mouse_menu, end_time);
2313 restore_getcjmp (save_jump);
2315 if (! NILP (c) && (kb != current_kboard))
2317 Lisp_Object last = KVAR (kb, kbd_queue);
2318 if (CONSP (last))
2320 while (CONSP (XCDR (last)))
2321 last = XCDR (last);
2322 if (!NILP (XCDR (last)))
2323 emacs_abort ();
2325 if (!CONSP (last))
2326 kset_kbd_queue (kb, list1 (c));
2327 else
2328 XSETCDR (last, list1 (c));
2329 kb->kbd_queue_has_data = 1;
2330 c = Qnil;
2331 if (single_kboard)
2332 goto start;
2333 current_kboard = kb;
2334 /* This is going to exit from read_char
2335 so we had better get rid of this frame's stuff. */
2336 return make_number (-2);
2339 /* Terminate Emacs in batch mode if at eof. */
2340 if (noninteractive && INTEGERP (c) && XINT (c) < 0)
2341 Fkill_emacs (make_number (1));
2343 if (INTEGERP (c))
2345 /* Add in any extra modifiers, where appropriate. */
2346 if ((extra_keyboard_modifiers & CHAR_CTL)
2347 || ((extra_keyboard_modifiers & 0177) < ' '
2348 && (extra_keyboard_modifiers & 0177) != 0))
2349 XSETINT (c, make_ctrl_char (XINT (c)));
2351 /* Transfer any other modifier bits directly from
2352 extra_keyboard_modifiers to c. Ignore the actual character code
2353 in the low 16 bits of extra_keyboard_modifiers. */
2354 XSETINT (c, XINT (c) | (extra_keyboard_modifiers & ~0xff7f & ~CHAR_CTL));
2357 return c;
2362 /* Like `read_event_from_main_queue' but applies keyboard-coding-system
2363 to tty input. */
2364 static Lisp_Object
2365 read_decoded_event_from_main_queue (struct timespec *end_time,
2366 sys_jmp_buf local_getcjmp,
2367 Lisp_Object prev_event,
2368 bool *used_mouse_menu)
2370 #define MAX_ENCODED_BYTES 16
2371 #ifndef WINDOWSNT
2372 Lisp_Object events[MAX_ENCODED_BYTES];
2373 int n = 0;
2374 #endif
2375 while (true)
2377 Lisp_Object nextevt
2378 = read_event_from_main_queue (end_time, local_getcjmp,
2379 used_mouse_menu);
2380 #ifdef WINDOWSNT
2381 /* w32_console already returns decoded events. It either reads
2382 Unicode characters from the Windows keyboard input, or
2383 converts characters encoded in the current codepage into
2384 Unicode. See w32inevt.c:key_event, near its end. */
2385 return nextevt;
2386 #else
2387 struct frame *frame = XFRAME (selected_frame);
2388 struct terminal *terminal = frame->terminal;
2389 if (!((FRAME_TERMCAP_P (frame) || FRAME_MSDOS_P (frame))
2390 /* Don't apply decoding if we're just reading a raw event
2391 (e.g. reading bytes sent by the xterm to specify the position
2392 of a mouse click). */
2393 && (!EQ (prev_event, Qt))
2394 && (TERMINAL_KEYBOARD_CODING (terminal)->common_flags
2395 & CODING_REQUIRE_DECODING_MASK)))
2396 return nextevt; /* No decoding needed. */
2397 else
2399 int meta_key = terminal->display_info.tty->meta_key;
2400 eassert (n < MAX_ENCODED_BYTES);
2401 events[n++] = nextevt;
2402 if (NATNUMP (nextevt)
2403 && XINT (nextevt) < (meta_key == 1 ? 0x80 : 0x100))
2404 { /* An encoded byte sequence, let's try to decode it. */
2405 struct coding_system *coding
2406 = TERMINAL_KEYBOARD_CODING (terminal);
2407 unsigned char src[MAX_ENCODED_BYTES];
2408 unsigned char dest[MAX_ENCODED_BYTES * MAX_MULTIBYTE_LENGTH];
2409 int i;
2410 for (i = 0; i < n; i++)
2411 src[i] = XINT (events[i]);
2412 if (meta_key != 2)
2413 for (i = 0; i < n; i++)
2414 src[i] &= ~0x80;
2415 coding->destination = dest;
2416 coding->dst_bytes = sizeof dest;
2417 decode_coding_c_string (coding, src, n, Qnil);
2418 eassert (coding->produced_char <= n);
2419 if (coding->produced_char == 0)
2420 { /* The encoded sequence is incomplete. */
2421 if (n < MAX_ENCODED_BYTES) /* Avoid buffer overflow. */
2422 continue; /* Read on! */
2424 else
2426 const unsigned char *p = coding->destination;
2427 eassert (coding->carryover_bytes == 0);
2428 n = 0;
2429 while (n < coding->produced_char)
2430 events[n++] = make_number (STRING_CHAR_ADVANCE (p));
2433 /* Now `events' should hold decoded events.
2434 Normally, n should be equal to 1, but better not rely on it.
2435 We can only return one event here, so return the first we
2436 had and keep the others (if any) for later. */
2437 while (n > 1)
2438 Vunread_command_events
2439 = Fcons (events[--n], Vunread_command_events);
2440 return events[0];
2442 #endif
2446 static bool
2447 echo_keystrokes_p (void)
2449 return (FLOATP (Vecho_keystrokes) ? XFLOAT_DATA (Vecho_keystrokes) > 0.0
2450 : INTEGERP (Vecho_keystrokes) ? XINT (Vecho_keystrokes) > 0 : false);
2453 /* Read a character from the keyboard; call the redisplay if needed. */
2454 /* commandflag 0 means do not autosave, but do redisplay.
2455 -1 means do not redisplay, but do autosave.
2456 -2 means do neither.
2457 1 means do both.
2459 The argument MAP is a keymap for menu prompting.
2461 PREV_EVENT is the previous input event, or nil if we are reading
2462 the first event of a key sequence (or not reading a key sequence).
2463 If PREV_EVENT is t, that is a "magic" value that says
2464 not to run input methods, but in other respects to act as if
2465 not reading a key sequence.
2467 If USED_MOUSE_MENU is non-null, then set *USED_MOUSE_MENU to true
2468 if we used a mouse menu to read the input, or false otherwise. If
2469 USED_MOUSE_MENU is null, don't dereference it.
2471 Value is -2 when we find input on another keyboard. A second call
2472 to read_char will read it.
2474 If END_TIME is non-null, it is a pointer to a struct timespec
2475 specifying the maximum time to wait until. If no input arrives by
2476 that time, stop waiting and return nil.
2478 Value is t if we showed a menu and the user rejected it. */
2480 Lisp_Object
2481 read_char (int commandflag, Lisp_Object map,
2482 Lisp_Object prev_event,
2483 bool *used_mouse_menu, struct timespec *end_time)
2485 Lisp_Object c;
2486 ptrdiff_t jmpcount;
2487 sys_jmp_buf local_getcjmp;
2488 sys_jmp_buf save_jump;
2489 Lisp_Object tem, save;
2490 volatile Lisp_Object previous_echo_area_message;
2491 volatile Lisp_Object also_record;
2492 volatile bool reread;
2493 struct gcpro gcpro1, gcpro2;
2494 bool volatile polling_stopped_here = 0;
2495 struct kboard *orig_kboard = current_kboard;
2497 also_record = Qnil;
2499 #if 0 /* This was commented out as part of fixing echo for C-u left. */
2500 before_command_key_count = this_command_key_count;
2501 before_command_echo_length = echo_length ();
2502 #endif
2503 c = Qnil;
2504 previous_echo_area_message = Qnil;
2506 GCPRO2 (c, previous_echo_area_message);
2508 retry:
2510 if (CONSP (Vunread_post_input_method_events))
2512 c = XCAR (Vunread_post_input_method_events);
2513 Vunread_post_input_method_events
2514 = XCDR (Vunread_post_input_method_events);
2516 /* Undo what read_char_x_menu_prompt did when it unread
2517 additional keys returned by Fx_popup_menu. */
2518 if (CONSP (c)
2519 && (SYMBOLP (XCAR (c)) || INTEGERP (XCAR (c)))
2520 && NILP (XCDR (c)))
2521 c = XCAR (c);
2523 reread = true;
2524 goto reread_first;
2526 else
2527 reread = false;
2530 if (CONSP (Vunread_command_events))
2532 bool was_disabled = 0;
2534 c = XCAR (Vunread_command_events);
2535 Vunread_command_events = XCDR (Vunread_command_events);
2537 /* Undo what sit-for did when it unread additional keys
2538 inside universal-argument. */
2540 if (CONSP (c) && EQ (XCAR (c), Qt))
2541 c = XCDR (c);
2542 else
2543 reread = true;
2545 /* Undo what read_char_x_menu_prompt did when it unread
2546 additional keys returned by Fx_popup_menu. */
2547 if (CONSP (c)
2548 && EQ (XCDR (c), Qdisabled)
2549 && (SYMBOLP (XCAR (c)) || INTEGERP (XCAR (c))))
2551 was_disabled = 1;
2552 c = XCAR (c);
2555 /* If the queued event is something that used the mouse,
2556 set used_mouse_menu accordingly. */
2557 if (used_mouse_menu
2558 /* Also check was_disabled so last-nonmenu-event won't return
2559 a bad value when submenus are involved. (Bug#447) */
2560 && (EQ (c, Qtool_bar) || EQ (c, Qmenu_bar) || was_disabled))
2561 *used_mouse_menu = 1;
2563 goto reread_for_input_method;
2566 if (CONSP (Vunread_input_method_events))
2568 c = XCAR (Vunread_input_method_events);
2569 Vunread_input_method_events = XCDR (Vunread_input_method_events);
2571 /* Undo what read_char_x_menu_prompt did when it unread
2572 additional keys returned by Fx_popup_menu. */
2573 if (CONSP (c)
2574 && (SYMBOLP (XCAR (c)) || INTEGERP (XCAR (c)))
2575 && NILP (XCDR (c)))
2576 c = XCAR (c);
2577 reread = true;
2578 goto reread_for_input_method;
2581 this_command_key_count_reset = 0;
2583 if (!NILP (Vexecuting_kbd_macro))
2585 /* We set this to Qmacro; since that's not a frame, nobody will
2586 try to switch frames on us, and the selected window will
2587 remain unchanged.
2589 Since this event came from a macro, it would be misleading to
2590 leave internal_last_event_frame set to wherever the last
2591 real event came from. Normally, a switch-frame event selects
2592 internal_last_event_frame after each command is read, but
2593 events read from a macro should never cause a new frame to be
2594 selected. */
2595 Vlast_event_frame = internal_last_event_frame = Qmacro;
2597 /* Exit the macro if we are at the end.
2598 Also, some things replace the macro with t
2599 to force an early exit. */
2600 if (EQ (Vexecuting_kbd_macro, Qt)
2601 || executing_kbd_macro_index >= XFASTINT (Flength (Vexecuting_kbd_macro)))
2603 XSETINT (c, -1);
2604 goto exit;
2607 c = Faref (Vexecuting_kbd_macro, make_number (executing_kbd_macro_index));
2608 if (STRINGP (Vexecuting_kbd_macro)
2609 && (XFASTINT (c) & 0x80) && (XFASTINT (c) <= 0xff))
2610 XSETFASTINT (c, CHAR_META | (XFASTINT (c) & ~0x80));
2612 executing_kbd_macro_index++;
2614 goto from_macro;
2617 if (!NILP (unread_switch_frame))
2619 c = unread_switch_frame;
2620 unread_switch_frame = Qnil;
2622 /* This event should make it into this_command_keys, and get echoed
2623 again, so we do not set `reread'. */
2624 goto reread_first;
2627 /* If redisplay was requested. */
2628 if (commandflag >= 0)
2630 bool echo_current = EQ (echo_message_buffer, echo_area_buffer[0]);
2632 /* If there is pending input, process any events which are not
2633 user-visible, such as X selection_request events. */
2634 if (input_pending
2635 || detect_input_pending_run_timers (0))
2636 swallow_events (false); /* May clear input_pending. */
2638 /* Redisplay if no pending input. */
2639 while (!(input_pending
2640 && (input_was_pending || !redisplay_dont_pause)))
2642 input_was_pending = input_pending;
2643 if (help_echo_showing_p && !EQ (selected_window, minibuf_window))
2644 redisplay_preserve_echo_area (5);
2645 else
2646 redisplay ();
2648 if (!input_pending)
2649 /* Normal case: no input arrived during redisplay. */
2650 break;
2652 /* Input arrived and pre-empted redisplay.
2653 Process any events which are not user-visible. */
2654 swallow_events (false);
2655 /* If that cleared input_pending, try again to redisplay. */
2658 /* Prevent the redisplay we just did
2659 from messing up echoing of the input after the prompt. */
2660 if (commandflag == 0 && echo_current)
2661 echo_message_buffer = echo_area_buffer[0];
2665 /* Message turns off echoing unless more keystrokes turn it on again.
2667 The code in 20.x for the condition was
2669 1. echo_area_glyphs && *echo_area_glyphs
2670 2. && echo_area_glyphs != current_kboard->echobuf
2671 3. && ok_to_echo_at_next_pause != echo_area_glyphs
2673 (1) means there's a current message displayed
2675 (2) means it's not the message from echoing from the current
2676 kboard.
2678 (3) There's only one place in 20.x where ok_to_echo_at_next_pause
2679 is set to a non-null value. This is done in read_char and it is
2680 set to echo_area_glyphs after a call to echo_char. That means
2681 ok_to_echo_at_next_pause is either null or
2682 current_kboard->echobuf with the appropriate current_kboard at
2683 that time.
2685 So, condition (3) means in clear text ok_to_echo_at_next_pause
2686 must be either null, or the current message isn't from echoing at
2687 all, or it's from echoing from a different kboard than the
2688 current one. */
2690 if (/* There currently is something in the echo area. */
2691 !NILP (echo_area_buffer[0])
2692 && (/* It's an echo from a different kboard. */
2693 echo_kboard != current_kboard
2694 /* Or we explicitly allow overwriting whatever there is. */
2695 || ok_to_echo_at_next_pause == NULL))
2696 cancel_echoing ();
2697 else
2698 echo_dash ();
2700 /* Try reading a character via menu prompting in the minibuf.
2701 Try this before the sit-for, because the sit-for
2702 would do the wrong thing if we are supposed to do
2703 menu prompting. If EVENT_HAS_PARAMETERS then we are reading
2704 after a mouse event so don't try a minibuf menu. */
2705 c = Qnil;
2706 if (KEYMAPP (map) && INTERACTIVE
2707 && !NILP (prev_event) && ! EVENT_HAS_PARAMETERS (prev_event)
2708 /* Don't bring up a menu if we already have another event. */
2709 && NILP (Vunread_command_events)
2710 && !detect_input_pending_run_timers (0))
2712 c = read_char_minibuf_menu_prompt (commandflag, map);
2714 if (INTEGERP (c) && XINT (c) == -2)
2715 return c; /* wrong_kboard_jmpbuf */
2717 if (! NILP (c))
2718 goto exit;
2721 /* Make a longjmp point for quits to use, but don't alter getcjmp just yet.
2722 We will do that below, temporarily for short sections of code,
2723 when appropriate. local_getcjmp must be in effect
2724 around any call to sit_for or kbd_buffer_get_event;
2725 it *must not* be in effect when we call redisplay. */
2727 jmpcount = SPECPDL_INDEX ();
2728 if (sys_setjmp (local_getcjmp))
2730 /* Handle quits while reading the keyboard. */
2731 /* We must have saved the outer value of getcjmp here,
2732 so restore it now. */
2733 restore_getcjmp (save_jump);
2734 pthread_sigmask (SIG_SETMASK, &empty_mask, 0);
2735 unbind_to (jmpcount, Qnil);
2736 XSETINT (c, quit_char);
2737 internal_last_event_frame = selected_frame;
2738 Vlast_event_frame = internal_last_event_frame;
2739 /* If we report the quit char as an event,
2740 don't do so more than once. */
2741 if (!NILP (Vinhibit_quit))
2742 Vquit_flag = Qnil;
2745 KBOARD *kb = FRAME_KBOARD (XFRAME (selected_frame));
2746 if (kb != current_kboard)
2748 Lisp_Object last = KVAR (kb, kbd_queue);
2749 /* We shouldn't get here if we were in single-kboard mode! */
2750 if (single_kboard)
2751 emacs_abort ();
2752 if (CONSP (last))
2754 while (CONSP (XCDR (last)))
2755 last = XCDR (last);
2756 if (!NILP (XCDR (last)))
2757 emacs_abort ();
2759 if (!CONSP (last))
2760 kset_kbd_queue (kb, list1 (c));
2761 else
2762 XSETCDR (last, list1 (c));
2763 kb->kbd_queue_has_data = 1;
2764 current_kboard = kb;
2765 /* This is going to exit from read_char
2766 so we had better get rid of this frame's stuff. */
2767 UNGCPRO;
2768 return make_number (-2); /* wrong_kboard_jmpbuf */
2771 goto non_reread;
2774 /* Start idle timers if no time limit is supplied. We don't do it
2775 if a time limit is supplied to avoid an infinite recursion in the
2776 situation where an idle timer calls `sit-for'. */
2778 if (!end_time)
2779 timer_start_idle ();
2781 /* If in middle of key sequence and minibuffer not active,
2782 start echoing if enough time elapses. */
2784 if (minibuf_level == 0
2785 && !end_time
2786 && !current_kboard->immediate_echo
2787 && this_command_key_count > 0
2788 && ! noninteractive
2789 && echo_keystrokes_p ()
2790 && (/* No message. */
2791 NILP (echo_area_buffer[0])
2792 /* Or empty message. */
2793 || (BUF_BEG (XBUFFER (echo_area_buffer[0]))
2794 == BUF_Z (XBUFFER (echo_area_buffer[0])))
2795 /* Or already echoing from same kboard. */
2796 || (echo_kboard && ok_to_echo_at_next_pause == echo_kboard)
2797 /* Or not echoing before and echoing allowed. */
2798 || (!echo_kboard && ok_to_echo_at_next_pause)))
2800 /* After a mouse event, start echoing right away.
2801 This is because we are probably about to display a menu,
2802 and we don't want to delay before doing so. */
2803 if (EVENT_HAS_PARAMETERS (prev_event))
2804 echo_now ();
2805 else
2807 Lisp_Object tem0;
2809 save_getcjmp (save_jump);
2810 restore_getcjmp (local_getcjmp);
2811 tem0 = sit_for (Vecho_keystrokes, 1, 1);
2812 restore_getcjmp (save_jump);
2813 if (EQ (tem0, Qt)
2814 && ! CONSP (Vunread_command_events))
2815 echo_now ();
2819 /* Maybe auto save due to number of keystrokes. */
2821 if (commandflag != 0 && commandflag != -2
2822 && auto_save_interval > 0
2823 && num_nonmacro_input_events - last_auto_save > max (auto_save_interval, 20)
2824 && !detect_input_pending_run_timers (0))
2826 Fdo_auto_save (Qnil, Qnil);
2827 /* Hooks can actually change some buffers in auto save. */
2828 redisplay ();
2831 /* Try reading using an X menu.
2832 This is never confused with reading using the minibuf
2833 because the recursive call of read_char in read_char_minibuf_menu_prompt
2834 does not pass on any keymaps. */
2836 if (KEYMAPP (map) && INTERACTIVE
2837 && !NILP (prev_event)
2838 && EVENT_HAS_PARAMETERS (prev_event)
2839 && !EQ (XCAR (prev_event), Qmenu_bar)
2840 && !EQ (XCAR (prev_event), Qtool_bar)
2841 /* Don't bring up a menu if we already have another event. */
2842 && NILP (Vunread_command_events))
2844 c = read_char_x_menu_prompt (map, prev_event, used_mouse_menu);
2846 /* Now that we have read an event, Emacs is not idle. */
2847 if (!end_time)
2848 timer_stop_idle ();
2850 goto exit;
2853 /* Maybe autosave and/or garbage collect due to idleness. */
2855 if (INTERACTIVE && NILP (c))
2857 int delay_level;
2858 ptrdiff_t buffer_size;
2860 /* Slow down auto saves logarithmically in size of current buffer,
2861 and garbage collect while we're at it. */
2862 if (! MINI_WINDOW_P (XWINDOW (selected_window)))
2863 last_non_minibuf_size = Z - BEG;
2864 buffer_size = (last_non_minibuf_size >> 8) + 1;
2865 delay_level = 0;
2866 while (buffer_size > 64)
2867 delay_level++, buffer_size -= buffer_size >> 2;
2868 if (delay_level < 4) delay_level = 4;
2869 /* delay_level is 4 for files under around 50k, 7 at 100k,
2870 9 at 200k, 11 at 300k, and 12 at 500k. It is 15 at 1 meg. */
2872 /* Auto save if enough time goes by without input. */
2873 if (commandflag != 0 && commandflag != -2
2874 && num_nonmacro_input_events > last_auto_save
2875 && INTEGERP (Vauto_save_timeout)
2876 && XINT (Vauto_save_timeout) > 0)
2878 Lisp_Object tem0;
2879 EMACS_INT timeout = XFASTINT (Vauto_save_timeout);
2881 timeout = min (timeout, MOST_POSITIVE_FIXNUM / delay_level * 4);
2882 timeout = delay_level * timeout / 4;
2883 save_getcjmp (save_jump);
2884 restore_getcjmp (local_getcjmp);
2885 tem0 = sit_for (make_number (timeout), 1, 1);
2886 restore_getcjmp (save_jump);
2888 if (EQ (tem0, Qt)
2889 && ! CONSP (Vunread_command_events))
2891 Fdo_auto_save (Qnil, Qnil);
2892 redisplay ();
2896 /* If there is still no input available, ask for GC. */
2897 if (!detect_input_pending_run_timers (0))
2898 maybe_gc ();
2901 /* Notify the caller if an autosave hook, or a timer, sentinel or
2902 filter in the sit_for calls above have changed the current
2903 kboard. This could happen if they use the minibuffer or start a
2904 recursive edit, like the fancy splash screen in server.el's
2905 filter. If this longjmp wasn't here, read_key_sequence would
2906 interpret the next key sequence using the wrong translation
2907 tables and function keymaps. */
2908 if (NILP (c) && current_kboard != orig_kboard)
2910 UNGCPRO;
2911 return make_number (-2); /* wrong_kboard_jmpbuf */
2914 /* If this has become non-nil here, it has been set by a timer
2915 or sentinel or filter. */
2916 if (CONSP (Vunread_command_events))
2918 c = XCAR (Vunread_command_events);
2919 Vunread_command_events = XCDR (Vunread_command_events);
2921 if (CONSP (c) && EQ (XCAR (c), Qt))
2922 c = XCDR (c);
2923 else
2924 reread = true;
2927 /* Read something from current KBOARD's side queue, if possible. */
2929 if (NILP (c))
2931 if (current_kboard->kbd_queue_has_data)
2933 if (!CONSP (KVAR (current_kboard, kbd_queue)))
2934 emacs_abort ();
2935 c = XCAR (KVAR (current_kboard, kbd_queue));
2936 kset_kbd_queue (current_kboard,
2937 XCDR (KVAR (current_kboard, kbd_queue)));
2938 if (NILP (KVAR (current_kboard, kbd_queue)))
2939 current_kboard->kbd_queue_has_data = 0;
2940 input_pending = readable_events (0);
2941 if (EVENT_HAS_PARAMETERS (c)
2942 && EQ (EVENT_HEAD_KIND (EVENT_HEAD (c)), Qswitch_frame))
2943 internal_last_event_frame = XCAR (XCDR (c));
2944 Vlast_event_frame = internal_last_event_frame;
2948 /* If current_kboard's side queue is empty check the other kboards.
2949 If one of them has data that we have not yet seen here,
2950 switch to it and process the data waiting for it.
2952 Note: if the events queued up for another kboard
2953 have already been seen here, and therefore are not a complete command,
2954 the kbd_queue_has_data field is 0, so we skip that kboard here.
2955 That's to avoid an infinite loop switching between kboards here. */
2956 if (NILP (c) && !single_kboard)
2958 KBOARD *kb;
2959 for (kb = all_kboards; kb; kb = kb->next_kboard)
2960 if (kb->kbd_queue_has_data)
2962 current_kboard = kb;
2963 /* This is going to exit from read_char
2964 so we had better get rid of this frame's stuff. */
2965 UNGCPRO;
2966 return make_number (-2); /* wrong_kboard_jmpbuf */
2970 wrong_kboard:
2972 STOP_POLLING;
2974 if (NILP (c))
2976 c = read_decoded_event_from_main_queue (end_time, local_getcjmp,
2977 prev_event, used_mouse_menu);
2978 if (NILP (c) && end_time
2979 && timespec_cmp (*end_time, current_timespec ()) <= 0)
2981 goto exit;
2984 if (EQ (c, make_number (-2)))
2986 /* This is going to exit from read_char
2987 so we had better get rid of this frame's stuff. */
2988 UNGCPRO;
2989 return c;
2993 non_reread:
2995 if (!end_time)
2996 timer_stop_idle ();
2997 RESUME_POLLING;
2999 if (NILP (c))
3001 if (commandflag >= 0
3002 && !input_pending && !detect_input_pending_run_timers (0))
3003 redisplay ();
3005 goto wrong_kboard;
3008 /* Buffer switch events are only for internal wakeups
3009 so don't show them to the user.
3010 Also, don't record a key if we already did. */
3011 if (BUFFERP (c))
3012 goto exit;
3014 /* Process special events within read_char
3015 and loop around to read another event. */
3016 save = Vquit_flag;
3017 Vquit_flag = Qnil;
3018 tem = access_keymap (get_keymap (Vspecial_event_map, 0, 1), c, 0, 0, 1);
3019 Vquit_flag = save;
3021 if (!NILP (tem))
3023 struct buffer *prev_buffer = current_buffer;
3024 last_input_event = c;
3025 call4 (Qcommand_execute, tem, Qnil, Fvector (1, &last_input_event), Qt);
3027 if (CONSP (c) && EQ (XCAR (c), Qselect_window) && !end_time)
3028 /* We stopped being idle for this event; undo that. This
3029 prevents automatic window selection (under
3030 mouse_autoselect_window from acting as a real input event, for
3031 example banishing the mouse under mouse-avoidance-mode. */
3032 timer_resume_idle ();
3034 if (current_buffer != prev_buffer)
3036 /* The command may have changed the keymaps. Pretend there
3037 is input in another keyboard and return. This will
3038 recalculate keymaps. */
3039 c = make_number (-2);
3040 goto exit;
3042 else
3043 goto retry;
3046 /* Handle things that only apply to characters. */
3047 if (INTEGERP (c))
3049 /* If kbd_buffer_get_event gave us an EOF, return that. */
3050 if (XINT (c) == -1)
3051 goto exit;
3053 if ((STRINGP (KVAR (current_kboard, Vkeyboard_translate_table))
3054 && UNSIGNED_CMP (XFASTINT (c), <,
3055 SCHARS (KVAR (current_kboard,
3056 Vkeyboard_translate_table))))
3057 || (VECTORP (KVAR (current_kboard, Vkeyboard_translate_table))
3058 && UNSIGNED_CMP (XFASTINT (c), <,
3059 ASIZE (KVAR (current_kboard,
3060 Vkeyboard_translate_table))))
3061 || (CHAR_TABLE_P (KVAR (current_kboard, Vkeyboard_translate_table))
3062 && CHARACTERP (c)))
3064 Lisp_Object d;
3065 d = Faref (KVAR (current_kboard, Vkeyboard_translate_table), c);
3066 /* nil in keyboard-translate-table means no translation. */
3067 if (!NILP (d))
3068 c = d;
3072 /* If this event is a mouse click in the menu bar,
3073 return just menu-bar for now. Modify the mouse click event
3074 so we won't do this twice, then queue it up. */
3075 if (EVENT_HAS_PARAMETERS (c)
3076 && CONSP (XCDR (c))
3077 && CONSP (EVENT_START (c))
3078 && CONSP (XCDR (EVENT_START (c))))
3080 Lisp_Object posn;
3082 posn = POSN_POSN (EVENT_START (c));
3083 /* Handle menu-bar events:
3084 insert the dummy prefix event `menu-bar'. */
3085 if (EQ (posn, Qmenu_bar) || EQ (posn, Qtool_bar))
3087 /* Change menu-bar to (menu-bar) as the event "position". */
3088 POSN_SET_POSN (EVENT_START (c), list1 (posn));
3090 also_record = c;
3091 Vunread_command_events = Fcons (c, Vunread_command_events);
3092 c = posn;
3096 /* Store these characters into recent_keys, the dribble file if any,
3097 and the keyboard macro being defined, if any. */
3098 record_char (c);
3099 if (! NILP (also_record))
3100 record_char (also_record);
3102 /* Wipe the echo area.
3103 But first, if we are about to use an input method,
3104 save the echo area contents for it to refer to. */
3105 if (INTEGERP (c)
3106 && ! NILP (Vinput_method_function)
3107 && ' ' <= XINT (c) && XINT (c) < 256 && XINT (c) != 127)
3109 previous_echo_area_message = Fcurrent_message ();
3110 Vinput_method_previous_message = previous_echo_area_message;
3113 /* Now wipe the echo area, except for help events which do their
3114 own stuff with the echo area. */
3115 if (!CONSP (c)
3116 || (!(EQ (Qhelp_echo, XCAR (c)))
3117 && !(EQ (Qswitch_frame, XCAR (c)))
3118 /* Don't wipe echo area for select window events: These might
3119 get delayed via `mouse-autoselect-window' (Bug#11304). */
3120 && !(EQ (Qselect_window, XCAR (c)))))
3122 if (!NILP (echo_area_buffer[0]))
3124 safe_run_hooks (Qecho_area_clear_hook);
3125 clear_message (1, 0);
3129 reread_for_input_method:
3130 from_macro:
3131 /* Pass this to the input method, if appropriate. */
3132 if (INTEGERP (c)
3133 && ! NILP (Vinput_method_function)
3134 /* Don't run the input method within a key sequence,
3135 after the first event of the key sequence. */
3136 && NILP (prev_event)
3137 && ' ' <= XINT (c) && XINT (c) < 256 && XINT (c) != 127)
3139 Lisp_Object keys;
3140 ptrdiff_t key_count;
3141 bool key_count_reset;
3142 struct gcpro gcpro1;
3143 ptrdiff_t count = SPECPDL_INDEX ();
3145 /* Save the echo status. */
3146 bool saved_immediate_echo = current_kboard->immediate_echo;
3147 struct kboard *saved_ok_to_echo = ok_to_echo_at_next_pause;
3148 Lisp_Object saved_echo_string = KVAR (current_kboard, echo_string);
3149 ptrdiff_t saved_echo_after_prompt = current_kboard->echo_after_prompt;
3151 #if 0
3152 if (before_command_restore_flag)
3154 this_command_key_count = before_command_key_count_1;
3155 if (this_command_key_count < this_single_command_key_start)
3156 this_single_command_key_start = this_command_key_count;
3157 echo_truncate (before_command_echo_length_1);
3158 before_command_restore_flag = 0;
3160 #endif
3162 /* Save the this_command_keys status. */
3163 key_count = this_command_key_count;
3164 key_count_reset = this_command_key_count_reset;
3166 if (key_count > 0)
3167 keys = Fcopy_sequence (this_command_keys);
3168 else
3169 keys = Qnil;
3170 GCPRO1 (keys);
3172 /* Clear out this_command_keys. */
3173 this_command_key_count = 0;
3174 this_command_key_count_reset = 0;
3176 /* Now wipe the echo area. */
3177 if (!NILP (echo_area_buffer[0]))
3178 safe_run_hooks (Qecho_area_clear_hook);
3179 clear_message (1, 0);
3180 echo_truncate (0);
3182 /* If we are not reading a key sequence,
3183 never use the echo area. */
3184 if (!KEYMAPP (map))
3186 specbind (Qinput_method_use_echo_area, Qt);
3189 /* Call the input method. */
3190 tem = call1 (Vinput_method_function, c);
3192 tem = unbind_to (count, tem);
3194 /* Restore the saved echoing state
3195 and this_command_keys state. */
3196 this_command_key_count = key_count;
3197 this_command_key_count_reset = key_count_reset;
3198 if (key_count > 0)
3199 this_command_keys = keys;
3201 cancel_echoing ();
3202 ok_to_echo_at_next_pause = saved_ok_to_echo;
3203 kset_echo_string (current_kboard, saved_echo_string);
3204 current_kboard->echo_after_prompt = saved_echo_after_prompt;
3205 if (saved_immediate_echo)
3206 echo_now ();
3208 UNGCPRO;
3210 /* The input method can return no events. */
3211 if (! CONSP (tem))
3213 /* Bring back the previous message, if any. */
3214 if (! NILP (previous_echo_area_message))
3215 message_with_string ("%s", previous_echo_area_message, 0);
3216 goto retry;
3218 /* It returned one event or more. */
3219 c = XCAR (tem);
3220 Vunread_post_input_method_events
3221 = nconc2 (XCDR (tem), Vunread_post_input_method_events);
3224 reread_first:
3226 /* Display help if not echoing. */
3227 if (CONSP (c) && EQ (XCAR (c), Qhelp_echo))
3229 /* (help-echo FRAME HELP WINDOW OBJECT POS). */
3230 Lisp_Object help, object, position, window, htem;
3232 htem = Fcdr (XCDR (c));
3233 help = Fcar (htem);
3234 htem = Fcdr (htem);
3235 window = Fcar (htem);
3236 htem = Fcdr (htem);
3237 object = Fcar (htem);
3238 htem = Fcdr (htem);
3239 position = Fcar (htem);
3241 show_help_echo (help, window, object, position);
3243 /* We stopped being idle for this event; undo that. */
3244 if (!end_time)
3245 timer_resume_idle ();
3246 goto retry;
3249 if ((! reread || this_command_key_count == 0
3250 || this_command_key_count_reset)
3251 && !end_time)
3254 /* Don't echo mouse motion events. */
3255 if (echo_keystrokes_p ()
3256 && ! (EVENT_HAS_PARAMETERS (c)
3257 && EQ (EVENT_HEAD_KIND (EVENT_HEAD (c)), Qmouse_movement)))
3259 echo_char (c);
3260 if (! NILP (also_record))
3261 echo_char (also_record);
3262 /* Once we reread a character, echoing can happen
3263 the next time we pause to read a new one. */
3264 ok_to_echo_at_next_pause = current_kboard;
3267 /* Record this character as part of the current key. */
3268 add_command_key (c);
3269 if (! NILP (also_record))
3270 add_command_key (also_record);
3273 last_input_event = c;
3274 num_input_events++;
3276 /* Process the help character specially if enabled. */
3277 if (!NILP (Vhelp_form) && help_char_p (c))
3279 ptrdiff_t count = SPECPDL_INDEX ();
3281 help_form_saved_window_configs
3282 = Fcons (Fcurrent_window_configuration (Qnil),
3283 help_form_saved_window_configs);
3284 record_unwind_protect_void (read_char_help_form_unwind);
3285 call0 (Qhelp_form_show);
3287 cancel_echoing ();
3290 c = read_char (0, Qnil, Qnil, 0, NULL);
3291 if (EVENT_HAS_PARAMETERS (c)
3292 && EQ (EVENT_HEAD_KIND (EVENT_HEAD (c)), Qmouse_click))
3293 XSETCAR (help_form_saved_window_configs, Qnil);
3295 while (BUFFERP (c));
3296 /* Remove the help from the frame. */
3297 unbind_to (count, Qnil);
3299 redisplay ();
3300 if (EQ (c, make_number (040)))
3302 cancel_echoing ();
3304 c = read_char (0, Qnil, Qnil, 0, NULL);
3305 while (BUFFERP (c));
3309 exit:
3310 RESUME_POLLING;
3311 input_was_pending = input_pending;
3312 RETURN_UNGCPRO (c);
3315 /* Record a key that came from a mouse menu.
3316 Record it for echoing, for this-command-keys, and so on. */
3318 static void
3319 record_menu_key (Lisp_Object c)
3321 /* Wipe the echo area. */
3322 clear_message (1, 0);
3324 record_char (c);
3326 #if 0
3327 before_command_key_count = this_command_key_count;
3328 before_command_echo_length = echo_length ();
3329 #endif
3331 /* Don't echo mouse motion events. */
3332 if (echo_keystrokes_p ())
3334 echo_char (c);
3336 /* Once we reread a character, echoing can happen
3337 the next time we pause to read a new one. */
3338 ok_to_echo_at_next_pause = 0;
3341 /* Record this character as part of the current key. */
3342 add_command_key (c);
3344 /* Re-reading in the middle of a command. */
3345 last_input_event = c;
3346 num_input_events++;
3349 /* Return true if should recognize C as "the help character". */
3351 static bool
3352 help_char_p (Lisp_Object c)
3354 Lisp_Object tail;
3356 if (EQ (c, Vhelp_char))
3357 return 1;
3358 for (tail = Vhelp_event_list; CONSP (tail); tail = XCDR (tail))
3359 if (EQ (c, XCAR (tail)))
3360 return 1;
3361 return 0;
3364 /* Record the input event C in various ways. */
3366 static void
3367 record_char (Lisp_Object c)
3369 int recorded = 0;
3371 if (CONSP (c) && (EQ (XCAR (c), Qhelp_echo) || EQ (XCAR (c), Qmouse_movement)))
3373 /* To avoid filling recent_keys with help-echo and mouse-movement
3374 events, we filter out repeated help-echo events, only store the
3375 first and last in a series of mouse-movement events, and don't
3376 store repeated help-echo events which are only separated by
3377 mouse-movement events. */
3379 Lisp_Object ev1, ev2, ev3;
3380 int ix1, ix2, ix3;
3382 if ((ix1 = recent_keys_index - 1) < 0)
3383 ix1 = NUM_RECENT_KEYS - 1;
3384 ev1 = AREF (recent_keys, ix1);
3386 if ((ix2 = ix1 - 1) < 0)
3387 ix2 = NUM_RECENT_KEYS - 1;
3388 ev2 = AREF (recent_keys, ix2);
3390 if ((ix3 = ix2 - 1) < 0)
3391 ix3 = NUM_RECENT_KEYS - 1;
3392 ev3 = AREF (recent_keys, ix3);
3394 if (EQ (XCAR (c), Qhelp_echo))
3396 /* Don't record `help-echo' in recent_keys unless it shows some help
3397 message, and a different help than the previously recorded
3398 event. */
3399 Lisp_Object help, last_help;
3401 help = Fcar_safe (Fcdr_safe (XCDR (c)));
3402 if (!STRINGP (help))
3403 recorded = 1;
3404 else if (CONSP (ev1) && EQ (XCAR (ev1), Qhelp_echo)
3405 && (last_help = Fcar_safe (Fcdr_safe (XCDR (ev1))), EQ (last_help, help)))
3406 recorded = 1;
3407 else if (CONSP (ev1) && EQ (XCAR (ev1), Qmouse_movement)
3408 && CONSP (ev2) && EQ (XCAR (ev2), Qhelp_echo)
3409 && (last_help = Fcar_safe (Fcdr_safe (XCDR (ev2))), EQ (last_help, help)))
3410 recorded = -1;
3411 else if (CONSP (ev1) && EQ (XCAR (ev1), Qmouse_movement)
3412 && CONSP (ev2) && EQ (XCAR (ev2), Qmouse_movement)
3413 && CONSP (ev3) && EQ (XCAR (ev3), Qhelp_echo)
3414 && (last_help = Fcar_safe (Fcdr_safe (XCDR (ev3))), EQ (last_help, help)))
3415 recorded = -2;
3417 else if (EQ (XCAR (c), Qmouse_movement))
3419 /* Only record one pair of `mouse-movement' on a window in recent_keys.
3420 So additional mouse movement events replace the last element. */
3421 Lisp_Object last_window, window;
3423 window = Fcar_safe (Fcar_safe (XCDR (c)));
3424 if (CONSP (ev1) && EQ (XCAR (ev1), Qmouse_movement)
3425 && (last_window = Fcar_safe (Fcar_safe (XCDR (ev1))), EQ (last_window, window))
3426 && CONSP (ev2) && EQ (XCAR (ev2), Qmouse_movement)
3427 && (last_window = Fcar_safe (Fcar_safe (XCDR (ev2))), EQ (last_window, window)))
3429 ASET (recent_keys, ix1, c);
3430 recorded = 1;
3434 else
3435 store_kbd_macro_char (c);
3437 if (!recorded)
3439 total_keys += total_keys < NUM_RECENT_KEYS;
3440 ASET (recent_keys, recent_keys_index, c);
3441 if (++recent_keys_index >= NUM_RECENT_KEYS)
3442 recent_keys_index = 0;
3444 else if (recorded < 0)
3446 /* We need to remove one or two events from recent_keys.
3447 To do this, we simply put nil at those events and move the
3448 recent_keys_index backwards over those events. Usually,
3449 users will never see those nil events, as they will be
3450 overwritten by the command keys entered to see recent_keys
3451 (e.g. C-h l). */
3453 while (recorded++ < 0 && total_keys > 0)
3455 if (total_keys < NUM_RECENT_KEYS)
3456 total_keys--;
3457 if (--recent_keys_index < 0)
3458 recent_keys_index = NUM_RECENT_KEYS - 1;
3459 ASET (recent_keys, recent_keys_index, Qnil);
3463 num_nonmacro_input_events++;
3465 /* Write c to the dribble file. If c is a lispy event, write
3466 the event's symbol to the dribble file, in <brackets>. Bleaugh.
3467 If you, dear reader, have a better idea, you've got the source. :-) */
3468 if (dribble)
3470 block_input ();
3471 if (INTEGERP (c))
3473 if (XUINT (c) < 0x100)
3474 putc (XUINT (c), dribble);
3475 else
3476 fprintf (dribble, " 0x%"pI"x", XUINT (c));
3478 else
3480 Lisp_Object dribblee;
3482 /* If it's a structured event, take the event header. */
3483 dribblee = EVENT_HEAD (c);
3485 if (SYMBOLP (dribblee))
3487 putc ('<', dribble);
3488 fwrite (SDATA (SYMBOL_NAME (dribblee)), sizeof (char),
3489 SBYTES (SYMBOL_NAME (dribblee)),
3490 dribble);
3491 putc ('>', dribble);
3495 fflush (dribble);
3496 unblock_input ();
3500 /* Copy out or in the info on where C-g should throw to.
3501 This is used when running Lisp code from within get_char,
3502 in case get_char is called recursively.
3503 See read_process_output. */
3505 static void
3506 save_getcjmp (sys_jmp_buf temp)
3508 memcpy (temp, getcjmp, sizeof getcjmp);
3511 static void
3512 restore_getcjmp (sys_jmp_buf temp)
3514 memcpy (getcjmp, temp, sizeof getcjmp);
3517 /* Low level keyboard/mouse input.
3518 kbd_buffer_store_event places events in kbd_buffer, and
3519 kbd_buffer_get_event retrieves them. */
3521 /* Return true if there are any events in the queue that read-char
3522 would return. If this returns false, a read-char would block. */
3523 static bool
3524 readable_events (int flags)
3526 if (flags & READABLE_EVENTS_DO_TIMERS_NOW)
3527 timer_check ();
3529 /* If the buffer contains only FOCUS_IN_EVENT events, and
3530 READABLE_EVENTS_FILTER_EVENTS is set, report it as empty. */
3531 if (kbd_fetch_ptr != kbd_store_ptr)
3533 if (flags & (READABLE_EVENTS_FILTER_EVENTS
3534 #ifdef USE_TOOLKIT_SCROLL_BARS
3535 | READABLE_EVENTS_IGNORE_SQUEEZABLES
3536 #endif
3539 struct input_event *event;
3541 event = ((kbd_fetch_ptr < kbd_buffer + KBD_BUFFER_SIZE)
3542 ? kbd_fetch_ptr
3543 : kbd_buffer);
3547 if (!(
3548 #ifdef USE_TOOLKIT_SCROLL_BARS
3549 (flags & READABLE_EVENTS_FILTER_EVENTS) &&
3550 #endif
3551 event->kind == FOCUS_IN_EVENT)
3552 #ifdef USE_TOOLKIT_SCROLL_BARS
3553 && !((flags & READABLE_EVENTS_IGNORE_SQUEEZABLES)
3554 && (event->kind == SCROLL_BAR_CLICK_EVENT
3555 || event->kind == HORIZONTAL_SCROLL_BAR_CLICK_EVENT)
3556 && event->part == scroll_bar_handle
3557 && event->modifiers == 0)
3558 #endif
3559 && !((flags & READABLE_EVENTS_FILTER_EVENTS)
3560 && event->kind == BUFFER_SWITCH_EVENT))
3561 return 1;
3562 event++;
3563 if (event == kbd_buffer + KBD_BUFFER_SIZE)
3564 event = kbd_buffer;
3566 while (event != kbd_store_ptr);
3568 else
3569 return 1;
3572 if (!(flags & READABLE_EVENTS_IGNORE_SQUEEZABLES)
3573 && !NILP (do_mouse_tracking) && some_mouse_moved ())
3574 return 1;
3575 if (single_kboard)
3577 if (current_kboard->kbd_queue_has_data)
3578 return 1;
3580 else
3582 KBOARD *kb;
3583 for (kb = all_kboards; kb; kb = kb->next_kboard)
3584 if (kb->kbd_queue_has_data)
3585 return 1;
3587 return 0;
3590 /* Set this for debugging, to have a way to get out */
3591 int stop_character EXTERNALLY_VISIBLE;
3593 static KBOARD *
3594 event_to_kboard (struct input_event *event)
3596 /* Not applicable for these special events. */
3597 if (event->kind == SELECTION_REQUEST_EVENT
3598 || event->kind == SELECTION_CLEAR_EVENT)
3599 return NULL;
3600 else
3602 Lisp_Object obj = event->frame_or_window;
3603 /* There are some events that set this field to nil or string. */
3604 if (WINDOWP (obj))
3605 obj = WINDOW_FRAME (XWINDOW (obj));
3606 /* Also ignore dead frames here. */
3607 return ((FRAMEP (obj) && FRAME_LIVE_P (XFRAME (obj)))
3608 ? FRAME_KBOARD (XFRAME (obj)) : NULL);
3612 #ifdef subprocesses
3613 /* Return the number of slots occupied in kbd_buffer. */
3615 static int
3616 kbd_buffer_nr_stored (void)
3618 return kbd_fetch_ptr == kbd_store_ptr
3620 : (kbd_fetch_ptr < kbd_store_ptr
3621 ? kbd_store_ptr - kbd_fetch_ptr
3622 : ((kbd_buffer + KBD_BUFFER_SIZE) - kbd_fetch_ptr
3623 + (kbd_store_ptr - kbd_buffer)));
3625 #endif /* Store an event obtained at interrupt level into kbd_buffer, fifo */
3627 void
3628 kbd_buffer_store_event (register struct input_event *event)
3630 kbd_buffer_store_event_hold (event, 0);
3633 /* Store EVENT obtained at interrupt level into kbd_buffer, fifo.
3635 If HOLD_QUIT is 0, just stuff EVENT into the fifo.
3636 Else, if HOLD_QUIT.kind != NO_EVENT, discard EVENT.
3637 Else, if EVENT is a quit event, store the quit event
3638 in HOLD_QUIT, and return (thus ignoring further events).
3640 This is used to postpone the processing of the quit event until all
3641 subsequent input events have been parsed (and discarded). */
3643 void
3644 kbd_buffer_store_event_hold (register struct input_event *event,
3645 struct input_event *hold_quit)
3647 if (event->kind == NO_EVENT)
3648 emacs_abort ();
3650 if (hold_quit && hold_quit->kind != NO_EVENT)
3651 return;
3653 if (event->kind == ASCII_KEYSTROKE_EVENT)
3655 register int c = event->code & 0377;
3657 if (event->modifiers & ctrl_modifier)
3658 c = make_ctrl_char (c);
3660 c |= (event->modifiers
3661 & (meta_modifier | alt_modifier
3662 | hyper_modifier | super_modifier));
3664 if (c == quit_char)
3666 KBOARD *kb = FRAME_KBOARD (XFRAME (event->frame_or_window));
3667 struct input_event *sp;
3669 if (single_kboard && kb != current_kboard)
3671 kset_kbd_queue
3672 (kb, list2 (make_lispy_switch_frame (event->frame_or_window),
3673 make_number (c)));
3674 kb->kbd_queue_has_data = 1;
3675 for (sp = kbd_fetch_ptr; sp != kbd_store_ptr; sp++)
3677 if (sp == kbd_buffer + KBD_BUFFER_SIZE)
3678 sp = kbd_buffer;
3680 if (event_to_kboard (sp) == kb)
3682 sp->kind = NO_EVENT;
3683 sp->frame_or_window = Qnil;
3684 sp->arg = Qnil;
3687 return;
3690 if (hold_quit)
3692 *hold_quit = *event;
3693 return;
3696 /* If this results in a quit_char being returned to Emacs as
3697 input, set Vlast_event_frame properly. If this doesn't
3698 get returned to Emacs as an event, the next event read
3699 will set Vlast_event_frame again, so this is safe to do. */
3701 Lisp_Object focus;
3703 focus = FRAME_FOCUS_FRAME (XFRAME (event->frame_or_window));
3704 if (NILP (focus))
3705 focus = event->frame_or_window;
3706 internal_last_event_frame = focus;
3707 Vlast_event_frame = focus;
3710 handle_interrupt (0);
3711 return;
3714 if (c && c == stop_character)
3716 sys_suspend ();
3717 return;
3720 /* Don't insert two BUFFER_SWITCH_EVENT's in a row.
3721 Just ignore the second one. */
3722 else if (event->kind == BUFFER_SWITCH_EVENT
3723 && kbd_fetch_ptr != kbd_store_ptr
3724 && ((kbd_store_ptr == kbd_buffer
3725 ? kbd_buffer + KBD_BUFFER_SIZE - 1
3726 : kbd_store_ptr - 1)->kind) == BUFFER_SWITCH_EVENT)
3727 return;
3729 if (kbd_store_ptr - kbd_buffer == KBD_BUFFER_SIZE)
3730 kbd_store_ptr = kbd_buffer;
3732 /* Don't let the very last slot in the buffer become full,
3733 since that would make the two pointers equal,
3734 and that is indistinguishable from an empty buffer.
3735 Discard the event if it would fill the last slot. */
3736 if (kbd_fetch_ptr - 1 != kbd_store_ptr)
3738 *kbd_store_ptr = *event;
3739 ++kbd_store_ptr;
3740 #ifdef subprocesses
3741 if (kbd_buffer_nr_stored () > KBD_BUFFER_SIZE / 2
3742 && ! kbd_on_hold_p ())
3744 /* Don't read keyboard input until we have processed kbd_buffer.
3745 This happens when pasting text longer than KBD_BUFFER_SIZE/2. */
3746 hold_keyboard_input ();
3747 if (!noninteractive)
3748 ignore_sigio ();
3749 stop_polling ();
3751 #endif /* subprocesses */
3754 /* If we're inside while-no-input, and this event qualifies
3755 as input, set quit-flag to cause an interrupt. */
3756 if (!NILP (Vthrow_on_input)
3757 && event->kind != FOCUS_IN_EVENT
3758 && event->kind != HELP_EVENT
3759 && event->kind != DEICONIFY_EVENT)
3761 Vquit_flag = Vthrow_on_input;
3762 /* If we're inside a function that wants immediate quits,
3763 do it now. */
3764 if (immediate_quit && NILP (Vinhibit_quit))
3766 immediate_quit = 0;
3767 QUIT;
3773 /* Put an input event back in the head of the event queue. */
3775 void
3776 kbd_buffer_unget_event (register struct input_event *event)
3778 if (kbd_fetch_ptr == kbd_buffer)
3779 kbd_fetch_ptr = kbd_buffer + KBD_BUFFER_SIZE;
3781 /* Don't let the very last slot in the buffer become full, */
3782 if (kbd_fetch_ptr - 1 != kbd_store_ptr)
3784 --kbd_fetch_ptr;
3785 *kbd_fetch_ptr = *event;
3789 /* Limit help event positions to this range, to avoid overflow problems. */
3790 #define INPUT_EVENT_POS_MAX \
3791 ((ptrdiff_t) min (PTRDIFF_MAX, min (TYPE_MAXIMUM (Time) / 2, \
3792 MOST_POSITIVE_FIXNUM)))
3793 #define INPUT_EVENT_POS_MIN (-1 - INPUT_EVENT_POS_MAX)
3795 /* Return a Time that encodes position POS. POS must be in range. */
3797 static Time
3798 position_to_Time (ptrdiff_t pos)
3800 eassert (INPUT_EVENT_POS_MIN <= pos && pos <= INPUT_EVENT_POS_MAX);
3801 return pos;
3804 /* Return the position that ENCODED_POS encodes.
3805 Avoid signed integer overflow. */
3807 static ptrdiff_t
3808 Time_to_position (Time encoded_pos)
3810 if (encoded_pos <= INPUT_EVENT_POS_MAX)
3811 return encoded_pos;
3812 Time encoded_pos_min = INPUT_EVENT_POS_MIN;
3813 eassert (encoded_pos_min <= encoded_pos);
3814 ptrdiff_t notpos = -1 - encoded_pos;
3815 return -1 - notpos;
3818 /* Generate a HELP_EVENT input_event and store it in the keyboard
3819 buffer.
3821 HELP is the help form.
3823 FRAME and WINDOW are the frame and window where the help is
3824 generated. OBJECT is the Lisp object where the help was found (a
3825 buffer, a string, an overlay, or nil if neither from a string nor
3826 from a buffer). POS is the position within OBJECT where the help
3827 was found. */
3829 void
3830 gen_help_event (Lisp_Object help, Lisp_Object frame, Lisp_Object window,
3831 Lisp_Object object, ptrdiff_t pos)
3833 struct input_event event;
3835 event.kind = HELP_EVENT;
3836 event.frame_or_window = frame;
3837 event.arg = object;
3838 event.x = WINDOWP (window) ? window : frame;
3839 event.y = help;
3840 event.timestamp = position_to_Time (pos);
3841 kbd_buffer_store_event (&event);
3845 /* Store HELP_EVENTs for HELP on FRAME in the input queue. */
3847 void
3848 kbd_buffer_store_help_event (Lisp_Object frame, Lisp_Object help)
3850 struct input_event event;
3852 event.kind = HELP_EVENT;
3853 event.frame_or_window = frame;
3854 event.arg = Qnil;
3855 event.x = Qnil;
3856 event.y = help;
3857 event.timestamp = 0;
3858 kbd_buffer_store_event (&event);
3862 /* Discard any mouse events in the event buffer by setting them to
3863 NO_EVENT. */
3864 void
3865 discard_mouse_events (void)
3867 struct input_event *sp;
3868 for (sp = kbd_fetch_ptr; sp != kbd_store_ptr; sp++)
3870 if (sp == kbd_buffer + KBD_BUFFER_SIZE)
3871 sp = kbd_buffer;
3873 if (sp->kind == MOUSE_CLICK_EVENT
3874 || sp->kind == WHEEL_EVENT
3875 || sp->kind == HORIZ_WHEEL_EVENT
3876 #ifdef HAVE_GPM
3877 || sp->kind == GPM_CLICK_EVENT
3878 #endif
3879 || sp->kind == SCROLL_BAR_CLICK_EVENT
3880 || sp->kind == HORIZONTAL_SCROLL_BAR_CLICK_EVENT)
3882 sp->kind = NO_EVENT;
3888 /* Return true if there are any real events waiting in the event
3889 buffer, not counting `NO_EVENT's.
3891 Discard NO_EVENT events at the front of the input queue, possibly
3892 leaving the input queue empty if there are no real input events. */
3894 bool
3895 kbd_buffer_events_waiting (void)
3897 struct input_event *sp;
3899 for (sp = kbd_fetch_ptr;
3900 sp != kbd_store_ptr && sp->kind == NO_EVENT;
3901 ++sp)
3903 if (sp == kbd_buffer + KBD_BUFFER_SIZE)
3904 sp = kbd_buffer;
3907 kbd_fetch_ptr = sp;
3908 return sp != kbd_store_ptr && sp->kind != NO_EVENT;
3912 /* Clear input event EVENT. */
3914 static void
3915 clear_event (struct input_event *event)
3917 event->kind = NO_EVENT;
3921 /* Read one event from the event buffer, waiting if necessary.
3922 The value is a Lisp object representing the event.
3923 The value is nil for an event that should be ignored,
3924 or that was handled here.
3925 We always read and discard one event. */
3927 static Lisp_Object
3928 kbd_buffer_get_event (KBOARD **kbp,
3929 bool *used_mouse_menu,
3930 struct timespec *end_time)
3932 Lisp_Object obj;
3934 #ifdef subprocesses
3935 if (kbd_on_hold_p () && kbd_buffer_nr_stored () < KBD_BUFFER_SIZE / 4)
3937 /* Start reading input again because we have processed enough to
3938 be able to accept new events again. */
3939 unhold_keyboard_input ();
3940 start_polling ();
3942 #endif /* subprocesses */
3944 #if !defined HAVE_DBUS && !defined USE_FILE_NOTIFY
3945 if (noninteractive
3946 /* In case we are running as a daemon, only do this before
3947 detaching from the terminal. */
3948 || (IS_DAEMON && daemon_pipe[1] >= 0))
3950 int c = getchar ();
3951 XSETINT (obj, c);
3952 *kbp = current_kboard;
3953 return obj;
3955 #endif /* !defined HAVE_DBUS && !defined USE_FILE_NOTIFY */
3957 /* Wait until there is input available. */
3958 for (;;)
3960 /* Break loop if there's an unread command event. Needed in
3961 moused window autoselection which uses a timer to insert such
3962 events. */
3963 if (CONSP (Vunread_command_events))
3964 break;
3966 if (kbd_fetch_ptr != kbd_store_ptr)
3967 break;
3968 if (!NILP (do_mouse_tracking) && some_mouse_moved ())
3969 break;
3971 /* If the quit flag is set, then read_char will return
3972 quit_char, so that counts as "available input." */
3973 if (!NILP (Vquit_flag))
3974 quit_throw_to_read_char (0);
3976 /* One way or another, wait until input is available; then, if
3977 interrupt handlers have not read it, read it now. */
3979 #ifdef USABLE_SIGIO
3980 gobble_input ();
3981 #endif
3982 if (kbd_fetch_ptr != kbd_store_ptr)
3983 break;
3984 if (!NILP (do_mouse_tracking) && some_mouse_moved ())
3985 break;
3986 if (end_time)
3988 struct timespec now = current_timespec ();
3989 if (timespec_cmp (*end_time, now) <= 0)
3990 return Qnil; /* Finished waiting. */
3991 else
3993 struct timespec duration = timespec_sub (*end_time, now);
3994 wait_reading_process_output (min (duration.tv_sec,
3995 WAIT_READING_MAX),
3996 duration.tv_nsec,
3997 -1, 1, Qnil, NULL, 0);
4000 else
4002 bool do_display = true;
4004 if (FRAME_TERMCAP_P (SELECTED_FRAME ()))
4006 struct tty_display_info *tty = CURTTY ();
4008 /* When this TTY is displaying a menu, we must prevent
4009 any redisplay, because we modify the frame's glyph
4010 matrix behind the back of the display engine. */
4011 if (tty->showing_menu)
4012 do_display = false;
4015 wait_reading_process_output (0, 0, -1, do_display, Qnil, NULL, 0);
4018 if (!interrupt_input && kbd_fetch_ptr == kbd_store_ptr)
4019 gobble_input ();
4022 if (CONSP (Vunread_command_events))
4024 Lisp_Object first;
4025 first = XCAR (Vunread_command_events);
4026 Vunread_command_events = XCDR (Vunread_command_events);
4027 *kbp = current_kboard;
4028 return first;
4031 /* At this point, we know that there is a readable event available
4032 somewhere. If the event queue is empty, then there must be a
4033 mouse movement enabled and available. */
4034 if (kbd_fetch_ptr != kbd_store_ptr)
4036 struct input_event *event;
4038 event = ((kbd_fetch_ptr < kbd_buffer + KBD_BUFFER_SIZE)
4039 ? kbd_fetch_ptr
4040 : kbd_buffer);
4042 *kbp = event_to_kboard (event);
4043 if (*kbp == 0)
4044 *kbp = current_kboard; /* Better than returning null ptr? */
4046 obj = Qnil;
4048 /* These two kinds of events get special handling
4049 and don't actually appear to the command loop.
4050 We return nil for them. */
4051 if (event->kind == SELECTION_REQUEST_EVENT
4052 || event->kind == SELECTION_CLEAR_EVENT)
4054 #ifdef HAVE_X11
4055 struct input_event copy;
4057 /* Remove it from the buffer before processing it,
4058 since otherwise swallow_events will see it
4059 and process it again. */
4060 copy = *event;
4061 kbd_fetch_ptr = event + 1;
4062 input_pending = readable_events (0);
4063 x_handle_selection_event (&copy);
4064 #else
4065 /* We're getting selection request events, but we don't have
4066 a window system. */
4067 emacs_abort ();
4068 #endif
4071 #if defined (HAVE_NS)
4072 else if (event->kind == NS_TEXT_EVENT)
4074 if (event->code == KEY_NS_PUT_WORKING_TEXT)
4075 obj = list1 (intern ("ns-put-working-text"));
4076 else
4077 obj = list1 (intern ("ns-unput-working-text"));
4078 kbd_fetch_ptr = event + 1;
4079 if (used_mouse_menu)
4080 *used_mouse_menu = 1;
4082 #endif
4084 #if defined (HAVE_X11) || defined (HAVE_NTGUI) \
4085 || defined (HAVE_NS)
4086 else if (event->kind == DELETE_WINDOW_EVENT)
4088 /* Make an event (delete-frame (FRAME)). */
4089 obj = list2 (Qdelete_frame, list1 (event->frame_or_window));
4090 kbd_fetch_ptr = event + 1;
4092 #endif
4093 #if defined (HAVE_X11) || defined (HAVE_NTGUI) \
4094 || defined (HAVE_NS)
4095 else if (event->kind == ICONIFY_EVENT)
4097 /* Make an event (iconify-frame (FRAME)). */
4098 obj = list2 (Qiconify_frame, list1 (event->frame_or_window));
4099 kbd_fetch_ptr = event + 1;
4101 else if (event->kind == DEICONIFY_EVENT)
4103 /* Make an event (make-frame-visible (FRAME)). */
4104 obj = list2 (Qmake_frame_visible, list1 (event->frame_or_window));
4105 kbd_fetch_ptr = event + 1;
4107 #endif
4108 else if (event->kind == BUFFER_SWITCH_EVENT)
4110 /* The value doesn't matter here; only the type is tested. */
4111 XSETBUFFER (obj, current_buffer);
4112 kbd_fetch_ptr = event + 1;
4114 #if defined (USE_X_TOOLKIT) || defined (HAVE_NTGUI) \
4115 || defined (HAVE_NS) || defined (USE_GTK)
4116 else if (event->kind == MENU_BAR_ACTIVATE_EVENT)
4118 kbd_fetch_ptr = event + 1;
4119 input_pending = readable_events (0);
4120 if (FRAME_LIVE_P (XFRAME (event->frame_or_window)))
4121 x_activate_menubar (XFRAME (event->frame_or_window));
4123 #endif
4124 #ifdef HAVE_NTGUI
4125 else if (event->kind == LANGUAGE_CHANGE_EVENT)
4127 /* Make an event (language-change FRAME CODEPAGE LANGUAGE-ID). */
4128 obj = list4 (Qlanguage_change,
4129 event->frame_or_window,
4130 make_number (event->code),
4131 make_number (event->modifiers));
4132 kbd_fetch_ptr = event + 1;
4134 #endif
4135 #ifdef USE_FILE_NOTIFY
4136 else if (event->kind == FILE_NOTIFY_EVENT)
4138 #ifdef HAVE_W32NOTIFY
4139 /* Make an event (file-notify (DESCRIPTOR ACTION FILE) CALLBACK). */
4140 obj = list3 (Qfile_notify,
4141 list3 (make_number (event->code),
4142 XCAR (event->arg),
4143 XCDR (event->arg)),
4144 event->frame_or_window);
4145 #else
4146 obj = make_lispy_event (event);
4147 #endif
4148 kbd_fetch_ptr = event + 1;
4150 #endif /* USE_FILE_NOTIFY */
4151 else if (event->kind == SAVE_SESSION_EVENT)
4153 obj = list2 (Qsave_session, event->arg);
4154 kbd_fetch_ptr = event + 1;
4156 /* Just discard these, by returning nil.
4157 With MULTI_KBOARD, these events are used as placeholders
4158 when we need to randomly delete events from the queue.
4159 (They shouldn't otherwise be found in the buffer,
4160 but on some machines it appears they do show up
4161 even without MULTI_KBOARD.) */
4162 /* On Windows NT/9X, NO_EVENT is used to delete extraneous
4163 mouse events during a popup-menu call. */
4164 else if (event->kind == NO_EVENT)
4165 kbd_fetch_ptr = event + 1;
4166 else if (event->kind == HELP_EVENT)
4168 Lisp_Object object, position, help, frame, window;
4170 frame = event->frame_or_window;
4171 object = event->arg;
4172 position = make_number (Time_to_position (event->timestamp));
4173 window = event->x;
4174 help = event->y;
4175 clear_event (event);
4177 kbd_fetch_ptr = event + 1;
4178 if (!WINDOWP (window))
4179 window = Qnil;
4180 obj = Fcons (Qhelp_echo,
4181 list5 (frame, help, window, object, position));
4183 else if (event->kind == FOCUS_IN_EVENT)
4185 /* Notification of a FocusIn event. The frame receiving the
4186 focus is in event->frame_or_window. Generate a
4187 switch-frame event if necessary. */
4188 Lisp_Object frame, focus;
4190 frame = event->frame_or_window;
4191 focus = FRAME_FOCUS_FRAME (XFRAME (frame));
4192 if (FRAMEP (focus))
4193 frame = focus;
4195 if (
4196 #ifdef HAVE_X11
4197 ! NILP (event->arg)
4199 #endif
4200 !EQ (frame, internal_last_event_frame)
4201 && !EQ (frame, selected_frame))
4202 obj = make_lispy_switch_frame (frame);
4203 else
4204 obj = make_lispy_focus_in (frame);
4206 internal_last_event_frame = frame;
4207 kbd_fetch_ptr = event + 1;
4209 else if (event->kind == FOCUS_OUT_EVENT)
4211 #ifdef HAVE_WINDOW_SYSTEM
4213 Display_Info *di;
4214 Lisp_Object frame = event->frame_or_window;
4215 bool focused = false;
4217 for (di = x_display_list; di && ! focused; di = di->next)
4218 focused = di->x_highlight_frame != 0;
4220 if (!focused)
4221 obj = make_lispy_focus_out (frame);
4223 #endif /* HAVE_WINDOW_SYSTEM */
4225 kbd_fetch_ptr = event + 1;
4227 #ifdef HAVE_DBUS
4228 else if (event->kind == DBUS_EVENT)
4230 obj = make_lispy_event (event);
4231 kbd_fetch_ptr = event + 1;
4233 #endif
4234 #ifdef HAVE_XWIDGETS
4235 else if (event->kind == XWIDGET_EVENT)
4237 obj = make_lispy_event (event);
4238 kbd_fetch_ptr = event + 1;
4240 #endif
4241 #ifdef HAVE_INOTIFY
4242 else if (event->kind == FILE_NOTIFY_EVENT)
4244 obj = make_lispy_event (event);
4245 kbd_fetch_ptr = event + 1;
4247 #endif
4248 else if (event->kind == CONFIG_CHANGED_EVENT)
4250 obj = make_lispy_event (event);
4251 kbd_fetch_ptr = event + 1;
4253 else
4255 /* If this event is on a different frame, return a switch-frame this
4256 time, and leave the event in the queue for next time. */
4257 Lisp_Object frame;
4258 Lisp_Object focus;
4260 frame = event->frame_or_window;
4261 if (CONSP (frame))
4262 frame = XCAR (frame);
4263 else if (WINDOWP (frame))
4264 frame = WINDOW_FRAME (XWINDOW (frame));
4266 focus = FRAME_FOCUS_FRAME (XFRAME (frame));
4267 if (! NILP (focus))
4268 frame = focus;
4270 if (! EQ (frame, internal_last_event_frame)
4271 && !EQ (frame, selected_frame))
4272 obj = make_lispy_switch_frame (frame);
4273 internal_last_event_frame = frame;
4275 /* If we didn't decide to make a switch-frame event, go ahead
4276 and build a real event from the queue entry. */
4278 if (NILP (obj))
4280 obj = make_lispy_event (event);
4282 #if defined (USE_X_TOOLKIT) || defined (HAVE_NTGUI) \
4283 || defined (HAVE_NS) || defined (USE_GTK)
4284 /* If this was a menu selection, then set the flag to inhibit
4285 writing to last_nonmenu_event. Don't do this if the event
4286 we're returning is (menu-bar), though; that indicates the
4287 beginning of the menu sequence, and we might as well leave
4288 that as the `event with parameters' for this selection. */
4289 if (used_mouse_menu
4290 && !EQ (event->frame_or_window, event->arg)
4291 && (event->kind == MENU_BAR_EVENT
4292 || event->kind == TOOL_BAR_EVENT))
4293 *used_mouse_menu = 1;
4294 #endif
4295 #ifdef HAVE_NS
4296 /* Certain system events are non-key events. */
4297 if (used_mouse_menu
4298 && event->kind == NS_NONKEY_EVENT)
4299 *used_mouse_menu = 1;
4300 #endif
4302 /* Wipe out this event, to catch bugs. */
4303 clear_event (event);
4304 kbd_fetch_ptr = event + 1;
4308 /* Try generating a mouse motion event. */
4309 else if (!NILP (do_mouse_tracking) && some_mouse_moved ())
4311 struct frame *f = some_mouse_moved ();
4312 Lisp_Object bar_window;
4313 enum scroll_bar_part part;
4314 Lisp_Object x, y;
4315 Time t;
4317 *kbp = current_kboard;
4318 /* Note that this uses F to determine which terminal to look at.
4319 If there is no valid info, it does not store anything
4320 so x remains nil. */
4321 x = Qnil;
4323 /* XXX Can f or mouse_position_hook be NULL here? */
4324 if (f && FRAME_TERMINAL (f)->mouse_position_hook)
4325 (*FRAME_TERMINAL (f)->mouse_position_hook) (&f, 0, &bar_window,
4326 &part, &x, &y, &t);
4328 obj = Qnil;
4330 /* Decide if we should generate a switch-frame event. Don't
4331 generate switch-frame events for motion outside of all Emacs
4332 frames. */
4333 if (!NILP (x) && f)
4335 Lisp_Object frame;
4337 frame = FRAME_FOCUS_FRAME (f);
4338 if (NILP (frame))
4339 XSETFRAME (frame, f);
4341 if (! EQ (frame, internal_last_event_frame)
4342 && !EQ (frame, selected_frame))
4343 obj = make_lispy_switch_frame (frame);
4344 internal_last_event_frame = frame;
4347 /* If we didn't decide to make a switch-frame event, go ahead and
4348 return a mouse-motion event. */
4349 if (!NILP (x) && NILP (obj))
4350 obj = make_lispy_movement (f, bar_window, part, x, y, t);
4352 else
4353 /* We were promised by the above while loop that there was
4354 something for us to read! */
4355 emacs_abort ();
4357 input_pending = readable_events (0);
4359 Vlast_event_frame = internal_last_event_frame;
4361 return (obj);
4364 /* Process any non-user-visible events (currently X selection events),
4365 without reading any user-visible events. */
4367 static void
4368 process_special_events (void)
4370 struct input_event *event;
4372 for (event = kbd_fetch_ptr; event != kbd_store_ptr; ++event)
4374 if (event == kbd_buffer + KBD_BUFFER_SIZE)
4376 event = kbd_buffer;
4377 if (event == kbd_store_ptr)
4378 break;
4381 /* If we find a stored X selection request, handle it now. */
4382 if (event->kind == SELECTION_REQUEST_EVENT
4383 || event->kind == SELECTION_CLEAR_EVENT)
4385 #ifdef HAVE_X11
4387 /* Remove the event from the fifo buffer before processing;
4388 otherwise swallow_events called recursively could see it
4389 and process it again. To do this, we move the events
4390 between kbd_fetch_ptr and EVENT one slot to the right,
4391 cyclically. */
4393 struct input_event copy = *event;
4394 struct input_event *beg
4395 = (kbd_fetch_ptr == kbd_buffer + KBD_BUFFER_SIZE)
4396 ? kbd_buffer : kbd_fetch_ptr;
4398 if (event > beg)
4399 memmove (beg + 1, beg, (event - beg) * sizeof (struct input_event));
4400 else if (event < beg)
4402 if (event > kbd_buffer)
4403 memmove (kbd_buffer + 1, kbd_buffer,
4404 (event - kbd_buffer) * sizeof (struct input_event));
4405 *kbd_buffer = *(kbd_buffer + KBD_BUFFER_SIZE - 1);
4406 if (beg < kbd_buffer + KBD_BUFFER_SIZE - 1)
4407 memmove (beg + 1, beg,
4408 (kbd_buffer + KBD_BUFFER_SIZE - 1 - beg)
4409 * sizeof (struct input_event));
4412 if (kbd_fetch_ptr == kbd_buffer + KBD_BUFFER_SIZE)
4413 kbd_fetch_ptr = kbd_buffer + 1;
4414 else
4415 kbd_fetch_ptr++;
4417 input_pending = readable_events (0);
4418 x_handle_selection_event (&copy);
4419 #else
4420 /* We're getting selection request events, but we don't have
4421 a window system. */
4422 emacs_abort ();
4423 #endif
4428 /* Process any events that are not user-visible, run timer events that
4429 are ripe, and return, without reading any user-visible events. */
4431 void
4432 swallow_events (bool do_display)
4434 unsigned old_timers_run;
4436 process_special_events ();
4438 old_timers_run = timers_run;
4439 get_input_pending (READABLE_EVENTS_DO_TIMERS_NOW);
4441 if (!input_pending && timers_run != old_timers_run && do_display)
4442 redisplay_preserve_echo_area (7);
4445 /* Record the start of when Emacs is idle,
4446 for the sake of running idle-time timers. */
4448 static void
4449 timer_start_idle (void)
4451 /* If we are already in the idle state, do nothing. */
4452 if (timespec_valid_p (timer_idleness_start_time))
4453 return;
4455 timer_idleness_start_time = current_timespec ();
4456 timer_last_idleness_start_time = timer_idleness_start_time;
4458 /* Mark all idle-time timers as once again candidates for running. */
4459 call0 (intern ("internal-timer-start-idle"));
4462 /* Record that Emacs is no longer idle, so stop running idle-time timers. */
4464 static void
4465 timer_stop_idle (void)
4467 timer_idleness_start_time = invalid_timespec ();
4470 /* Resume idle timer from last idle start time. */
4472 static void
4473 timer_resume_idle (void)
4475 if (timespec_valid_p (timer_idleness_start_time))
4476 return;
4478 timer_idleness_start_time = timer_last_idleness_start_time;
4481 /* This is only for debugging. */
4482 struct input_event last_timer_event EXTERNALLY_VISIBLE;
4484 /* List of elisp functions to call, delayed because they were generated in
4485 a context where Elisp could not be safely run (e.g. redisplay, signal,
4486 ...). Each element has the form (FUN . ARGS). */
4487 Lisp_Object pending_funcalls;
4489 /* Return true if TIMER is a valid timer, placing its value into *RESULT. */
4490 static bool
4491 decode_timer (Lisp_Object timer, struct timespec *result)
4493 Lisp_Object *vector;
4495 if (! (VECTORP (timer) && ASIZE (timer) == 9))
4496 return 0;
4497 vector = XVECTOR (timer)->contents;
4498 if (! NILP (vector[0]))
4499 return 0;
4500 if (! INTEGERP (vector[2]))
4501 return false;
4503 struct lisp_time t;
4504 if (! decode_time_components (vector[1], vector[2], vector[3], vector[8],
4505 &t, 0))
4506 return false;
4507 *result = lisp_to_timespec (t);
4508 return timespec_valid_p (*result);
4512 /* Check whether a timer has fired. To prevent larger problems we simply
4513 disregard elements that are not proper timers. Do not make a circular
4514 timer list for the time being.
4516 Returns the time to wait until the next timer fires. If a
4517 timer is triggering now, return zero.
4518 If no timer is active, return -1.
4520 If a timer is ripe, we run it, with quitting turned off.
4521 In that case we return 0 to indicate that a new timer_check_2 call
4522 should be done. */
4524 static struct timespec
4525 timer_check_2 (Lisp_Object timers, Lisp_Object idle_timers)
4527 struct timespec nexttime;
4528 struct timespec now;
4529 struct timespec idleness_now;
4530 Lisp_Object chosen_timer;
4531 struct gcpro gcpro1;
4533 nexttime = invalid_timespec ();
4535 chosen_timer = Qnil;
4536 GCPRO1 (chosen_timer);
4538 /* First run the code that was delayed. */
4539 while (CONSP (pending_funcalls))
4541 Lisp_Object funcall = XCAR (pending_funcalls);
4542 pending_funcalls = XCDR (pending_funcalls);
4543 safe_call2 (Qapply, XCAR (funcall), XCDR (funcall));
4546 if (CONSP (timers) || CONSP (idle_timers))
4548 now = current_timespec ();
4549 idleness_now = (timespec_valid_p (timer_idleness_start_time)
4550 ? timespec_sub (now, timer_idleness_start_time)
4551 : make_timespec (0, 0));
4554 while (CONSP (timers) || CONSP (idle_timers))
4556 Lisp_Object timer = Qnil, idle_timer = Qnil;
4557 struct timespec timer_time, idle_timer_time;
4558 struct timespec difference;
4559 struct timespec timer_difference = invalid_timespec ();
4560 struct timespec idle_timer_difference = invalid_timespec ();
4561 bool ripe, timer_ripe = 0, idle_timer_ripe = 0;
4563 /* Set TIMER and TIMER_DIFFERENCE
4564 based on the next ordinary timer.
4565 TIMER_DIFFERENCE is the distance in time from NOW to when
4566 this timer becomes ripe (negative if it's already ripe).
4567 Skip past invalid timers and timers already handled. */
4568 if (CONSP (timers))
4570 timer = XCAR (timers);
4571 if (! decode_timer (timer, &timer_time))
4573 timers = XCDR (timers);
4574 continue;
4577 timer_ripe = timespec_cmp (timer_time, now) <= 0;
4578 timer_difference = (timer_ripe
4579 ? timespec_sub (now, timer_time)
4580 : timespec_sub (timer_time, now));
4583 /* Likewise for IDLE_TIMER and IDLE_TIMER_DIFFERENCE
4584 based on the next idle timer. */
4585 if (CONSP (idle_timers))
4587 idle_timer = XCAR (idle_timers);
4588 if (! decode_timer (idle_timer, &idle_timer_time))
4590 idle_timers = XCDR (idle_timers);
4591 continue;
4594 idle_timer_ripe = timespec_cmp (idle_timer_time, idleness_now) <= 0;
4595 idle_timer_difference
4596 = (idle_timer_ripe
4597 ? timespec_sub (idleness_now, idle_timer_time)
4598 : timespec_sub (idle_timer_time, idleness_now));
4601 /* Decide which timer is the next timer,
4602 and set CHOSEN_TIMER, DIFFERENCE, and RIPE accordingly.
4603 Also step down the list where we found that timer. */
4605 if (timespec_valid_p (timer_difference)
4606 && (! timespec_valid_p (idle_timer_difference)
4607 || idle_timer_ripe < timer_ripe
4608 || (idle_timer_ripe == timer_ripe
4609 && ((timer_ripe
4610 ? timespec_cmp (idle_timer_difference,
4611 timer_difference)
4612 : timespec_cmp (timer_difference,
4613 idle_timer_difference))
4614 < 0))))
4616 chosen_timer = timer;
4617 timers = XCDR (timers);
4618 difference = timer_difference;
4619 ripe = timer_ripe;
4621 else
4623 chosen_timer = idle_timer;
4624 idle_timers = XCDR (idle_timers);
4625 difference = idle_timer_difference;
4626 ripe = idle_timer_ripe;
4629 /* If timer is ripe, run it if it hasn't been run. */
4630 if (ripe)
4632 if (NILP (AREF (chosen_timer, 0)))
4634 ptrdiff_t count = SPECPDL_INDEX ();
4635 Lisp_Object old_deactivate_mark = Vdeactivate_mark;
4637 /* Mark the timer as triggered to prevent problems if the lisp
4638 code fails to reschedule it right. */
4639 ASET (chosen_timer, 0, Qt);
4641 specbind (Qinhibit_quit, Qt);
4643 call1 (Qtimer_event_handler, chosen_timer);
4644 Vdeactivate_mark = old_deactivate_mark;
4645 timers_run++;
4646 unbind_to (count, Qnil);
4648 /* Since we have handled the event,
4649 we don't need to tell the caller to wake up and do it. */
4650 /* But the caller must still wait for the next timer, so
4651 return 0 to indicate that. */
4654 nexttime = make_timespec (0, 0);
4655 break;
4657 else
4658 /* When we encounter a timer that is still waiting,
4659 return the amount of time to wait before it is ripe. */
4661 UNGCPRO;
4662 return difference;
4666 /* No timers are pending in the future. */
4667 /* Return 0 if we generated an event, and -1 if not. */
4668 UNGCPRO;
4669 return nexttime;
4673 /* Check whether a timer has fired. To prevent larger problems we simply
4674 disregard elements that are not proper timers. Do not make a circular
4675 timer list for the time being.
4677 Returns the time to wait until the next timer fires.
4678 If no timer is active, return an invalid value.
4680 As long as any timer is ripe, we run it. */
4682 struct timespec
4683 timer_check (void)
4685 struct timespec nexttime;
4686 Lisp_Object timers, idle_timers;
4687 struct gcpro gcpro1, gcpro2;
4689 Lisp_Object tem = Vinhibit_quit;
4690 Vinhibit_quit = Qt;
4692 /* We use copies of the timers' lists to allow a timer to add itself
4693 again, without locking up Emacs if the newly added timer is
4694 already ripe when added. */
4696 /* Always consider the ordinary timers. */
4697 timers = Fcopy_sequence (Vtimer_list);
4698 /* Consider the idle timers only if Emacs is idle. */
4699 if (timespec_valid_p (timer_idleness_start_time))
4700 idle_timers = Fcopy_sequence (Vtimer_idle_list);
4701 else
4702 idle_timers = Qnil;
4704 Vinhibit_quit = tem;
4706 GCPRO2 (timers, idle_timers);
4710 nexttime = timer_check_2 (timers, idle_timers);
4712 while (nexttime.tv_sec == 0 && nexttime.tv_nsec == 0);
4714 UNGCPRO;
4715 return nexttime;
4718 DEFUN ("current-idle-time", Fcurrent_idle_time, Scurrent_idle_time, 0, 0, 0,
4719 doc: /* Return the current length of Emacs idleness, or nil.
4720 The value when Emacs is idle is a list of four integers (HIGH LOW USEC PSEC)
4721 in the same style as (current-time).
4723 The value when Emacs is not idle is nil.
4725 PSEC is a multiple of the system clock resolution. */)
4726 (void)
4728 if (timespec_valid_p (timer_idleness_start_time))
4729 return make_lisp_time (timespec_sub (current_timespec (),
4730 timer_idleness_start_time));
4732 return Qnil;
4735 /* Caches for modify_event_symbol. */
4736 static Lisp_Object accent_key_syms;
4737 static Lisp_Object func_key_syms;
4738 static Lisp_Object mouse_syms;
4739 static Lisp_Object wheel_syms;
4740 static Lisp_Object drag_n_drop_syms;
4742 /* This is a list of keysym codes for special "accent" characters.
4743 It parallels lispy_accent_keys. */
4745 static const int lispy_accent_codes[] =
4747 #ifdef XK_dead_circumflex
4748 XK_dead_circumflex,
4749 #else
4751 #endif
4752 #ifdef XK_dead_grave
4753 XK_dead_grave,
4754 #else
4756 #endif
4757 #ifdef XK_dead_tilde
4758 XK_dead_tilde,
4759 #else
4761 #endif
4762 #ifdef XK_dead_diaeresis
4763 XK_dead_diaeresis,
4764 #else
4766 #endif
4767 #ifdef XK_dead_macron
4768 XK_dead_macron,
4769 #else
4771 #endif
4772 #ifdef XK_dead_degree
4773 XK_dead_degree,
4774 #else
4776 #endif
4777 #ifdef XK_dead_acute
4778 XK_dead_acute,
4779 #else
4781 #endif
4782 #ifdef XK_dead_cedilla
4783 XK_dead_cedilla,
4784 #else
4786 #endif
4787 #ifdef XK_dead_breve
4788 XK_dead_breve,
4789 #else
4791 #endif
4792 #ifdef XK_dead_ogonek
4793 XK_dead_ogonek,
4794 #else
4796 #endif
4797 #ifdef XK_dead_caron
4798 XK_dead_caron,
4799 #else
4801 #endif
4802 #ifdef XK_dead_doubleacute
4803 XK_dead_doubleacute,
4804 #else
4806 #endif
4807 #ifdef XK_dead_abovedot
4808 XK_dead_abovedot,
4809 #else
4811 #endif
4812 #ifdef XK_dead_abovering
4813 XK_dead_abovering,
4814 #else
4816 #endif
4817 #ifdef XK_dead_iota
4818 XK_dead_iota,
4819 #else
4821 #endif
4822 #ifdef XK_dead_belowdot
4823 XK_dead_belowdot,
4824 #else
4826 #endif
4827 #ifdef XK_dead_voiced_sound
4828 XK_dead_voiced_sound,
4829 #else
4831 #endif
4832 #ifdef XK_dead_semivoiced_sound
4833 XK_dead_semivoiced_sound,
4834 #else
4836 #endif
4837 #ifdef XK_dead_hook
4838 XK_dead_hook,
4839 #else
4841 #endif
4842 #ifdef XK_dead_horn
4843 XK_dead_horn,
4844 #else
4846 #endif
4849 /* This is a list of Lisp names for special "accent" characters.
4850 It parallels lispy_accent_codes. */
4852 static const char *const lispy_accent_keys[] =
4854 "dead-circumflex",
4855 "dead-grave",
4856 "dead-tilde",
4857 "dead-diaeresis",
4858 "dead-macron",
4859 "dead-degree",
4860 "dead-acute",
4861 "dead-cedilla",
4862 "dead-breve",
4863 "dead-ogonek",
4864 "dead-caron",
4865 "dead-doubleacute",
4866 "dead-abovedot",
4867 "dead-abovering",
4868 "dead-iota",
4869 "dead-belowdot",
4870 "dead-voiced-sound",
4871 "dead-semivoiced-sound",
4872 "dead-hook",
4873 "dead-horn",
4876 #ifdef HAVE_NTGUI
4877 #define FUNCTION_KEY_OFFSET 0x0
4879 const char *const lispy_function_keys[] =
4881 0, /* 0 */
4883 0, /* VK_LBUTTON 0x01 */
4884 0, /* VK_RBUTTON 0x02 */
4885 "cancel", /* VK_CANCEL 0x03 */
4886 0, /* VK_MBUTTON 0x04 */
4888 0, 0, 0, /* 0x05 .. 0x07 */
4890 "backspace", /* VK_BACK 0x08 */
4891 "tab", /* VK_TAB 0x09 */
4893 0, 0, /* 0x0A .. 0x0B */
4895 "clear", /* VK_CLEAR 0x0C */
4896 "return", /* VK_RETURN 0x0D */
4898 0, 0, /* 0x0E .. 0x0F */
4900 0, /* VK_SHIFT 0x10 */
4901 0, /* VK_CONTROL 0x11 */
4902 0, /* VK_MENU 0x12 */
4903 "pause", /* VK_PAUSE 0x13 */
4904 "capslock", /* VK_CAPITAL 0x14 */
4905 "kana", /* VK_KANA/VK_HANGUL 0x15 */
4906 0, /* 0x16 */
4907 "junja", /* VK_JUNJA 0x17 */
4908 "final", /* VK_FINAL 0x18 */
4909 "kanji", /* VK_KANJI/VK_HANJA 0x19 */
4910 0, /* 0x1A */
4911 "escape", /* VK_ESCAPE 0x1B */
4912 "convert", /* VK_CONVERT 0x1C */
4913 "non-convert", /* VK_NONCONVERT 0x1D */
4914 "accept", /* VK_ACCEPT 0x1E */
4915 "mode-change", /* VK_MODECHANGE 0x1F */
4916 0, /* VK_SPACE 0x20 */
4917 "prior", /* VK_PRIOR 0x21 */
4918 "next", /* VK_NEXT 0x22 */
4919 "end", /* VK_END 0x23 */
4920 "home", /* VK_HOME 0x24 */
4921 "left", /* VK_LEFT 0x25 */
4922 "up", /* VK_UP 0x26 */
4923 "right", /* VK_RIGHT 0x27 */
4924 "down", /* VK_DOWN 0x28 */
4925 "select", /* VK_SELECT 0x29 */
4926 "print", /* VK_PRINT 0x2A */
4927 "execute", /* VK_EXECUTE 0x2B */
4928 "snapshot", /* VK_SNAPSHOT 0x2C */
4929 "insert", /* VK_INSERT 0x2D */
4930 "delete", /* VK_DELETE 0x2E */
4931 "help", /* VK_HELP 0x2F */
4933 /* VK_0 thru VK_9 are the same as ASCII '0' thru '9' (0x30 - 0x39) */
4935 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
4937 0, 0, 0, 0, 0, 0, 0, /* 0x3A .. 0x40 */
4939 /* VK_A thru VK_Z are the same as ASCII 'A' thru 'Z' (0x41 - 0x5A) */
4941 0, 0, 0, 0, 0, 0, 0, 0, 0,
4942 0, 0, 0, 0, 0, 0, 0, 0, 0,
4943 0, 0, 0, 0, 0, 0, 0, 0,
4945 "lwindow", /* VK_LWIN 0x5B */
4946 "rwindow", /* VK_RWIN 0x5C */
4947 "apps", /* VK_APPS 0x5D */
4948 0, /* 0x5E */
4949 "sleep",
4950 "kp-0", /* VK_NUMPAD0 0x60 */
4951 "kp-1", /* VK_NUMPAD1 0x61 */
4952 "kp-2", /* VK_NUMPAD2 0x62 */
4953 "kp-3", /* VK_NUMPAD3 0x63 */
4954 "kp-4", /* VK_NUMPAD4 0x64 */
4955 "kp-5", /* VK_NUMPAD5 0x65 */
4956 "kp-6", /* VK_NUMPAD6 0x66 */
4957 "kp-7", /* VK_NUMPAD7 0x67 */
4958 "kp-8", /* VK_NUMPAD8 0x68 */
4959 "kp-9", /* VK_NUMPAD9 0x69 */
4960 "kp-multiply", /* VK_MULTIPLY 0x6A */
4961 "kp-add", /* VK_ADD 0x6B */
4962 "kp-separator", /* VK_SEPARATOR 0x6C */
4963 "kp-subtract", /* VK_SUBTRACT 0x6D */
4964 "kp-decimal", /* VK_DECIMAL 0x6E */
4965 "kp-divide", /* VK_DIVIDE 0x6F */
4966 "f1", /* VK_F1 0x70 */
4967 "f2", /* VK_F2 0x71 */
4968 "f3", /* VK_F3 0x72 */
4969 "f4", /* VK_F4 0x73 */
4970 "f5", /* VK_F5 0x74 */
4971 "f6", /* VK_F6 0x75 */
4972 "f7", /* VK_F7 0x76 */
4973 "f8", /* VK_F8 0x77 */
4974 "f9", /* VK_F9 0x78 */
4975 "f10", /* VK_F10 0x79 */
4976 "f11", /* VK_F11 0x7A */
4977 "f12", /* VK_F12 0x7B */
4978 "f13", /* VK_F13 0x7C */
4979 "f14", /* VK_F14 0x7D */
4980 "f15", /* VK_F15 0x7E */
4981 "f16", /* VK_F16 0x7F */
4982 "f17", /* VK_F17 0x80 */
4983 "f18", /* VK_F18 0x81 */
4984 "f19", /* VK_F19 0x82 */
4985 "f20", /* VK_F20 0x83 */
4986 "f21", /* VK_F21 0x84 */
4987 "f22", /* VK_F22 0x85 */
4988 "f23", /* VK_F23 0x86 */
4989 "f24", /* VK_F24 0x87 */
4991 0, 0, 0, 0, /* 0x88 .. 0x8B */
4992 0, 0, 0, 0, /* 0x8C .. 0x8F */
4994 "kp-numlock", /* VK_NUMLOCK 0x90 */
4995 "scroll", /* VK_SCROLL 0x91 */
4996 /* Not sure where the following block comes from.
4997 Windows headers have NEC and Fujitsu specific keys in
4998 this block, but nothing generic. */
4999 "kp-space", /* VK_NUMPAD_CLEAR 0x92 */
5000 "kp-enter", /* VK_NUMPAD_ENTER 0x93 */
5001 "kp-prior", /* VK_NUMPAD_PRIOR 0x94 */
5002 "kp-next", /* VK_NUMPAD_NEXT 0x95 */
5003 "kp-end", /* VK_NUMPAD_END 0x96 */
5004 "kp-home", /* VK_NUMPAD_HOME 0x97 */
5005 "kp-left", /* VK_NUMPAD_LEFT 0x98 */
5006 "kp-up", /* VK_NUMPAD_UP 0x99 */
5007 "kp-right", /* VK_NUMPAD_RIGHT 0x9A */
5008 "kp-down", /* VK_NUMPAD_DOWN 0x9B */
5009 "kp-insert", /* VK_NUMPAD_INSERT 0x9C */
5010 "kp-delete", /* VK_NUMPAD_DELETE 0x9D */
5012 0, 0, /* 0x9E .. 0x9F */
5015 * VK_L* & VK_R* - left and right Alt, Ctrl and Shift virtual keys.
5016 * Used only as parameters to GetAsyncKeyState and GetKeyState.
5017 * No other API or message will distinguish left and right keys this way.
5018 * 0xA0 .. 0xA5
5020 0, 0, 0, 0, 0, 0,
5022 /* Multimedia keys. These are handled as WM_APPCOMMAND, which allows us
5023 to enable them selectively, and gives access to a few more functions.
5024 See lispy_multimedia_keys below. */
5025 0, 0, 0, 0, 0, 0, 0, /* 0xA6 .. 0xAC Browser */
5026 0, 0, 0, /* 0xAD .. 0xAF Volume */
5027 0, 0, 0, 0, /* 0xB0 .. 0xB3 Media */
5028 0, 0, 0, 0, /* 0xB4 .. 0xB7 Apps */
5030 /* 0xB8 .. 0xC0 "OEM" keys - all seem to be punctuation. */
5031 0, 0, 0, 0, 0, 0, 0, 0, 0,
5033 /* 0xC1 - 0xDA unallocated, 0xDB-0xDF more OEM keys */
5034 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
5035 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
5037 0, /* 0xE0 */
5038 "ax", /* VK_OEM_AX 0xE1 */
5039 0, /* VK_OEM_102 0xE2 */
5040 "ico-help", /* VK_ICO_HELP 0xE3 */
5041 "ico-00", /* VK_ICO_00 0xE4 */
5042 0, /* VK_PROCESSKEY 0xE5 - used by IME */
5043 "ico-clear", /* VK_ICO_CLEAR 0xE6 */
5044 0, /* VK_PACKET 0xE7 - used to pass Unicode chars */
5045 0, /* 0xE8 */
5046 "reset", /* VK_OEM_RESET 0xE9 */
5047 "jump", /* VK_OEM_JUMP 0xEA */
5048 "oem-pa1", /* VK_OEM_PA1 0xEB */
5049 "oem-pa2", /* VK_OEM_PA2 0xEC */
5050 "oem-pa3", /* VK_OEM_PA3 0xED */
5051 "wsctrl", /* VK_OEM_WSCTRL 0xEE */
5052 "cusel", /* VK_OEM_CUSEL 0xEF */
5053 "oem-attn", /* VK_OEM_ATTN 0xF0 */
5054 "finish", /* VK_OEM_FINISH 0xF1 */
5055 "copy", /* VK_OEM_COPY 0xF2 */
5056 "auto", /* VK_OEM_AUTO 0xF3 */
5057 "enlw", /* VK_OEM_ENLW 0xF4 */
5058 "backtab", /* VK_OEM_BACKTAB 0xF5 */
5059 "attn", /* VK_ATTN 0xF6 */
5060 "crsel", /* VK_CRSEL 0xF7 */
5061 "exsel", /* VK_EXSEL 0xF8 */
5062 "ereof", /* VK_EREOF 0xF9 */
5063 "play", /* VK_PLAY 0xFA */
5064 "zoom", /* VK_ZOOM 0xFB */
5065 "noname", /* VK_NONAME 0xFC */
5066 "pa1", /* VK_PA1 0xFD */
5067 "oem_clear", /* VK_OEM_CLEAR 0xFE */
5068 0 /* 0xFF */
5071 /* Some of these duplicate the "Media keys" on newer keyboards,
5072 but they are delivered to the application in a different way. */
5073 static const char *const lispy_multimedia_keys[] =
5076 "browser-back",
5077 "browser-forward",
5078 "browser-refresh",
5079 "browser-stop",
5080 "browser-search",
5081 "browser-favorites",
5082 "browser-home",
5083 "volume-mute",
5084 "volume-down",
5085 "volume-up",
5086 "media-next",
5087 "media-previous",
5088 "media-stop",
5089 "media-play-pause",
5090 "mail",
5091 "media-select",
5092 "app-1",
5093 "app-2",
5094 "bass-down",
5095 "bass-boost",
5096 "bass-up",
5097 "treble-down",
5098 "treble-up",
5099 "mic-volume-mute",
5100 "mic-volume-down",
5101 "mic-volume-up",
5102 "help",
5103 "find",
5104 "new",
5105 "open",
5106 "close",
5107 "save",
5108 "print",
5109 "undo",
5110 "redo",
5111 "copy",
5112 "cut",
5113 "paste",
5114 "mail-reply",
5115 "mail-forward",
5116 "mail-send",
5117 "spell-check",
5118 "toggle-dictate-command",
5119 "mic-toggle",
5120 "correction-list",
5121 "media-play",
5122 "media-pause",
5123 "media-record",
5124 "media-fast-forward",
5125 "media-rewind",
5126 "media-channel-up",
5127 "media-channel-down"
5130 #else /* not HAVE_NTGUI */
5132 /* This should be dealt with in XTread_socket now, and that doesn't
5133 depend on the client system having the Kana syms defined. See also
5134 the XK_kana_A case below. */
5135 #if 0
5136 #ifdef XK_kana_A
5137 static const char *const lispy_kana_keys[] =
5139 /* X Keysym value */
5140 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, /* 0x400 .. 0x40f */
5141 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, /* 0x410 .. 0x41f */
5142 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, /* 0x420 .. 0x42f */
5143 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, /* 0x430 .. 0x43f */
5144 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, /* 0x440 .. 0x44f */
5145 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, /* 0x450 .. 0x45f */
5146 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, /* 0x460 .. 0x46f */
5147 0,0,0,0,0,0,0,0,0,0,0,0,0,0,"overline",0,
5148 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, /* 0x480 .. 0x48f */
5149 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, /* 0x490 .. 0x49f */
5150 0, "kana-fullstop", "kana-openingbracket", "kana-closingbracket",
5151 "kana-comma", "kana-conjunctive", "kana-WO", "kana-a",
5152 "kana-i", "kana-u", "kana-e", "kana-o",
5153 "kana-ya", "kana-yu", "kana-yo", "kana-tsu",
5154 "prolongedsound", "kana-A", "kana-I", "kana-U",
5155 "kana-E", "kana-O", "kana-KA", "kana-KI",
5156 "kana-KU", "kana-KE", "kana-KO", "kana-SA",
5157 "kana-SHI", "kana-SU", "kana-SE", "kana-SO",
5158 "kana-TA", "kana-CHI", "kana-TSU", "kana-TE",
5159 "kana-TO", "kana-NA", "kana-NI", "kana-NU",
5160 "kana-NE", "kana-NO", "kana-HA", "kana-HI",
5161 "kana-FU", "kana-HE", "kana-HO", "kana-MA",
5162 "kana-MI", "kana-MU", "kana-ME", "kana-MO",
5163 "kana-YA", "kana-YU", "kana-YO", "kana-RA",
5164 "kana-RI", "kana-RU", "kana-RE", "kana-RO",
5165 "kana-WA", "kana-N", "voicedsound", "semivoicedsound",
5166 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, /* 0x4e0 .. 0x4ef */
5167 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, /* 0x4f0 .. 0x4ff */
5169 #endif /* XK_kana_A */
5170 #endif /* 0 */
5172 #define FUNCTION_KEY_OFFSET 0xff00
5174 /* You'll notice that this table is arranged to be conveniently
5175 indexed by X Windows keysym values. */
5176 static const char *const lispy_function_keys[] =
5178 /* X Keysym value */
5180 0, 0, 0, 0, 0, 0, 0, 0, /* 0xff00...0f */
5181 "backspace", "tab", "linefeed", "clear",
5182 0, "return", 0, 0,
5183 0, 0, 0, "pause", /* 0xff10...1f */
5184 0, 0, 0, 0, 0, 0, 0, "escape",
5185 0, 0, 0, 0,
5186 0, "kanji", "muhenkan", "henkan", /* 0xff20...2f */
5187 "romaji", "hiragana", "katakana", "hiragana-katakana",
5188 "zenkaku", "hankaku", "zenkaku-hankaku", "touroku",
5189 "massyo", "kana-lock", "kana-shift", "eisu-shift",
5190 "eisu-toggle", /* 0xff30...3f */
5191 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
5192 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* 0xff40...4f */
5194 "home", "left", "up", "right", /* 0xff50 */ /* IsCursorKey */
5195 "down", "prior", "next", "end",
5196 "begin", 0, 0, 0, 0, 0, 0, 0,
5197 "select", /* 0xff60 */ /* IsMiscFunctionKey */
5198 "print",
5199 "execute",
5200 "insert",
5201 0, /* 0xff64 */
5202 "undo",
5203 "redo",
5204 "menu",
5205 "find",
5206 "cancel",
5207 "help",
5208 "break", /* 0xff6b */
5210 0, 0, 0, 0,
5211 0, 0, 0, 0, "backtab", 0, 0, 0, /* 0xff70... */
5212 0, 0, 0, 0, 0, 0, 0, "kp-numlock", /* 0xff78... */
5213 "kp-space", /* 0xff80 */ /* IsKeypadKey */
5214 0, 0, 0, 0, 0, 0, 0, 0,
5215 "kp-tab", /* 0xff89 */
5216 0, 0, 0,
5217 "kp-enter", /* 0xff8d */
5218 0, 0, 0,
5219 "kp-f1", /* 0xff91 */
5220 "kp-f2",
5221 "kp-f3",
5222 "kp-f4",
5223 "kp-home", /* 0xff95 */
5224 "kp-left",
5225 "kp-up",
5226 "kp-right",
5227 "kp-down",
5228 "kp-prior", /* kp-page-up */
5229 "kp-next", /* kp-page-down */
5230 "kp-end",
5231 "kp-begin",
5232 "kp-insert",
5233 "kp-delete",
5234 0, /* 0xffa0 */
5235 0, 0, 0, 0, 0, 0, 0, 0, 0,
5236 "kp-multiply", /* 0xffaa */
5237 "kp-add",
5238 "kp-separator",
5239 "kp-subtract",
5240 "kp-decimal",
5241 "kp-divide", /* 0xffaf */
5242 "kp-0", /* 0xffb0 */
5243 "kp-1", "kp-2", "kp-3", "kp-4", "kp-5", "kp-6", "kp-7", "kp-8", "kp-9",
5244 0, /* 0xffba */
5245 0, 0,
5246 "kp-equal", /* 0xffbd */
5247 "f1", /* 0xffbe */ /* IsFunctionKey */
5248 "f2",
5249 "f3", "f4", "f5", "f6", "f7", "f8", "f9", "f10", /* 0xffc0 */
5250 "f11", "f12", "f13", "f14", "f15", "f16", "f17", "f18",
5251 "f19", "f20", "f21", "f22", "f23", "f24", "f25", "f26", /* 0xffd0 */
5252 "f27", "f28", "f29", "f30", "f31", "f32", "f33", "f34",
5253 "f35", 0, 0, 0, 0, 0, 0, 0, /* 0xffe0 */
5254 0, 0, 0, 0, 0, 0, 0, 0,
5255 0, 0, 0, 0, 0, 0, 0, 0, /* 0xfff0 */
5256 0, 0, 0, 0, 0, 0, 0, "delete"
5259 /* ISO 9995 Function and Modifier Keys; the first byte is 0xFE. */
5260 #define ISO_FUNCTION_KEY_OFFSET 0xfe00
5262 static const char *const iso_lispy_function_keys[] =
5264 0, 0, 0, 0, 0, 0, 0, 0, /* 0xfe00 */
5265 0, 0, 0, 0, 0, 0, 0, 0, /* 0xfe08 */
5266 0, 0, 0, 0, 0, 0, 0, 0, /* 0xfe10 */
5267 0, 0, 0, 0, 0, 0, 0, 0, /* 0xfe18 */
5268 "iso-lefttab", /* 0xfe20 */
5269 "iso-move-line-up", "iso-move-line-down",
5270 "iso-partial-line-up", "iso-partial-line-down",
5271 "iso-partial-space-left", "iso-partial-space-right",
5272 "iso-set-margin-left", "iso-set-margin-right", /* 0xffe27, 28 */
5273 "iso-release-margin-left", "iso-release-margin-right",
5274 "iso-release-both-margins",
5275 "iso-fast-cursor-left", "iso-fast-cursor-right",
5276 "iso-fast-cursor-up", "iso-fast-cursor-down",
5277 "iso-continuous-underline", "iso-discontinuous-underline", /* 0xfe30, 31 */
5278 "iso-emphasize", "iso-center-object", "iso-enter", /* ... 0xfe34 */
5281 #endif /* not HAVE_NTGUI */
5283 static Lisp_Object Vlispy_mouse_stem;
5285 static const char *const lispy_wheel_names[] =
5287 "wheel-up", "wheel-down", "wheel-left", "wheel-right"
5290 /* drag-n-drop events are generated when a set of selected files are
5291 dragged from another application and dropped onto an Emacs window. */
5292 static const char *const lispy_drag_n_drop_names[] =
5294 "drag-n-drop"
5297 /* Scroll bar parts. */
5298 static Lisp_Object Qabove_handle, Qhandle, Qbelow_handle;
5299 static Lisp_Object Qbefore_handle, Qhorizontal_handle, Qafter_handle;
5300 Lisp_Object Qup, Qdown, Qtop, Qbottom;
5301 static Lisp_Object Qleftmost, Qrightmost;
5302 static Lisp_Object Qend_scroll;
5303 static Lisp_Object Qratio;
5305 /* An array of scroll bar parts, indexed by an enum scroll_bar_part value.
5306 Note that Qnil corresponds to scroll_bar_nowhere and should not appear
5307 in Lisp events. */
5308 static Lisp_Object *const scroll_bar_parts[] = {
5309 &Qnil, &Qabove_handle, &Qhandle, &Qbelow_handle,
5310 &Qup, &Qdown, &Qtop, &Qbottom, &Qend_scroll, &Qratio,
5311 &Qbefore_handle, &Qhorizontal_handle, &Qafter_handle,
5312 &Qleft, &Qright, &Qleftmost, &Qrightmost, &Qend_scroll, &Qratio
5315 /* A vector, indexed by button number, giving the down-going location
5316 of currently depressed buttons, both scroll bar and non-scroll bar.
5318 The elements have the form
5319 (BUTTON-NUMBER MODIFIER-MASK . REST)
5320 where REST is the cdr of a position as it would be reported in the event.
5322 The make_lispy_event function stores positions here to tell the
5323 difference between click and drag events, and to store the starting
5324 location to be included in drag events. */
5326 static Lisp_Object button_down_location;
5328 /* Information about the most recent up-going button event: Which
5329 button, what location, and what time. */
5331 static int last_mouse_button;
5332 static int last_mouse_x;
5333 static int last_mouse_y;
5334 static Time button_down_time;
5336 /* The number of clicks in this multiple-click. */
5338 static int double_click_count;
5340 /* X and Y are frame-relative coordinates for a click or wheel event.
5341 Return a Lisp-style event list. */
5343 static Lisp_Object
5344 make_lispy_position (struct frame *f, Lisp_Object x, Lisp_Object y,
5345 Time t)
5347 enum window_part part;
5348 Lisp_Object posn = Qnil;
5349 Lisp_Object extra_info = Qnil;
5350 /* Coordinate pixel positions to return. */
5351 int xret = 0, yret = 0;
5352 /* The window under frame pixel coordinates (x,y) */
5353 Lisp_Object window = f
5354 ? window_from_coordinates (f, XINT (x), XINT (y), &part, 0)
5355 : Qnil;
5357 if (WINDOWP (window))
5359 /* It's a click in window WINDOW at frame coordinates (X,Y) */
5360 struct window *w = XWINDOW (window);
5361 Lisp_Object string_info = Qnil;
5362 ptrdiff_t textpos = 0;
5363 int col = -1, row = -1;
5364 int dx = -1, dy = -1;
5365 int width = -1, height = -1;
5366 Lisp_Object object = Qnil;
5368 /* Pixel coordinates relative to the window corner. */
5369 int wx = XINT (x) - WINDOW_LEFT_EDGE_X (w);
5370 int wy = XINT (y) - WINDOW_TOP_EDGE_Y (w);
5372 /* For text area clicks, return X, Y relative to the corner of
5373 this text area. Note that dX, dY etc are set below, by
5374 buffer_posn_from_coords. */
5375 if (part == ON_TEXT)
5377 xret = XINT (x) - window_box_left (w, TEXT_AREA);
5378 yret = wy - WINDOW_HEADER_LINE_HEIGHT (w);
5380 /* For mode line and header line clicks, return X, Y relative to
5381 the left window edge. Use mode_line_string to look for a
5382 string on the click position. */
5383 else if (part == ON_MODE_LINE || part == ON_HEADER_LINE)
5385 Lisp_Object string;
5386 ptrdiff_t charpos;
5388 posn = (part == ON_MODE_LINE) ? Qmode_line : Qheader_line;
5389 /* Note that mode_line_string takes COL, ROW as pixels and
5390 converts them to characters. */
5391 col = wx;
5392 row = wy;
5393 string = mode_line_string (w, part, &col, &row, &charpos,
5394 &object, &dx, &dy, &width, &height);
5395 if (STRINGP (string))
5396 string_info = Fcons (string, make_number (charpos));
5397 textpos = -1;
5399 xret = wx;
5400 yret = wy;
5402 /* For fringes and margins, Y is relative to the area's (and the
5403 window's) top edge, while X is meaningless. */
5404 else if (part == ON_LEFT_MARGIN || part == ON_RIGHT_MARGIN)
5406 Lisp_Object string;
5407 ptrdiff_t charpos;
5409 posn = (part == ON_LEFT_MARGIN) ? Qleft_margin : Qright_margin;
5410 col = wx;
5411 row = wy;
5412 string = marginal_area_string (w, part, &col, &row, &charpos,
5413 &object, &dx, &dy, &width, &height);
5414 if (STRINGP (string))
5415 string_info = Fcons (string, make_number (charpos));
5416 xret = wx;
5417 yret = wy - WINDOW_HEADER_LINE_HEIGHT (w);
5419 else if (part == ON_LEFT_FRINGE)
5421 posn = Qleft_fringe;
5422 col = 0;
5423 xret = wx;
5424 dx = wx
5425 - (WINDOW_HAS_FRINGES_OUTSIDE_MARGINS (w)
5426 ? 0 : window_box_width (w, LEFT_MARGIN_AREA));
5427 dy = yret = wy - WINDOW_HEADER_LINE_HEIGHT (w);
5429 else if (part == ON_RIGHT_FRINGE)
5431 posn = Qright_fringe;
5432 col = 0;
5433 xret = wx;
5434 dx = wx
5435 - window_box_width (w, LEFT_MARGIN_AREA)
5436 - window_box_width (w, TEXT_AREA)
5437 - (WINDOW_HAS_FRINGES_OUTSIDE_MARGINS (w)
5438 ? window_box_width (w, RIGHT_MARGIN_AREA)
5439 : 0);
5440 dy = yret = wy - WINDOW_HEADER_LINE_HEIGHT (w);
5442 else if (part == ON_VERTICAL_BORDER)
5444 posn = Qvertical_line;
5445 width = 1;
5446 dx = 0;
5447 xret = wx;
5448 dy = yret = wy;
5450 else if (part == ON_VERTICAL_SCROLL_BAR)
5452 posn = Qvertical_scroll_bar;
5453 width = WINDOW_SCROLL_BAR_AREA_WIDTH (w);
5454 dx = xret = wx;
5455 dy = yret = wy;
5457 else if (part == ON_HORIZONTAL_SCROLL_BAR)
5459 posn = Qhorizontal_scroll_bar;
5460 width = WINDOW_SCROLL_BAR_AREA_HEIGHT (w);
5461 dx = xret = wx;
5462 dy = yret = wy;
5464 else if (part == ON_RIGHT_DIVIDER)
5466 posn = Qright_divider;
5467 width = WINDOW_RIGHT_DIVIDER_WIDTH (w);
5468 dx = xret = wx;
5469 dy = yret = wy;
5471 else if (part == ON_BOTTOM_DIVIDER)
5473 posn = Qbottom_divider;
5474 width = WINDOW_BOTTOM_DIVIDER_WIDTH (w);
5475 dx = xret = wx;
5476 dy = yret = wy;
5479 /* For clicks in the text area, fringes, or margins, call
5480 buffer_posn_from_coords to extract TEXTPOS, the buffer
5481 position nearest to the click. */
5482 if (!textpos)
5484 Lisp_Object string2, object2 = Qnil;
5485 struct display_pos p;
5486 int dx2, dy2;
5487 int width2, height2;
5488 /* The pixel X coordinate passed to buffer_posn_from_coords
5489 is the X coordinate relative to the text area for
5490 text-area and right-margin clicks, zero otherwise. */
5491 int x2
5492 = (part == ON_TEXT) ? xret
5493 : (part == ON_RIGHT_FRINGE || part == ON_RIGHT_MARGIN)
5494 ? (XINT (x) - window_box_left (w, TEXT_AREA))
5495 : 0;
5496 int y2 = wy;
5498 string2 = buffer_posn_from_coords (w, &x2, &y2, &p,
5499 &object2, &dx2, &dy2,
5500 &width2, &height2);
5501 textpos = CHARPOS (p.pos);
5502 if (col < 0) col = x2;
5503 if (row < 0) row = y2;
5504 if (dx < 0) dx = dx2;
5505 if (dy < 0) dy = dy2;
5506 if (width < 0) width = width2;
5507 if (height < 0) height = height2;
5509 if (NILP (posn))
5511 posn = make_number (textpos);
5512 if (STRINGP (string2))
5513 string_info = Fcons (string2,
5514 make_number (CHARPOS (p.string_pos)));
5516 if (NILP (object))
5517 object = object2;
5520 #ifdef HAVE_WINDOW_SYSTEM
5521 if (IMAGEP (object))
5523 Lisp_Object image_map, hotspot;
5524 if ((image_map = Fplist_get (XCDR (object), QCmap),
5525 !NILP (image_map))
5526 && (hotspot = find_hot_spot (image_map, dx, dy),
5527 CONSP (hotspot))
5528 && (hotspot = XCDR (hotspot), CONSP (hotspot)))
5529 posn = XCAR (hotspot);
5531 #endif
5533 /* Object info. */
5534 extra_info
5535 = list3 (object,
5536 Fcons (make_number (dx), make_number (dy)),
5537 Fcons (make_number (width), make_number (height)));
5539 /* String info. */
5540 extra_info = Fcons (string_info,
5541 Fcons (textpos < 0 ? Qnil : make_number (textpos),
5542 Fcons (Fcons (make_number (col),
5543 make_number (row)),
5544 extra_info)));
5546 else if (f != 0)
5548 /* Return mouse pixel coordinates here. */
5549 XSETFRAME (window, f);
5550 xret = XINT (x);
5551 yret = XINT (y);
5553 else
5554 window = Qnil;
5556 return Fcons (window,
5557 Fcons (posn,
5558 Fcons (Fcons (make_number (xret),
5559 make_number (yret)),
5560 Fcons (make_number (t),
5561 extra_info))));
5564 /* Return non-zero if F is a GUI frame that uses some toolkit-managed
5565 menu bar. This really means that Emacs draws and manages the menu
5566 bar as part of its normal display, and therefore can compute its
5567 geometry. */
5568 static bool
5569 toolkit_menubar_in_use (struct frame *f)
5571 #if defined (USE_X_TOOLKIT) || defined (USE_GTK) || defined (HAVE_NS) || defined (HAVE_NTGUI)
5572 return !(!FRAME_WINDOW_P (f));
5573 #else
5574 return false;
5575 #endif
5578 /* Build the part of Lisp event which represents scroll bar state from
5579 EV. TYPE is one of Qvertical_scroll_bar or Qhorizontal_scroll_bar. */
5581 static Lisp_Object
5582 make_scroll_bar_position (struct input_event *ev, Lisp_Object type)
5584 return list5 (ev->frame_or_window, type, Fcons (ev->x, ev->y),
5585 make_number (ev->timestamp), *scroll_bar_parts[ev->part]);
5588 /* Given a struct input_event, build the lisp event which represents
5589 it. If EVENT is 0, build a mouse movement event from the mouse
5590 movement buffer, which should have a movement event in it.
5592 Note that events must be passed to this function in the order they
5593 are received; this function stores the location of button presses
5594 in order to build drag events when the button is released. */
5596 static Lisp_Object
5597 make_lispy_event (struct input_event *event)
5599 int i;
5601 switch (event->kind)
5603 /* A simple keystroke. */
5604 case ASCII_KEYSTROKE_EVENT:
5605 case MULTIBYTE_CHAR_KEYSTROKE_EVENT:
5607 Lisp_Object lispy_c;
5608 EMACS_INT c = event->code;
5609 if (event->kind == ASCII_KEYSTROKE_EVENT)
5611 c &= 0377;
5612 eassert (c == event->code);
5613 /* Turn ASCII characters into control characters
5614 when proper. */
5615 if (event->modifiers & ctrl_modifier)
5617 c = make_ctrl_char (c);
5618 event->modifiers &= ~ctrl_modifier;
5622 /* Add in the other modifier bits. The shift key was taken care
5623 of by the X code. */
5624 c |= (event->modifiers
5625 & (meta_modifier | alt_modifier
5626 | hyper_modifier | super_modifier | ctrl_modifier));
5627 /* Distinguish Shift-SPC from SPC. */
5628 if ((event->code) == 040
5629 && event->modifiers & shift_modifier)
5630 c |= shift_modifier;
5631 button_down_time = 0;
5632 XSETFASTINT (lispy_c, c);
5633 return lispy_c;
5636 #ifdef HAVE_NS
5637 /* NS_NONKEY_EVENTs are just like NON_ASCII_KEYSTROKE_EVENTs,
5638 except that they are non-key events (last-nonmenu-event is nil). */
5639 case NS_NONKEY_EVENT:
5640 #endif
5642 /* A function key. The symbol may need to have modifier prefixes
5643 tacked onto it. */
5644 case NON_ASCII_KEYSTROKE_EVENT:
5645 button_down_time = 0;
5647 for (i = 0; i < ARRAYELTS (lispy_accent_codes); i++)
5648 if (event->code == lispy_accent_codes[i])
5649 return modify_event_symbol (i,
5650 event->modifiers,
5651 Qfunction_key, Qnil,
5652 lispy_accent_keys, &accent_key_syms,
5653 ARRAYELTS (lispy_accent_keys));
5655 #if 0
5656 #ifdef XK_kana_A
5657 if (event->code >= 0x400 && event->code < 0x500)
5658 return modify_event_symbol (event->code - 0x400,
5659 event->modifiers & ~shift_modifier,
5660 Qfunction_key, Qnil,
5661 lispy_kana_keys, &func_key_syms,
5662 ARRAYELTS (lispy_kana_keys));
5663 #endif /* XK_kana_A */
5664 #endif /* 0 */
5666 #ifdef ISO_FUNCTION_KEY_OFFSET
5667 if (event->code < FUNCTION_KEY_OFFSET
5668 && event->code >= ISO_FUNCTION_KEY_OFFSET)
5669 return modify_event_symbol (event->code - ISO_FUNCTION_KEY_OFFSET,
5670 event->modifiers,
5671 Qfunction_key, Qnil,
5672 iso_lispy_function_keys, &func_key_syms,
5673 ARRAYELTS (iso_lispy_function_keys));
5674 #endif
5676 if ((FUNCTION_KEY_OFFSET <= event->code
5677 && (event->code
5678 < FUNCTION_KEY_OFFSET + ARRAYELTS (lispy_function_keys)))
5679 && lispy_function_keys[event->code - FUNCTION_KEY_OFFSET])
5680 return modify_event_symbol (event->code - FUNCTION_KEY_OFFSET,
5681 event->modifiers,
5682 Qfunction_key, Qnil,
5683 lispy_function_keys, &func_key_syms,
5684 ARRAYELTS (lispy_function_keys));
5686 /* Handle system-specific or unknown keysyms.
5687 We need to use an alist rather than a vector as the cache
5688 since we can't make a vector long enough. */
5689 if (NILP (KVAR (current_kboard, system_key_syms)))
5690 kset_system_key_syms (current_kboard, Fcons (Qnil, Qnil));
5691 return modify_event_symbol (event->code,
5692 event->modifiers,
5693 Qfunction_key,
5694 KVAR (current_kboard, Vsystem_key_alist),
5695 0, &KVAR (current_kboard, system_key_syms),
5696 PTRDIFF_MAX);
5698 #ifdef HAVE_NTGUI
5699 case MULTIMEDIA_KEY_EVENT:
5700 if (event->code < ARRAYELTS (lispy_multimedia_keys)
5701 && event->code > 0 && lispy_multimedia_keys[event->code])
5703 return modify_event_symbol (event->code, event->modifiers,
5704 Qfunction_key, Qnil,
5705 lispy_multimedia_keys, &func_key_syms,
5706 ARRAYELTS (lispy_multimedia_keys));
5708 return Qnil;
5709 #endif
5711 /* A mouse click. Figure out where it is, decide whether it's
5712 a press, click or drag, and build the appropriate structure. */
5713 case MOUSE_CLICK_EVENT:
5714 #ifdef HAVE_GPM
5715 case GPM_CLICK_EVENT:
5716 #endif
5717 #ifndef USE_TOOLKIT_SCROLL_BARS
5718 case SCROLL_BAR_CLICK_EVENT:
5719 case HORIZONTAL_SCROLL_BAR_CLICK_EVENT:
5720 #endif
5722 int button = event->code;
5723 bool is_double;
5724 Lisp_Object position;
5725 Lisp_Object *start_pos_ptr;
5726 Lisp_Object start_pos;
5728 position = Qnil;
5730 /* Build the position as appropriate for this mouse click. */
5731 if (event->kind == MOUSE_CLICK_EVENT
5732 #ifdef HAVE_GPM
5733 || event->kind == GPM_CLICK_EVENT
5734 #endif
5737 struct frame *f = XFRAME (event->frame_or_window);
5738 int row, column;
5740 /* Ignore mouse events that were made on frame that
5741 have been deleted. */
5742 if (! FRAME_LIVE_P (f))
5743 return Qnil;
5745 /* EVENT->x and EVENT->y are frame-relative pixel
5746 coordinates at this place. Under old redisplay, COLUMN
5747 and ROW are set to frame relative glyph coordinates
5748 which are then used to determine whether this click is
5749 in a menu (non-toolkit version). */
5750 if (!toolkit_menubar_in_use (f))
5752 pixel_to_glyph_coords (f, XINT (event->x), XINT (event->y),
5753 &column, &row, NULL, 1);
5755 /* In the non-toolkit version, clicks on the menu bar
5756 are ordinary button events in the event buffer.
5757 Distinguish them, and invoke the menu.
5759 (In the toolkit version, the toolkit handles the
5760 menu bar and Emacs doesn't know about it until
5761 after the user makes a selection.) */
5762 if (row >= 0 && row < FRAME_MENU_BAR_LINES (f)
5763 && (event->modifiers & down_modifier))
5765 Lisp_Object items, item;
5767 /* Find the menu bar item under `column'. */
5768 item = Qnil;
5769 items = FRAME_MENU_BAR_ITEMS (f);
5770 for (i = 0; i < ASIZE (items); i += 4)
5772 Lisp_Object pos, string;
5773 string = AREF (items, i + 1);
5774 pos = AREF (items, i + 3);
5775 if (NILP (string))
5776 break;
5777 if (column >= XINT (pos)
5778 && column < XINT (pos) + SCHARS (string))
5780 item = AREF (items, i);
5781 break;
5785 /* ELisp manual 2.4b says (x y) are window
5786 relative but code says they are
5787 frame-relative. */
5788 position = list4 (event->frame_or_window,
5789 Qmenu_bar,
5790 Fcons (event->x, event->y),
5791 make_number (event->timestamp));
5793 return list2 (item, position);
5797 position = make_lispy_position (f, event->x, event->y,
5798 event->timestamp);
5800 #ifndef USE_TOOLKIT_SCROLL_BARS
5801 else
5802 /* It's a scrollbar click. */
5803 position = make_scroll_bar_position (event, Qvertical_scroll_bar);
5804 #endif /* not USE_TOOLKIT_SCROLL_BARS */
5806 if (button >= ASIZE (button_down_location))
5808 ptrdiff_t incr = button - ASIZE (button_down_location) + 1;
5809 button_down_location = larger_vector (button_down_location,
5810 incr, -1);
5811 mouse_syms = larger_vector (mouse_syms, incr, -1);
5814 start_pos_ptr = aref_addr (button_down_location, button);
5815 start_pos = *start_pos_ptr;
5816 *start_pos_ptr = Qnil;
5819 /* On window-system frames, use the value of
5820 double-click-fuzz as is. On other frames, interpret it
5821 as a multiple of 1/8 characters. */
5822 struct frame *f;
5823 int fuzz;
5825 if (WINDOWP (event->frame_or_window))
5826 f = XFRAME (XWINDOW (event->frame_or_window)->frame);
5827 else if (FRAMEP (event->frame_or_window))
5828 f = XFRAME (event->frame_or_window);
5829 else
5830 emacs_abort ();
5832 if (FRAME_WINDOW_P (f))
5833 fuzz = double_click_fuzz;
5834 else
5835 fuzz = double_click_fuzz / 8;
5837 is_double = (button == last_mouse_button
5838 && (eabs (XINT (event->x) - last_mouse_x) <= fuzz)
5839 && (eabs (XINT (event->y) - last_mouse_y) <= fuzz)
5840 && button_down_time != 0
5841 && (EQ (Vdouble_click_time, Qt)
5842 || (NATNUMP (Vdouble_click_time)
5843 && (event->timestamp - button_down_time
5844 < XFASTINT (Vdouble_click_time)))));
5847 last_mouse_button = button;
5848 last_mouse_x = XINT (event->x);
5849 last_mouse_y = XINT (event->y);
5851 /* If this is a button press, squirrel away the location, so
5852 we can decide later whether it was a click or a drag. */
5853 if (event->modifiers & down_modifier)
5855 if (is_double)
5857 double_click_count++;
5858 event->modifiers |= ((double_click_count > 2)
5859 ? triple_modifier
5860 : double_modifier);
5862 else
5863 double_click_count = 1;
5864 button_down_time = event->timestamp;
5865 *start_pos_ptr = Fcopy_alist (position);
5866 ignore_mouse_drag_p = 0;
5869 /* Now we're releasing a button - check the co-ordinates to
5870 see if this was a click or a drag. */
5871 else if (event->modifiers & up_modifier)
5873 /* If we did not see a down before this up, ignore the up.
5874 Probably this happened because the down event chose a
5875 menu item. It would be an annoyance to treat the
5876 release of the button that chose the menu item as a
5877 separate event. */
5879 if (!CONSP (start_pos))
5880 return Qnil;
5882 event->modifiers &= ~up_modifier;
5885 Lisp_Object new_down, down;
5886 EMACS_INT xdiff = double_click_fuzz, ydiff = double_click_fuzz;
5888 /* The third element of every position
5889 should be the (x,y) pair. */
5890 down = Fcar (Fcdr (Fcdr (start_pos)));
5891 new_down = Fcar (Fcdr (Fcdr (position)));
5893 if (CONSP (down)
5894 && INTEGERP (XCAR (down)) && INTEGERP (XCDR (down)))
5896 xdiff = XINT (XCAR (new_down)) - XINT (XCAR (down));
5897 ydiff = XINT (XCDR (new_down)) - XINT (XCDR (down));
5900 if (ignore_mouse_drag_p)
5902 event->modifiers |= click_modifier;
5903 ignore_mouse_drag_p = 0;
5905 else if (xdiff < double_click_fuzz && xdiff > - double_click_fuzz
5906 && ydiff < double_click_fuzz && ydiff > - double_click_fuzz
5907 /* Maybe the mouse has moved a lot, caused scrolling, and
5908 eventually ended up at the same screen position (but
5909 not buffer position) in which case it is a drag, not
5910 a click. */
5911 /* FIXME: OTOH if the buffer position has changed
5912 because of a timer or process filter rather than
5913 because of mouse movement, it should be considered as
5914 a click. But mouse-drag-region completely ignores
5915 this case and it hasn't caused any real problem, so
5916 it's probably OK to ignore it as well. */
5917 && EQ (Fcar (Fcdr (start_pos)), Fcar (Fcdr (position))))
5918 /* Mouse hasn't moved (much). */
5919 event->modifiers |= click_modifier;
5920 else
5922 button_down_time = 0;
5923 event->modifiers |= drag_modifier;
5926 /* Don't check is_double; treat this as multiple
5927 if the down-event was multiple. */
5928 if (double_click_count > 1)
5929 event->modifiers |= ((double_click_count > 2)
5930 ? triple_modifier
5931 : double_modifier);
5934 else
5935 /* Every mouse event should either have the down_modifier or
5936 the up_modifier set. */
5937 emacs_abort ();
5940 /* Get the symbol we should use for the mouse click. */
5941 Lisp_Object head;
5943 head = modify_event_symbol (button,
5944 event->modifiers,
5945 Qmouse_click, Vlispy_mouse_stem,
5946 NULL,
5947 &mouse_syms,
5948 ASIZE (mouse_syms));
5949 if (event->modifiers & drag_modifier)
5950 return list3 (head, start_pos, position);
5951 else if (event->modifiers & (double_modifier | triple_modifier))
5952 return list3 (head, position, make_number (double_click_count));
5953 else
5954 return list2 (head, position);
5958 case WHEEL_EVENT:
5959 case HORIZ_WHEEL_EVENT:
5961 Lisp_Object position;
5962 Lisp_Object head;
5964 /* Build the position as appropriate for this mouse click. */
5965 struct frame *f = XFRAME (event->frame_or_window);
5967 /* Ignore wheel events that were made on frame that have been
5968 deleted. */
5969 if (! FRAME_LIVE_P (f))
5970 return Qnil;
5972 position = make_lispy_position (f, event->x, event->y,
5973 event->timestamp);
5975 /* Set double or triple modifiers to indicate the wheel speed. */
5977 /* On window-system frames, use the value of
5978 double-click-fuzz as is. On other frames, interpret it
5979 as a multiple of 1/8 characters. */
5980 struct frame *fr;
5981 int fuzz;
5982 int symbol_num;
5983 bool is_double;
5985 if (WINDOWP (event->frame_or_window))
5986 fr = XFRAME (XWINDOW (event->frame_or_window)->frame);
5987 else if (FRAMEP (event->frame_or_window))
5988 fr = XFRAME (event->frame_or_window);
5989 else
5990 emacs_abort ();
5992 fuzz = FRAME_WINDOW_P (fr)
5993 ? double_click_fuzz : double_click_fuzz / 8;
5995 if (event->modifiers & up_modifier)
5997 /* Emit a wheel-up event. */
5998 event->modifiers &= ~up_modifier;
5999 symbol_num = 0;
6001 else if (event->modifiers & down_modifier)
6003 /* Emit a wheel-down event. */
6004 event->modifiers &= ~down_modifier;
6005 symbol_num = 1;
6007 else
6008 /* Every wheel event should either have the down_modifier or
6009 the up_modifier set. */
6010 emacs_abort ();
6012 if (event->kind == HORIZ_WHEEL_EVENT)
6013 symbol_num += 2;
6015 is_double = (last_mouse_button == - (1 + symbol_num)
6016 && (eabs (XINT (event->x) - last_mouse_x) <= fuzz)
6017 && (eabs (XINT (event->y) - last_mouse_y) <= fuzz)
6018 && button_down_time != 0
6019 && (EQ (Vdouble_click_time, Qt)
6020 || (NATNUMP (Vdouble_click_time)
6021 && (event->timestamp - button_down_time
6022 < XFASTINT (Vdouble_click_time)))));
6023 if (is_double)
6025 double_click_count++;
6026 event->modifiers |= ((double_click_count > 2)
6027 ? triple_modifier
6028 : double_modifier);
6030 else
6032 double_click_count = 1;
6033 event->modifiers |= click_modifier;
6036 button_down_time = event->timestamp;
6037 /* Use a negative value to distinguish wheel from mouse button. */
6038 last_mouse_button = - (1 + symbol_num);
6039 last_mouse_x = XINT (event->x);
6040 last_mouse_y = XINT (event->y);
6042 /* Get the symbol we should use for the wheel event. */
6043 head = modify_event_symbol (symbol_num,
6044 event->modifiers,
6045 Qmouse_click,
6046 Qnil,
6047 lispy_wheel_names,
6048 &wheel_syms,
6049 ASIZE (wheel_syms));
6052 if (event->modifiers & (double_modifier | triple_modifier))
6053 return list3 (head, position, make_number (double_click_count));
6054 else
6055 return list2 (head, position);
6059 #ifdef USE_TOOLKIT_SCROLL_BARS
6061 /* We don't have down and up events if using toolkit scroll bars,
6062 so make this always a click event. Store in the `part' of
6063 the Lisp event a symbol which maps to the following actions:
6065 `above_handle' page up
6066 `below_handle' page down
6067 `up' line up
6068 `down' line down
6069 `top' top of buffer
6070 `bottom' bottom of buffer
6071 `handle' thumb has been dragged.
6072 `end-scroll' end of interaction with scroll bar
6074 The incoming input_event contains in its `part' member an
6075 index of type `enum scroll_bar_part' which we can use as an
6076 index in scroll_bar_parts to get the appropriate symbol. */
6078 case SCROLL_BAR_CLICK_EVENT:
6080 Lisp_Object position, head;
6082 position = make_scroll_bar_position (event, Qvertical_scroll_bar);
6084 /* Always treat scroll bar events as clicks. */
6085 event->modifiers |= click_modifier;
6086 event->modifiers &= ~up_modifier;
6088 if (event->code >= ASIZE (mouse_syms))
6089 mouse_syms = larger_vector (mouse_syms,
6090 event->code - ASIZE (mouse_syms) + 1,
6091 -1);
6093 /* Get the symbol we should use for the mouse click. */
6094 head = modify_event_symbol (event->code,
6095 event->modifiers,
6096 Qmouse_click,
6097 Vlispy_mouse_stem,
6098 NULL, &mouse_syms,
6099 ASIZE (mouse_syms));
6100 return list2 (head, position);
6103 case HORIZONTAL_SCROLL_BAR_CLICK_EVENT:
6105 Lisp_Object position, head;
6107 position = make_scroll_bar_position (event, Qhorizontal_scroll_bar);
6109 /* Always treat scroll bar events as clicks. */
6110 event->modifiers |= click_modifier;
6111 event->modifiers &= ~up_modifier;
6113 if (event->code >= ASIZE (mouse_syms))
6114 mouse_syms = larger_vector (mouse_syms,
6115 event->code - ASIZE (mouse_syms) + 1,
6116 -1);
6118 /* Get the symbol we should use for the mouse click. */
6119 head = modify_event_symbol (event->code,
6120 event->modifiers,
6121 Qmouse_click,
6122 Vlispy_mouse_stem,
6123 NULL, &mouse_syms,
6124 ASIZE (mouse_syms));
6125 return list2 (head, position);
6128 #endif /* USE_TOOLKIT_SCROLL_BARS */
6130 case DRAG_N_DROP_EVENT:
6132 struct frame *f;
6133 Lisp_Object head, position;
6134 Lisp_Object files;
6136 f = XFRAME (event->frame_or_window);
6137 files = event->arg;
6139 /* Ignore mouse events that were made on frames that
6140 have been deleted. */
6141 if (! FRAME_LIVE_P (f))
6142 return Qnil;
6144 position = make_lispy_position (f, event->x, event->y,
6145 event->timestamp);
6147 head = modify_event_symbol (0, event->modifiers,
6148 Qdrag_n_drop, Qnil,
6149 lispy_drag_n_drop_names,
6150 &drag_n_drop_syms, 1);
6151 return list3 (head, position, files);
6154 #if defined (USE_X_TOOLKIT) || defined (HAVE_NTGUI) \
6155 || defined (HAVE_NS) || defined (USE_GTK)
6156 case MENU_BAR_EVENT:
6157 if (EQ (event->arg, event->frame_or_window))
6158 /* This is the prefix key. We translate this to
6159 `(menu_bar)' because the code in keyboard.c for menu
6160 events, which we use, relies on this. */
6161 return list1 (Qmenu_bar);
6162 return event->arg;
6163 #endif
6165 case SELECT_WINDOW_EVENT:
6166 /* Make an event (select-window (WINDOW)). */
6167 return list2 (Qselect_window, list1 (event->frame_or_window));
6169 case TOOL_BAR_EVENT:
6170 if (EQ (event->arg, event->frame_or_window))
6171 /* This is the prefix key. We translate this to
6172 `(tool_bar)' because the code in keyboard.c for tool bar
6173 events, which we use, relies on this. */
6174 return list1 (Qtool_bar);
6175 else if (SYMBOLP (event->arg))
6176 return apply_modifiers (event->modifiers, event->arg);
6177 return event->arg;
6179 case USER_SIGNAL_EVENT:
6180 /* A user signal. */
6182 char *name = find_user_signal_name (event->code);
6183 if (!name)
6184 emacs_abort ();
6185 return intern (name);
6188 case SAVE_SESSION_EVENT:
6189 return Qsave_session;
6191 #ifdef HAVE_DBUS
6192 case DBUS_EVENT:
6194 return Fcons (Qdbus_event, event->arg);
6196 #endif /* HAVE_DBUS */
6198 #ifdef HAVE_XWIDGETS
6199 case XWIDGET_EVENT:
6201 printf("cool, an xwidget event arrived in make_lispy_event!\n");
6202 return Fcons (Qxwidget_event,event->arg);
6204 #endif /* HAVE_XWIDGETS */
6207 #if defined HAVE_GFILENOTIFY || defined HAVE_INOTIFY
6208 case FILE_NOTIFY_EVENT:
6210 return Fcons (Qfile_notify, event->arg);
6212 #endif /* defined HAVE_GFILENOTIFY || defined HAVE_INOTIFY */
6214 case CONFIG_CHANGED_EVENT:
6215 return list3 (Qconfig_changed_event,
6216 event->arg, event->frame_or_window);
6218 /* The 'kind' field of the event is something we don't recognize. */
6219 default:
6220 emacs_abort ();
6224 static Lisp_Object
6225 make_lispy_movement (struct frame *frame, Lisp_Object bar_window, enum scroll_bar_part part,
6226 Lisp_Object x, Lisp_Object y, Time t)
6228 /* Is it a scroll bar movement? */
6229 if (frame && ! NILP (bar_window))
6231 Lisp_Object part_sym;
6233 part_sym = *scroll_bar_parts[(int) part];
6234 return list2 (Qscroll_bar_movement,
6235 list5 (bar_window,
6236 Qvertical_scroll_bar,
6237 Fcons (x, y),
6238 make_number (t),
6239 part_sym));
6241 /* Or is it an ordinary mouse movement? */
6242 else
6244 Lisp_Object position;
6245 position = make_lispy_position (frame, x, y, t);
6246 return list2 (Qmouse_movement, position);
6250 /* Construct a switch frame event. */
6251 static Lisp_Object
6252 make_lispy_switch_frame (Lisp_Object frame)
6254 return list2 (Qswitch_frame, frame);
6257 static Lisp_Object
6258 make_lispy_focus_in (Lisp_Object frame)
6260 return list2 (Qfocus_in, frame);
6263 #ifdef HAVE_WINDOW_SYSTEM
6265 static Lisp_Object
6266 make_lispy_focus_out (Lisp_Object frame)
6268 return list2 (Qfocus_out, frame);
6271 #endif /* HAVE_WINDOW_SYSTEM */
6273 /* Manipulating modifiers. */
6275 /* Parse the name of SYMBOL, and return the set of modifiers it contains.
6277 If MODIFIER_END is non-zero, set *MODIFIER_END to the position in
6278 SYMBOL's name of the end of the modifiers; the string from this
6279 position is the unmodified symbol name.
6281 This doesn't use any caches. */
6283 static int
6284 parse_modifiers_uncached (Lisp_Object symbol, ptrdiff_t *modifier_end)
6286 Lisp_Object name;
6287 ptrdiff_t i;
6288 int modifiers;
6290 CHECK_SYMBOL (symbol);
6292 modifiers = 0;
6293 name = SYMBOL_NAME (symbol);
6295 for (i = 0; i < SBYTES (name) - 1; )
6297 ptrdiff_t this_mod_end = 0;
6298 int this_mod = 0;
6300 /* See if the name continues with a modifier word.
6301 Check that the word appears, but don't check what follows it.
6302 Set this_mod and this_mod_end to record what we find. */
6304 switch (SREF (name, i))
6306 #define SINGLE_LETTER_MOD(BIT) \
6307 (this_mod_end = i + 1, this_mod = BIT)
6309 case 'A':
6310 SINGLE_LETTER_MOD (alt_modifier);
6311 break;
6313 case 'C':
6314 SINGLE_LETTER_MOD (ctrl_modifier);
6315 break;
6317 case 'H':
6318 SINGLE_LETTER_MOD (hyper_modifier);
6319 break;
6321 case 'M':
6322 SINGLE_LETTER_MOD (meta_modifier);
6323 break;
6325 case 'S':
6326 SINGLE_LETTER_MOD (shift_modifier);
6327 break;
6329 case 's':
6330 SINGLE_LETTER_MOD (super_modifier);
6331 break;
6333 #undef SINGLE_LETTER_MOD
6335 #define MULTI_LETTER_MOD(BIT, NAME, LEN) \
6336 if (i + LEN + 1 <= SBYTES (name) \
6337 && ! memcmp (SDATA (name) + i, NAME, LEN)) \
6339 this_mod_end = i + LEN; \
6340 this_mod = BIT; \
6343 case 'd':
6344 MULTI_LETTER_MOD (drag_modifier, "drag", 4);
6345 MULTI_LETTER_MOD (down_modifier, "down", 4);
6346 MULTI_LETTER_MOD (double_modifier, "double", 6);
6347 break;
6349 case 't':
6350 MULTI_LETTER_MOD (triple_modifier, "triple", 6);
6351 break;
6352 #undef MULTI_LETTER_MOD
6356 /* If we found no modifier, stop looking for them. */
6357 if (this_mod_end == 0)
6358 break;
6360 /* Check there is a dash after the modifier, so that it
6361 really is a modifier. */
6362 if (this_mod_end >= SBYTES (name)
6363 || SREF (name, this_mod_end) != '-')
6364 break;
6366 /* This modifier is real; look for another. */
6367 modifiers |= this_mod;
6368 i = this_mod_end + 1;
6371 /* Should we include the `click' modifier? */
6372 if (! (modifiers & (down_modifier | drag_modifier
6373 | double_modifier | triple_modifier))
6374 && i + 7 == SBYTES (name)
6375 && memcmp (SDATA (name) + i, "mouse-", 6) == 0
6376 && ('0' <= SREF (name, i + 6) && SREF (name, i + 6) <= '9'))
6377 modifiers |= click_modifier;
6379 if (! (modifiers & (double_modifier | triple_modifier))
6380 && i + 6 < SBYTES (name)
6381 && memcmp (SDATA (name) + i, "wheel-", 6) == 0)
6382 modifiers |= click_modifier;
6384 if (modifier_end)
6385 *modifier_end = i;
6387 return modifiers;
6390 /* Return a symbol whose name is the modifier prefixes for MODIFIERS
6391 prepended to the string BASE[0..BASE_LEN-1].
6392 This doesn't use any caches. */
6393 static Lisp_Object
6394 apply_modifiers_uncached (int modifiers, char *base, int base_len, int base_len_byte)
6396 /* Since BASE could contain nulls, we can't use intern here; we have
6397 to use Fintern, which expects a genuine Lisp_String, and keeps a
6398 reference to it. */
6399 char new_mods[sizeof "A-C-H-M-S-s-down-drag-double-triple-"];
6400 int mod_len;
6403 char *p = new_mods;
6405 /* Only the event queue may use the `up' modifier; it should always
6406 be turned into a click or drag event before presented to lisp code. */
6407 if (modifiers & up_modifier)
6408 emacs_abort ();
6410 if (modifiers & alt_modifier) { *p++ = 'A'; *p++ = '-'; }
6411 if (modifiers & ctrl_modifier) { *p++ = 'C'; *p++ = '-'; }
6412 if (modifiers & hyper_modifier) { *p++ = 'H'; *p++ = '-'; }
6413 if (modifiers & meta_modifier) { *p++ = 'M'; *p++ = '-'; }
6414 if (modifiers & shift_modifier) { *p++ = 'S'; *p++ = '-'; }
6415 if (modifiers & super_modifier) { *p++ = 's'; *p++ = '-'; }
6416 if (modifiers & double_modifier) { strcpy (p, "double-"); p += 7; }
6417 if (modifiers & triple_modifier) { strcpy (p, "triple-"); p += 7; }
6418 if (modifiers & down_modifier) { strcpy (p, "down-"); p += 5; }
6419 if (modifiers & drag_modifier) { strcpy (p, "drag-"); p += 5; }
6420 /* The click modifier is denoted by the absence of other modifiers. */
6422 *p = '\0';
6424 mod_len = p - new_mods;
6428 Lisp_Object new_name;
6430 new_name = make_uninit_multibyte_string (mod_len + base_len,
6431 mod_len + base_len_byte);
6432 memcpy (SDATA (new_name), new_mods, mod_len);
6433 memcpy (SDATA (new_name) + mod_len, base, base_len_byte);
6435 return Fintern (new_name, Qnil);
6440 static const char *const modifier_names[] =
6442 "up", "down", "drag", "click", "double", "triple", 0, 0,
6443 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
6444 0, 0, "alt", "super", "hyper", "shift", "control", "meta"
6446 #define NUM_MOD_NAMES ARRAYELTS (modifier_names)
6448 static Lisp_Object modifier_symbols;
6450 /* Return the list of modifier symbols corresponding to the mask MODIFIERS. */
6451 static Lisp_Object
6452 lispy_modifier_list (int modifiers)
6454 Lisp_Object modifier_list;
6455 int i;
6457 modifier_list = Qnil;
6458 for (i = 0; (1<<i) <= modifiers && i < NUM_MOD_NAMES; i++)
6459 if (modifiers & (1<<i))
6460 modifier_list = Fcons (AREF (modifier_symbols, i),
6461 modifier_list);
6463 return modifier_list;
6467 /* Parse the modifiers on SYMBOL, and return a list like (UNMODIFIED MASK),
6468 where UNMODIFIED is the unmodified form of SYMBOL,
6469 MASK is the set of modifiers present in SYMBOL's name.
6470 This is similar to parse_modifiers_uncached, but uses the cache in
6471 SYMBOL's Qevent_symbol_element_mask property, and maintains the
6472 Qevent_symbol_elements property. */
6474 #define KEY_TO_CHAR(k) (XINT (k) & ((1 << CHARACTERBITS) - 1))
6476 Lisp_Object
6477 parse_modifiers (Lisp_Object symbol)
6479 Lisp_Object elements;
6481 if (INTEGERP (symbol))
6482 return list2i (KEY_TO_CHAR (symbol), XINT (symbol) & CHAR_MODIFIER_MASK);
6483 else if (!SYMBOLP (symbol))
6484 return Qnil;
6486 elements = Fget (symbol, Qevent_symbol_element_mask);
6487 if (CONSP (elements))
6488 return elements;
6489 else
6491 ptrdiff_t end;
6492 int modifiers = parse_modifiers_uncached (symbol, &end);
6493 Lisp_Object unmodified;
6494 Lisp_Object mask;
6496 unmodified = Fintern (make_string (SSDATA (SYMBOL_NAME (symbol)) + end,
6497 SBYTES (SYMBOL_NAME (symbol)) - end),
6498 Qnil);
6500 if (modifiers & ~INTMASK)
6501 emacs_abort ();
6502 XSETFASTINT (mask, modifiers);
6503 elements = list2 (unmodified, mask);
6505 /* Cache the parsing results on SYMBOL. */
6506 Fput (symbol, Qevent_symbol_element_mask,
6507 elements);
6508 Fput (symbol, Qevent_symbol_elements,
6509 Fcons (unmodified, lispy_modifier_list (modifiers)));
6511 /* Since we know that SYMBOL is modifiers applied to unmodified,
6512 it would be nice to put that in unmodified's cache.
6513 But we can't, since we're not sure that parse_modifiers is
6514 canonical. */
6516 return elements;
6520 DEFUN ("internal-event-symbol-parse-modifiers", Fevent_symbol_parse_modifiers,
6521 Sevent_symbol_parse_modifiers, 1, 1, 0,
6522 doc: /* Parse the event symbol. For internal use. */)
6523 (Lisp_Object symbol)
6525 /* Fill the cache if needed. */
6526 parse_modifiers (symbol);
6527 /* Ignore the result (which is stored on Qevent_symbol_element_mask)
6528 and use the Lispier representation stored on Qevent_symbol_elements
6529 instead. */
6530 return Fget (symbol, Qevent_symbol_elements);
6533 /* Apply the modifiers MODIFIERS to the symbol BASE.
6534 BASE must be unmodified.
6536 This is like apply_modifiers_uncached, but uses BASE's
6537 Qmodifier_cache property, if present. It also builds
6538 Qevent_symbol_elements properties, since it has that info anyway.
6540 apply_modifiers copies the value of BASE's Qevent_kind property to
6541 the modified symbol. */
6542 static Lisp_Object
6543 apply_modifiers (int modifiers, Lisp_Object base)
6545 Lisp_Object cache, idx, entry, new_symbol;
6547 /* Mask out upper bits. We don't know where this value's been. */
6548 modifiers &= INTMASK;
6550 if (INTEGERP (base))
6551 return make_number (XINT (base) | modifiers);
6553 /* The click modifier never figures into cache indices. */
6554 cache = Fget (base, Qmodifier_cache);
6555 XSETFASTINT (idx, (modifiers & ~click_modifier));
6556 entry = assq_no_quit (idx, cache);
6558 if (CONSP (entry))
6559 new_symbol = XCDR (entry);
6560 else
6562 /* We have to create the symbol ourselves. */
6563 new_symbol = apply_modifiers_uncached (modifiers,
6564 SSDATA (SYMBOL_NAME (base)),
6565 SCHARS (SYMBOL_NAME (base)),
6566 SBYTES (SYMBOL_NAME (base)));
6568 /* Add the new symbol to the base's cache. */
6569 entry = Fcons (idx, new_symbol);
6570 Fput (base, Qmodifier_cache, Fcons (entry, cache));
6572 /* We have the parsing info now for free, so we could add it to
6573 the caches:
6574 XSETFASTINT (idx, modifiers);
6575 Fput (new_symbol, Qevent_symbol_element_mask,
6576 list2 (base, idx));
6577 Fput (new_symbol, Qevent_symbol_elements,
6578 Fcons (base, lispy_modifier_list (modifiers)));
6579 Sadly, this is only correct if `base' is indeed a base event,
6580 which is not necessarily the case. -stef */
6583 /* Make sure this symbol is of the same kind as BASE.
6585 You'd think we could just set this once and for all when we
6586 intern the symbol above, but reorder_modifiers may call us when
6587 BASE's property isn't set right; we can't assume that just
6588 because it has a Qmodifier_cache property it must have its
6589 Qevent_kind set right as well. */
6590 if (NILP (Fget (new_symbol, Qevent_kind)))
6592 Lisp_Object kind;
6594 kind = Fget (base, Qevent_kind);
6595 if (! NILP (kind))
6596 Fput (new_symbol, Qevent_kind, kind);
6599 return new_symbol;
6603 /* Given a symbol whose name begins with modifiers ("C-", "M-", etc),
6604 return a symbol with the modifiers placed in the canonical order.
6605 Canonical order is alphabetical, except for down and drag, which
6606 always come last. The 'click' modifier is never written out.
6608 Fdefine_key calls this to make sure that (for example) C-M-foo
6609 and M-C-foo end up being equivalent in the keymap. */
6611 Lisp_Object
6612 reorder_modifiers (Lisp_Object symbol)
6614 /* It's hopefully okay to write the code this way, since everything
6615 will soon be in caches, and no consing will be done at all. */
6616 Lisp_Object parsed;
6618 parsed = parse_modifiers (symbol);
6619 return apply_modifiers (XFASTINT (XCAR (XCDR (parsed))),
6620 XCAR (parsed));
6624 /* For handling events, we often want to produce a symbol whose name
6625 is a series of modifier key prefixes ("M-", "C-", etcetera) attached
6626 to some base, like the name of a function key or mouse button.
6627 modify_event_symbol produces symbols of this sort.
6629 NAME_TABLE should point to an array of strings, such that NAME_TABLE[i]
6630 is the name of the i'th symbol. TABLE_SIZE is the number of elements
6631 in the table.
6633 Alternatively, NAME_ALIST_OR_STEM is either an alist mapping codes
6634 into symbol names, or a string specifying a name stem used to
6635 construct a symbol name or the form `STEM-N', where N is the decimal
6636 representation of SYMBOL_NUM. NAME_ALIST_OR_STEM is used if it is
6637 non-nil; otherwise NAME_TABLE is used.
6639 SYMBOL_TABLE should be a pointer to a Lisp_Object whose value will
6640 persist between calls to modify_event_symbol that it can use to
6641 store a cache of the symbols it's generated for this NAME_TABLE
6642 before. The object stored there may be a vector or an alist.
6644 SYMBOL_NUM is the number of the base name we want from NAME_TABLE.
6646 MODIFIERS is a set of modifier bits (as given in struct input_events)
6647 whose prefixes should be applied to the symbol name.
6649 SYMBOL_KIND is the value to be placed in the event_kind property of
6650 the returned symbol.
6652 The symbols we create are supposed to have an
6653 `event-symbol-elements' property, which lists the modifiers present
6654 in the symbol's name. */
6656 static Lisp_Object
6657 modify_event_symbol (ptrdiff_t symbol_num, int modifiers, Lisp_Object symbol_kind,
6658 Lisp_Object name_alist_or_stem, const char *const *name_table,
6659 Lisp_Object *symbol_table, ptrdiff_t table_size)
6661 Lisp_Object value;
6662 Lisp_Object symbol_int;
6664 /* Get rid of the "vendor-specific" bit here. */
6665 XSETINT (symbol_int, symbol_num & 0xffffff);
6667 /* Is this a request for a valid symbol? */
6668 if (symbol_num < 0 || symbol_num >= table_size)
6669 return Qnil;
6671 if (CONSP (*symbol_table))
6672 value = Fcdr (assq_no_quit (symbol_int, *symbol_table));
6674 /* If *symbol_table doesn't seem to be initialized properly, fix that.
6675 *symbol_table should be a lisp vector TABLE_SIZE elements long,
6676 where the Nth element is the symbol for NAME_TABLE[N], or nil if
6677 we've never used that symbol before. */
6678 else
6680 if (! VECTORP (*symbol_table)
6681 || ASIZE (*symbol_table) != table_size)
6683 Lisp_Object size;
6685 XSETFASTINT (size, table_size);
6686 *symbol_table = Fmake_vector (size, Qnil);
6689 value = AREF (*symbol_table, symbol_num);
6692 /* Have we already used this symbol before? */
6693 if (NILP (value))
6695 /* No; let's create it. */
6696 if (CONSP (name_alist_or_stem))
6697 value = Fcdr_safe (Fassq (symbol_int, name_alist_or_stem));
6698 else if (STRINGP (name_alist_or_stem))
6700 char *buf;
6701 ptrdiff_t len = (SBYTES (name_alist_or_stem)
6702 + sizeof "-" + INT_STRLEN_BOUND (EMACS_INT));
6703 USE_SAFE_ALLOCA;
6704 buf = SAFE_ALLOCA (len);
6705 esprintf (buf, "%s-%"pI"d", SDATA (name_alist_or_stem),
6706 XINT (symbol_int) + 1);
6707 value = intern (buf);
6708 SAFE_FREE ();
6710 else if (name_table != 0 && name_table[symbol_num])
6711 value = intern (name_table[symbol_num]);
6713 #ifdef HAVE_WINDOW_SYSTEM
6714 if (NILP (value))
6716 char *name = x_get_keysym_name (symbol_num);
6717 if (name)
6718 value = intern (name);
6720 #endif
6722 if (NILP (value))
6724 char buf[sizeof "key-" + INT_STRLEN_BOUND (EMACS_INT)];
6725 sprintf (buf, "key-%"pD"d", symbol_num);
6726 value = intern (buf);
6729 if (CONSP (*symbol_table))
6730 *symbol_table = Fcons (Fcons (symbol_int, value), *symbol_table);
6731 else
6732 ASET (*symbol_table, symbol_num, value);
6734 /* Fill in the cache entries for this symbol; this also
6735 builds the Qevent_symbol_elements property, which the user
6736 cares about. */
6737 apply_modifiers (modifiers & click_modifier, value);
6738 Fput (value, Qevent_kind, symbol_kind);
6741 /* Apply modifiers to that symbol. */
6742 return apply_modifiers (modifiers, value);
6745 /* Convert a list that represents an event type,
6746 such as (ctrl meta backspace), into the usual representation of that
6747 event type as a number or a symbol. */
6749 DEFUN ("event-convert-list", Fevent_convert_list, Sevent_convert_list, 1, 1, 0,
6750 doc: /* Convert the event description list EVENT-DESC to an event type.
6751 EVENT-DESC should contain one base event type (a character or symbol)
6752 and zero or more modifier names (control, meta, hyper, super, shift, alt,
6753 drag, down, double or triple). The base must be last.
6754 The return value is an event type (a character or symbol) which
6755 has the same base event type and all the specified modifiers. */)
6756 (Lisp_Object event_desc)
6758 Lisp_Object base;
6759 int modifiers = 0;
6760 Lisp_Object rest;
6762 base = Qnil;
6763 rest = event_desc;
6764 while (CONSP (rest))
6766 Lisp_Object elt;
6767 int this = 0;
6769 elt = XCAR (rest);
6770 rest = XCDR (rest);
6772 /* Given a symbol, see if it is a modifier name. */
6773 if (SYMBOLP (elt) && CONSP (rest))
6774 this = parse_solitary_modifier (elt);
6776 if (this != 0)
6777 modifiers |= this;
6778 else if (!NILP (base))
6779 error ("Two bases given in one event");
6780 else
6781 base = elt;
6785 /* Let the symbol A refer to the character A. */
6786 if (SYMBOLP (base) && SCHARS (SYMBOL_NAME (base)) == 1)
6787 XSETINT (base, SREF (SYMBOL_NAME (base), 0));
6789 if (INTEGERP (base))
6791 /* Turn (shift a) into A. */
6792 if ((modifiers & shift_modifier) != 0
6793 && (XINT (base) >= 'a' && XINT (base) <= 'z'))
6795 XSETINT (base, XINT (base) - ('a' - 'A'));
6796 modifiers &= ~shift_modifier;
6799 /* Turn (control a) into C-a. */
6800 if (modifiers & ctrl_modifier)
6801 return make_number ((modifiers & ~ctrl_modifier)
6802 | make_ctrl_char (XINT (base)));
6803 else
6804 return make_number (modifiers | XINT (base));
6806 else if (SYMBOLP (base))
6807 return apply_modifiers (modifiers, base);
6808 else
6809 error ("Invalid base event");
6812 /* Try to recognize SYMBOL as a modifier name.
6813 Return the modifier flag bit, or 0 if not recognized. */
6816 parse_solitary_modifier (Lisp_Object symbol)
6818 Lisp_Object name = SYMBOL_NAME (symbol);
6820 switch (SREF (name, 0))
6822 #define SINGLE_LETTER_MOD(BIT) \
6823 if (SBYTES (name) == 1) \
6824 return BIT;
6826 #define MULTI_LETTER_MOD(BIT, NAME, LEN) \
6827 if (LEN == SBYTES (name) \
6828 && ! memcmp (SDATA (name), NAME, LEN)) \
6829 return BIT;
6831 case 'A':
6832 SINGLE_LETTER_MOD (alt_modifier);
6833 break;
6835 case 'a':
6836 MULTI_LETTER_MOD (alt_modifier, "alt", 3);
6837 break;
6839 case 'C':
6840 SINGLE_LETTER_MOD (ctrl_modifier);
6841 break;
6843 case 'c':
6844 MULTI_LETTER_MOD (ctrl_modifier, "ctrl", 4);
6845 MULTI_LETTER_MOD (ctrl_modifier, "control", 7);
6846 break;
6848 case 'H':
6849 SINGLE_LETTER_MOD (hyper_modifier);
6850 break;
6852 case 'h':
6853 MULTI_LETTER_MOD (hyper_modifier, "hyper", 5);
6854 break;
6856 case 'M':
6857 SINGLE_LETTER_MOD (meta_modifier);
6858 break;
6860 case 'm':
6861 MULTI_LETTER_MOD (meta_modifier, "meta", 4);
6862 break;
6864 case 'S':
6865 SINGLE_LETTER_MOD (shift_modifier);
6866 break;
6868 case 's':
6869 MULTI_LETTER_MOD (shift_modifier, "shift", 5);
6870 MULTI_LETTER_MOD (super_modifier, "super", 5);
6871 SINGLE_LETTER_MOD (super_modifier);
6872 break;
6874 case 'd':
6875 MULTI_LETTER_MOD (drag_modifier, "drag", 4);
6876 MULTI_LETTER_MOD (down_modifier, "down", 4);
6877 MULTI_LETTER_MOD (double_modifier, "double", 6);
6878 break;
6880 case 't':
6881 MULTI_LETTER_MOD (triple_modifier, "triple", 6);
6882 break;
6884 #undef SINGLE_LETTER_MOD
6885 #undef MULTI_LETTER_MOD
6888 return 0;
6891 /* Return true if EVENT is a list whose elements are all integers or symbols.
6892 Such a list is not valid as an event,
6893 but it can be a Lucid-style event type list. */
6895 bool
6896 lucid_event_type_list_p (Lisp_Object object)
6898 Lisp_Object tail;
6900 if (! CONSP (object))
6901 return 0;
6903 if (EQ (XCAR (object), Qhelp_echo)
6904 || EQ (XCAR (object), Qvertical_line)
6905 || EQ (XCAR (object), Qmode_line)
6906 || EQ (XCAR (object), Qheader_line))
6907 return 0;
6909 for (tail = object; CONSP (tail); tail = XCDR (tail))
6911 Lisp_Object elt;
6912 elt = XCAR (tail);
6913 if (! (INTEGERP (elt) || SYMBOLP (elt)))
6914 return 0;
6917 return NILP (tail);
6920 /* Return true if terminal input chars are available.
6921 Also, store the return value into INPUT_PENDING.
6923 Serves the purpose of ioctl (0, FIONREAD, ...)
6924 but works even if FIONREAD does not exist.
6925 (In fact, this may actually read some input.)
6927 If READABLE_EVENTS_DO_TIMERS_NOW is set in FLAGS, actually run
6928 timer events that are ripe.
6929 If READABLE_EVENTS_FILTER_EVENTS is set in FLAGS, ignore internal
6930 events (FOCUS_IN_EVENT).
6931 If READABLE_EVENTS_IGNORE_SQUEEZABLES is set in FLAGS, ignore mouse
6932 movements and toolkit scroll bar thumb drags. */
6934 static bool
6935 get_input_pending (int flags)
6937 /* First of all, have we already counted some input? */
6938 input_pending = (!NILP (Vquit_flag) || readable_events (flags));
6940 /* If input is being read as it arrives, and we have none, there is none. */
6941 if (!input_pending && (!interrupt_input || interrupts_deferred))
6943 /* Try to read some input and see how much we get. */
6944 gobble_input ();
6945 input_pending = (!NILP (Vquit_flag) || readable_events (flags));
6948 return input_pending;
6951 /* Put a BUFFER_SWITCH_EVENT in the buffer
6952 so that read_key_sequence will notice the new current buffer. */
6954 void
6955 record_asynch_buffer_change (void)
6957 /* We don't need a buffer-switch event unless Emacs is waiting for input.
6958 The purpose of the event is to make read_key_sequence look up the
6959 keymaps again. If we aren't in read_key_sequence, we don't need one,
6960 and the event could cause trouble by messing up (input-pending-p).
6961 Note: Fwaiting_for_user_input_p always returns nil when async
6962 subprocesses aren't supported. */
6963 if (!NILP (Fwaiting_for_user_input_p ()))
6965 struct input_event event;
6967 EVENT_INIT (event);
6968 event.kind = BUFFER_SWITCH_EVENT;
6969 event.frame_or_window = Qnil;
6970 event.arg = Qnil;
6972 /* Make sure no interrupt happens while storing the event. */
6973 #ifdef USABLE_SIGIO
6974 if (interrupt_input)
6975 kbd_buffer_store_event (&event);
6976 else
6977 #endif
6979 stop_polling ();
6980 kbd_buffer_store_event (&event);
6981 start_polling ();
6986 /* Read any terminal input already buffered up by the system
6987 into the kbd_buffer, but do not wait.
6989 Return the number of keyboard chars read, or -1 meaning
6990 this is a bad time to try to read input. */
6993 gobble_input (void)
6995 int nread = 0;
6996 bool err = 0;
6997 struct terminal *t;
6999 /* Store pending user signal events, if any. */
7000 store_user_signal_events ();
7002 /* Loop through the available terminals, and call their input hooks. */
7003 t = terminal_list;
7004 while (t)
7006 struct terminal *next = t->next_terminal;
7008 if (t->read_socket_hook)
7010 int nr;
7011 struct input_event hold_quit;
7013 if (input_blocked_p ())
7015 pending_signals = 1;
7016 break;
7019 EVENT_INIT (hold_quit);
7020 hold_quit.kind = NO_EVENT;
7022 /* No need for FIONREAD or fcntl; just say don't wait. */
7023 while ((nr = (*t->read_socket_hook) (t, &hold_quit)) > 0)
7024 nread += nr;
7026 if (nr == -1) /* Not OK to read input now. */
7028 err = 1;
7030 else if (nr == -2) /* Non-transient error. */
7032 /* The terminal device terminated; it should be closed. */
7034 /* Kill Emacs if this was our last terminal. */
7035 if (!terminal_list->next_terminal)
7036 /* Formerly simply reported no input, but that
7037 sometimes led to a failure of Emacs to terminate.
7038 SIGHUP seems appropriate if we can't reach the
7039 terminal. */
7040 /* ??? Is it really right to send the signal just to
7041 this process rather than to the whole process
7042 group? Perhaps on systems with FIONREAD Emacs is
7043 alone in its group. */
7044 terminate_due_to_signal (SIGHUP, 10);
7046 /* XXX Is calling delete_terminal safe here? It calls delete_frame. */
7048 Lisp_Object tmp;
7049 XSETTERMINAL (tmp, t);
7050 Fdelete_terminal (tmp, Qnoelisp);
7054 /* If there was no error, make sure the pointer
7055 is visible for all frames on this terminal. */
7056 if (nr >= 0)
7058 Lisp_Object tail, frame;
7060 FOR_EACH_FRAME (tail, frame)
7062 struct frame *f = XFRAME (frame);
7063 if (FRAME_TERMINAL (f) == t)
7064 frame_make_pointer_visible (f);
7068 if (hold_quit.kind != NO_EVENT)
7069 kbd_buffer_store_event (&hold_quit);
7072 t = next;
7075 if (err && !nread)
7076 nread = -1;
7078 return nread;
7081 /* This is the tty way of reading available input.
7083 Note that each terminal device has its own `struct terminal' object,
7084 and so this function is called once for each individual termcap
7085 terminal. The first parameter indicates which terminal to read from. */
7088 tty_read_avail_input (struct terminal *terminal,
7089 struct input_event *hold_quit)
7091 /* Using KBD_BUFFER_SIZE - 1 here avoids reading more than
7092 the kbd_buffer can really hold. That may prevent loss
7093 of characters on some systems when input is stuffed at us. */
7094 unsigned char cbuf[KBD_BUFFER_SIZE - 1];
7095 int n_to_read, i;
7096 struct tty_display_info *tty = terminal->display_info.tty;
7097 int nread = 0;
7098 #ifdef subprocesses
7099 int buffer_free = KBD_BUFFER_SIZE - kbd_buffer_nr_stored () - 1;
7101 if (kbd_on_hold_p () || buffer_free <= 0)
7102 return 0;
7103 #endif /* subprocesses */
7105 if (!terminal->name) /* Don't read from a dead terminal. */
7106 return 0;
7108 if (terminal->type != output_termcap
7109 && terminal->type != output_msdos_raw)
7110 emacs_abort ();
7112 /* XXX I think the following code should be moved to separate hook
7113 functions in system-dependent files. */
7114 #ifdef WINDOWSNT
7115 /* FIXME: AFAIK, tty_read_avail_input is not used under w32 since the non-GUI
7116 code sets read_socket_hook to w32_console_read_socket instead! */
7117 return 0;
7118 #else /* not WINDOWSNT */
7119 if (! tty->term_initted) /* In case we get called during bootstrap. */
7120 return 0;
7122 if (! tty->input)
7123 return 0; /* The terminal is suspended. */
7125 #ifdef MSDOS
7126 n_to_read = dos_keysns ();
7127 if (n_to_read == 0)
7128 return 0;
7130 cbuf[0] = dos_keyread ();
7131 nread = 1;
7133 #else /* not MSDOS */
7134 #ifdef HAVE_GPM
7135 if (gpm_tty == tty)
7137 Gpm_Event event;
7138 struct input_event gpm_hold_quit;
7139 int gpm, fd = gpm_fd;
7141 EVENT_INIT (gpm_hold_quit);
7142 gpm_hold_quit.kind = NO_EVENT;
7144 /* gpm==1 if event received.
7145 gpm==0 if the GPM daemon has closed the connection, in which case
7146 Gpm_GetEvent closes gpm_fd and clears it to -1, which is why
7147 we save it in `fd' so close_gpm can remove it from the
7148 select masks.
7149 gpm==-1 if a protocol error or EWOULDBLOCK; the latter is normal. */
7150 while (gpm = Gpm_GetEvent (&event), gpm == 1) {
7151 nread += handle_one_term_event (tty, &event, &gpm_hold_quit);
7153 if (gpm == 0)
7154 /* Presumably the GPM daemon has closed the connection. */
7155 close_gpm (fd);
7156 if (gpm_hold_quit.kind != NO_EVENT)
7157 kbd_buffer_store_event (&gpm_hold_quit);
7158 if (nread)
7159 return nread;
7161 #endif /* HAVE_GPM */
7163 /* Determine how many characters we should *try* to read. */
7164 #ifdef USABLE_FIONREAD
7165 /* Find out how much input is available. */
7166 if (ioctl (fileno (tty->input), FIONREAD, &n_to_read) < 0)
7168 if (! noninteractive)
7169 return -2; /* Close this terminal. */
7170 else
7171 n_to_read = 0;
7173 if (n_to_read == 0)
7174 return 0;
7175 if (n_to_read > sizeof cbuf)
7176 n_to_read = sizeof cbuf;
7177 #elif defined USG || defined CYGWIN
7178 /* Read some input if available, but don't wait. */
7179 n_to_read = sizeof cbuf;
7180 fcntl (fileno (tty->input), F_SETFL, O_NONBLOCK);
7181 #else
7182 # error "Cannot read without possibly delaying"
7183 #endif
7185 #ifdef subprocesses
7186 /* Don't read more than we can store. */
7187 if (n_to_read > buffer_free)
7188 n_to_read = buffer_free;
7189 #endif /* subprocesses */
7191 /* Now read; for one reason or another, this will not block.
7192 NREAD is set to the number of chars read. */
7195 nread = emacs_read (fileno (tty->input), (char *) cbuf, n_to_read);
7196 /* POSIX infers that processes which are not in the session leader's
7197 process group won't get SIGHUPs at logout time. BSDI adheres to
7198 this part standard and returns -1 from read (0) with errno==EIO
7199 when the control tty is taken away.
7200 Jeffrey Honig <jch@bsdi.com> says this is generally safe. */
7201 if (nread == -1 && errno == EIO)
7202 return -2; /* Close this terminal. */
7203 #if defined (AIX) && defined (_BSD)
7204 /* The kernel sometimes fails to deliver SIGHUP for ptys.
7205 This looks incorrect, but it isn't, because _BSD causes
7206 O_NDELAY to be defined in fcntl.h as O_NONBLOCK,
7207 and that causes a value other than 0 when there is no input. */
7208 if (nread == 0)
7209 return -2; /* Close this terminal. */
7210 #endif
7212 while (
7213 /* We used to retry the read if it was interrupted.
7214 But this does the wrong thing when O_NONBLOCK causes
7215 an EAGAIN error. Does anybody know of a situation
7216 where a retry is actually needed? */
7217 #if 0
7218 nread < 0 && (errno == EAGAIN || errno == EFAULT
7219 #ifdef EBADSLT
7220 || errno == EBADSLT
7221 #endif
7223 #else
7225 #endif
7228 #ifndef USABLE_FIONREAD
7229 #if defined (USG) || defined (CYGWIN)
7230 fcntl (fileno (tty->input), F_SETFL, 0);
7231 #endif /* USG or CYGWIN */
7232 #endif /* no FIONREAD */
7234 if (nread <= 0)
7235 return nread;
7237 #endif /* not MSDOS */
7238 #endif /* not WINDOWSNT */
7240 for (i = 0; i < nread; i++)
7242 struct input_event buf;
7243 EVENT_INIT (buf);
7244 buf.kind = ASCII_KEYSTROKE_EVENT;
7245 buf.modifiers = 0;
7246 if (tty->meta_key == 1 && (cbuf[i] & 0x80))
7247 buf.modifiers = meta_modifier;
7248 if (tty->meta_key != 2)
7249 cbuf[i] &= ~0x80;
7251 buf.code = cbuf[i];
7252 /* Set the frame corresponding to the active tty. Note that the
7253 value of selected_frame is not reliable here, redisplay tends
7254 to temporarily change it. */
7255 buf.frame_or_window = tty->top_frame;
7256 buf.arg = Qnil;
7258 kbd_buffer_store_event (&buf);
7259 /* Don't look at input that follows a C-g too closely.
7260 This reduces lossage due to autorepeat on C-g. */
7261 if (buf.kind == ASCII_KEYSTROKE_EVENT
7262 && buf.code == quit_char)
7263 break;
7266 return nread;
7269 static void
7270 handle_async_input (void)
7272 #ifdef USABLE_SIGIO
7273 while (1)
7275 int nread = gobble_input ();
7276 /* -1 means it's not ok to read the input now.
7277 UNBLOCK_INPUT will read it later; now, avoid infinite loop.
7278 0 means there was no keyboard input available. */
7279 if (nread <= 0)
7280 break;
7282 #endif
7285 void
7286 process_pending_signals (void)
7288 pending_signals = 0;
7289 handle_async_input ();
7290 do_pending_atimers ();
7293 /* Undo any number of BLOCK_INPUT calls down to level LEVEL,
7294 and reinvoke any pending signal if the level is now 0 and
7295 a fatal error is not already in progress. */
7297 void
7298 unblock_input_to (int level)
7300 interrupt_input_blocked = level;
7301 if (level == 0)
7303 if (pending_signals && !fatal_error_in_progress)
7304 process_pending_signals ();
7306 else if (level < 0)
7307 emacs_abort ();
7310 /* End critical section.
7312 If doing signal-driven input, and a signal came in when input was
7313 blocked, reinvoke the signal handler now to deal with it.
7315 It will also process queued input, if it was not read before.
7316 When a longer code sequence does not use block/unblock input
7317 at all, the whole input gathered up to the next call to
7318 unblock_input will be processed inside that call. */
7320 void
7321 unblock_input (void)
7323 unblock_input_to (interrupt_input_blocked - 1);
7326 /* Undo any number of BLOCK_INPUT calls,
7327 and also reinvoke any pending signal. */
7329 void
7330 totally_unblock_input (void)
7332 unblock_input_to (0);
7335 #ifdef USABLE_SIGIO
7337 void
7338 handle_input_available_signal (int sig)
7340 pending_signals = 1;
7342 if (input_available_clear_time)
7343 *input_available_clear_time = make_timespec (0, 0);
7346 static void
7347 deliver_input_available_signal (int sig)
7349 deliver_process_signal (sig, handle_input_available_signal);
7351 #endif /* USABLE_SIGIO */
7354 /* User signal events. */
7356 struct user_signal_info
7358 /* Signal number. */
7359 int sig;
7361 /* Name of the signal. */
7362 char *name;
7364 /* Number of pending signals. */
7365 int npending;
7367 struct user_signal_info *next;
7370 /* List of user signals. */
7371 static struct user_signal_info *user_signals = NULL;
7373 void
7374 add_user_signal (int sig, const char *name)
7376 struct sigaction action;
7377 struct user_signal_info *p;
7379 for (p = user_signals; p; p = p->next)
7380 if (p->sig == sig)
7381 /* Already added. */
7382 return;
7384 p = xmalloc (sizeof *p);
7385 p->sig = sig;
7386 p->name = xstrdup (name);
7387 p->npending = 0;
7388 p->next = user_signals;
7389 user_signals = p;
7391 emacs_sigaction_init (&action, deliver_user_signal);
7392 sigaction (sig, &action, 0);
7395 static void
7396 handle_user_signal (int sig)
7398 struct user_signal_info *p;
7399 const char *special_event_name = NULL;
7401 if (SYMBOLP (Vdebug_on_event))
7402 special_event_name = SSDATA (SYMBOL_NAME (Vdebug_on_event));
7404 for (p = user_signals; p; p = p->next)
7405 if (p->sig == sig)
7407 if (special_event_name
7408 && strcmp (special_event_name, p->name) == 0)
7410 /* Enter the debugger in many ways. */
7411 debug_on_next_call = 1;
7412 debug_on_quit = 1;
7413 Vquit_flag = Qt;
7414 Vinhibit_quit = Qnil;
7416 /* Eat the event. */
7417 break;
7420 p->npending++;
7421 #ifdef USABLE_SIGIO
7422 if (interrupt_input)
7423 handle_input_available_signal (sig);
7424 else
7425 #endif
7427 /* Tell wait_reading_process_output that it needs to wake
7428 up and look around. */
7429 if (input_available_clear_time)
7430 *input_available_clear_time = make_timespec (0, 0);
7432 break;
7436 static void
7437 deliver_user_signal (int sig)
7439 deliver_process_signal (sig, handle_user_signal);
7442 static char *
7443 find_user_signal_name (int sig)
7445 struct user_signal_info *p;
7447 for (p = user_signals; p; p = p->next)
7448 if (p->sig == sig)
7449 return p->name;
7451 return NULL;
7454 static void
7455 store_user_signal_events (void)
7457 struct user_signal_info *p;
7458 struct input_event buf;
7459 bool buf_initialized = 0;
7461 for (p = user_signals; p; p = p->next)
7462 if (p->npending > 0)
7464 if (! buf_initialized)
7466 memset (&buf, 0, sizeof buf);
7467 buf.kind = USER_SIGNAL_EVENT;
7468 buf.frame_or_window = selected_frame;
7469 buf_initialized = 1;
7474 buf.code = p->sig;
7475 kbd_buffer_store_event (&buf);
7476 p->npending--;
7478 while (p->npending > 0);
7483 static void menu_bar_item (Lisp_Object, Lisp_Object, Lisp_Object, void *);
7484 static Lisp_Object menu_bar_one_keymap_changed_items;
7486 /* These variables hold the vector under construction within
7487 menu_bar_items and its subroutines, and the current index
7488 for storing into that vector. */
7489 static Lisp_Object menu_bar_items_vector;
7490 static int menu_bar_items_index;
7493 static const char *separator_names[] = {
7494 "space",
7495 "no-line",
7496 "single-line",
7497 "double-line",
7498 "single-dashed-line",
7499 "double-dashed-line",
7500 "shadow-etched-in",
7501 "shadow-etched-out",
7502 "shadow-etched-in-dash",
7503 "shadow-etched-out-dash",
7504 "shadow-double-etched-in",
7505 "shadow-double-etched-out",
7506 "shadow-double-etched-in-dash",
7507 "shadow-double-etched-out-dash",
7511 /* Return true if LABEL specifies a separator. */
7513 bool
7514 menu_separator_name_p (const char *label)
7516 if (!label)
7517 return 0;
7518 else if (strlen (label) > 3
7519 && memcmp (label, "--", 2) == 0
7520 && label[2] != '-')
7522 int i;
7523 label += 2;
7524 for (i = 0; separator_names[i]; ++i)
7525 if (strcmp (label, separator_names[i]) == 0)
7526 return 1;
7528 else
7530 /* It's a separator if it contains only dashes. */
7531 while (*label == '-')
7532 ++label;
7533 return (*label == 0);
7536 return 0;
7540 /* Return a vector of menu items for a menu bar, appropriate
7541 to the current buffer. Each item has three elements in the vector:
7542 KEY STRING MAPLIST.
7544 OLD is an old vector we can optionally reuse, or nil. */
7546 Lisp_Object
7547 menu_bar_items (Lisp_Object old)
7549 /* The number of keymaps we're scanning right now, and the number of
7550 keymaps we have allocated space for. */
7551 ptrdiff_t nmaps;
7553 /* maps[0..nmaps-1] are the prefix definitions of KEYBUF[0..t-1]
7554 in the current keymaps, or nil where it is not a prefix. */
7555 Lisp_Object *maps;
7557 Lisp_Object mapsbuf[3];
7558 Lisp_Object def, tail;
7560 ptrdiff_t mapno;
7561 Lisp_Object oquit;
7563 USE_SAFE_ALLOCA;
7565 /* In order to build the menus, we need to call the keymap
7566 accessors. They all call QUIT. But this function is called
7567 during redisplay, during which a quit is fatal. So inhibit
7568 quitting while building the menus.
7569 We do this instead of specbind because (1) errors will clear it anyway
7570 and (2) this avoids risk of specpdl overflow. */
7571 oquit = Vinhibit_quit;
7572 Vinhibit_quit = Qt;
7574 if (!NILP (old))
7575 menu_bar_items_vector = old;
7576 else
7577 menu_bar_items_vector = Fmake_vector (make_number (24), Qnil);
7578 menu_bar_items_index = 0;
7580 /* Build our list of keymaps.
7581 If we recognize a function key and replace its escape sequence in
7582 keybuf with its symbol, or if the sequence starts with a mouse
7583 click and we need to switch buffers, we jump back here to rebuild
7584 the initial keymaps from the current buffer. */
7586 Lisp_Object *tmaps;
7588 /* Should overriding-terminal-local-map and overriding-local-map apply? */
7589 if (!NILP (Voverriding_local_map_menu_flag)
7590 && !NILP (Voverriding_local_map))
7592 /* Yes, use them (if non-nil) as well as the global map. */
7593 maps = mapsbuf;
7594 nmaps = 0;
7595 if (!NILP (KVAR (current_kboard, Voverriding_terminal_local_map)))
7596 maps[nmaps++] = KVAR (current_kboard, Voverriding_terminal_local_map);
7597 if (!NILP (Voverriding_local_map))
7598 maps[nmaps++] = Voverriding_local_map;
7600 else
7602 /* No, so use major and minor mode keymaps and keymap property.
7603 Note that menu-bar bindings in the local-map and keymap
7604 properties may not work reliable, as they are only
7605 recognized when the menu-bar (or mode-line) is updated,
7606 which does not normally happen after every command. */
7607 Lisp_Object tem;
7608 ptrdiff_t nminor;
7609 nminor = current_minor_maps (NULL, &tmaps);
7610 SAFE_NALLOCA (maps, 1, nminor + 4);
7611 nmaps = 0;
7612 tem = KVAR (current_kboard, Voverriding_terminal_local_map);
7613 if (!NILP (tem) && !NILP (Voverriding_local_map_menu_flag))
7614 maps[nmaps++] = tem;
7615 if (tem = get_local_map (PT, current_buffer, Qkeymap), !NILP (tem))
7616 maps[nmaps++] = tem;
7617 memcpy (maps + nmaps, tmaps, nminor * sizeof (maps[0]));
7618 nmaps += nminor;
7619 maps[nmaps++] = get_local_map (PT, current_buffer, Qlocal_map);
7621 maps[nmaps++] = current_global_map;
7624 /* Look up in each map the dummy prefix key `menu-bar'. */
7626 for (mapno = nmaps - 1; mapno >= 0; mapno--)
7627 if (!NILP (maps[mapno]))
7629 def = get_keymap (access_keymap (maps[mapno], Qmenu_bar, 1, 0, 1),
7630 0, 1);
7631 if (CONSP (def))
7633 menu_bar_one_keymap_changed_items = Qnil;
7634 map_keymap_canonical (def, menu_bar_item, Qnil, NULL);
7638 /* Move to the end those items that should be at the end. */
7640 for (tail = Vmenu_bar_final_items; CONSP (tail); tail = XCDR (tail))
7642 int i;
7643 int end = menu_bar_items_index;
7645 for (i = 0; i < end; i += 4)
7646 if (EQ (XCAR (tail), AREF (menu_bar_items_vector, i)))
7648 Lisp_Object tem0, tem1, tem2, tem3;
7649 /* Move the item at index I to the end,
7650 shifting all the others forward. */
7651 tem0 = AREF (menu_bar_items_vector, i + 0);
7652 tem1 = AREF (menu_bar_items_vector, i + 1);
7653 tem2 = AREF (menu_bar_items_vector, i + 2);
7654 tem3 = AREF (menu_bar_items_vector, i + 3);
7655 if (end > i + 4)
7656 memmove (aref_addr (menu_bar_items_vector, i),
7657 aref_addr (menu_bar_items_vector, i + 4),
7658 (end - i - 4) * word_size);
7659 ASET (menu_bar_items_vector, end - 4, tem0);
7660 ASET (menu_bar_items_vector, end - 3, tem1);
7661 ASET (menu_bar_items_vector, end - 2, tem2);
7662 ASET (menu_bar_items_vector, end - 1, tem3);
7663 break;
7667 /* Add nil, nil, nil, nil at the end. */
7669 int i = menu_bar_items_index;
7670 if (i + 4 > ASIZE (menu_bar_items_vector))
7671 menu_bar_items_vector
7672 = larger_vector (menu_bar_items_vector, 4, -1);
7673 /* Add this item. */
7674 ASET (menu_bar_items_vector, i, Qnil); i++;
7675 ASET (menu_bar_items_vector, i, Qnil); i++;
7676 ASET (menu_bar_items_vector, i, Qnil); i++;
7677 ASET (menu_bar_items_vector, i, Qnil); i++;
7678 menu_bar_items_index = i;
7681 Vinhibit_quit = oquit;
7682 SAFE_FREE ();
7683 return menu_bar_items_vector;
7686 /* Add one item to menu_bar_items_vector, for KEY, ITEM_STRING and DEF.
7687 If there's already an item for KEY, add this DEF to it. */
7689 Lisp_Object item_properties;
7691 static void
7692 menu_bar_item (Lisp_Object key, Lisp_Object item, Lisp_Object dummy1, void *dummy2)
7694 struct gcpro gcpro1;
7695 int i;
7696 bool parsed;
7697 Lisp_Object tem;
7699 if (EQ (item, Qundefined))
7701 /* If a map has an explicit `undefined' as definition,
7702 discard any previously made menu bar item. */
7704 for (i = 0; i < menu_bar_items_index; i += 4)
7705 if (EQ (key, AREF (menu_bar_items_vector, i)))
7707 if (menu_bar_items_index > i + 4)
7708 memmove (aref_addr (menu_bar_items_vector, i),
7709 aref_addr (menu_bar_items_vector, i + 4),
7710 (menu_bar_items_index - i - 4) * word_size);
7711 menu_bar_items_index -= 4;
7715 /* If this keymap has already contributed to this KEY,
7716 don't contribute to it a second time. */
7717 tem = Fmemq (key, menu_bar_one_keymap_changed_items);
7718 if (!NILP (tem) || NILP (item))
7719 return;
7721 menu_bar_one_keymap_changed_items
7722 = Fcons (key, menu_bar_one_keymap_changed_items);
7724 /* We add to menu_bar_one_keymap_changed_items before doing the
7725 parse_menu_item, so that if it turns out it wasn't a menu item,
7726 it still correctly hides any further menu item. */
7727 GCPRO1 (key);
7728 parsed = parse_menu_item (item, 1);
7729 UNGCPRO;
7730 if (!parsed)
7731 return;
7733 item = AREF (item_properties, ITEM_PROPERTY_DEF);
7735 /* Find any existing item for this KEY. */
7736 for (i = 0; i < menu_bar_items_index; i += 4)
7737 if (EQ (key, AREF (menu_bar_items_vector, i)))
7738 break;
7740 /* If we did not find this KEY, add it at the end. */
7741 if (i == menu_bar_items_index)
7743 /* If vector is too small, get a bigger one. */
7744 if (i + 4 > ASIZE (menu_bar_items_vector))
7745 menu_bar_items_vector = larger_vector (menu_bar_items_vector, 4, -1);
7746 /* Add this item. */
7747 ASET (menu_bar_items_vector, i, key); i++;
7748 ASET (menu_bar_items_vector, i,
7749 AREF (item_properties, ITEM_PROPERTY_NAME)); i++;
7750 ASET (menu_bar_items_vector, i, list1 (item)); i++;
7751 ASET (menu_bar_items_vector, i, make_number (0)); i++;
7752 menu_bar_items_index = i;
7754 /* We did find an item for this KEY. Add ITEM to its list of maps. */
7755 else
7757 Lisp_Object old;
7758 old = AREF (menu_bar_items_vector, i + 2);
7759 /* If the new and the old items are not both keymaps,
7760 the lookup will only find `item'. */
7761 item = Fcons (item, KEYMAPP (item) && KEYMAPP (XCAR (old)) ? old : Qnil);
7762 ASET (menu_bar_items_vector, i + 2, item);
7766 /* This is used as the handler when calling menu_item_eval_property. */
7767 static Lisp_Object
7768 menu_item_eval_property_1 (Lisp_Object arg)
7770 /* If we got a quit from within the menu computation,
7771 quit all the way out of it. This takes care of C-] in the debugger. */
7772 if (CONSP (arg) && EQ (XCAR (arg), Qquit))
7773 Fsignal (Qquit, Qnil);
7775 return Qnil;
7778 static Lisp_Object
7779 eval_dyn (Lisp_Object form)
7781 return Feval (form, Qnil);
7784 /* Evaluate an expression and return the result (or nil if something
7785 went wrong). Used to evaluate dynamic parts of menu items. */
7786 Lisp_Object
7787 menu_item_eval_property (Lisp_Object sexpr)
7789 ptrdiff_t count = SPECPDL_INDEX ();
7790 Lisp_Object val;
7791 specbind (Qinhibit_redisplay, Qt);
7792 val = internal_condition_case_1 (eval_dyn, sexpr, Qerror,
7793 menu_item_eval_property_1);
7794 return unbind_to (count, val);
7797 /* This function parses a menu item and leaves the result in the
7798 vector item_properties.
7799 ITEM is a key binding, a possible menu item.
7800 INMENUBAR is > 0 when this is considered for an entry in a menu bar
7801 top level.
7802 INMENUBAR is < 0 when this is considered for an entry in a keyboard menu.
7803 parse_menu_item returns true if the item is a menu item and false
7804 otherwise. */
7806 bool
7807 parse_menu_item (Lisp_Object item, int inmenubar)
7809 Lisp_Object def, tem, item_string, start;
7810 Lisp_Object filter;
7811 Lisp_Object keyhint;
7812 int i;
7814 filter = Qnil;
7815 keyhint = Qnil;
7817 if (!CONSP (item))
7818 return 0;
7820 /* Create item_properties vector if necessary. */
7821 if (NILP (item_properties))
7822 item_properties
7823 = Fmake_vector (make_number (ITEM_PROPERTY_ENABLE + 1), Qnil);
7825 /* Initialize optional entries. */
7826 for (i = ITEM_PROPERTY_DEF; i < ITEM_PROPERTY_ENABLE; i++)
7827 ASET (item_properties, i, Qnil);
7828 ASET (item_properties, ITEM_PROPERTY_ENABLE, Qt);
7830 /* Save the item here to protect it from GC. */
7831 ASET (item_properties, ITEM_PROPERTY_ITEM, item);
7833 item_string = XCAR (item);
7835 start = item;
7836 item = XCDR (item);
7837 if (STRINGP (item_string))
7839 /* Old format menu item. */
7840 ASET (item_properties, ITEM_PROPERTY_NAME, item_string);
7842 /* Maybe help string. */
7843 if (CONSP (item) && STRINGP (XCAR (item)))
7845 ASET (item_properties, ITEM_PROPERTY_HELP, XCAR (item));
7846 start = item;
7847 item = XCDR (item);
7850 /* Maybe an obsolete key binding cache. */
7851 if (CONSP (item) && CONSP (XCAR (item))
7852 && (NILP (XCAR (XCAR (item)))
7853 || VECTORP (XCAR (XCAR (item)))))
7854 item = XCDR (item);
7856 /* This is the real definition--the function to run. */
7857 ASET (item_properties, ITEM_PROPERTY_DEF, item);
7859 /* Get enable property, if any. */
7860 if (SYMBOLP (item))
7862 tem = Fget (item, Qmenu_enable);
7863 if (!NILP (Venable_disabled_menus_and_buttons))
7864 ASET (item_properties, ITEM_PROPERTY_ENABLE, Qt);
7865 else if (!NILP (tem))
7866 ASET (item_properties, ITEM_PROPERTY_ENABLE, tem);
7869 else if (EQ (item_string, Qmenu_item) && CONSP (item))
7871 /* New format menu item. */
7872 ASET (item_properties, ITEM_PROPERTY_NAME, XCAR (item));
7873 start = XCDR (item);
7874 if (CONSP (start))
7876 /* We have a real binding. */
7877 ASET (item_properties, ITEM_PROPERTY_DEF, XCAR (start));
7879 item = XCDR (start);
7880 /* Is there an obsolete cache list with key equivalences. */
7881 if (CONSP (item) && CONSP (XCAR (item)))
7882 item = XCDR (item);
7884 /* Parse properties. */
7885 while (CONSP (item) && CONSP (XCDR (item)))
7887 tem = XCAR (item);
7888 item = XCDR (item);
7890 if (EQ (tem, QCenable))
7892 if (!NILP (Venable_disabled_menus_and_buttons))
7893 ASET (item_properties, ITEM_PROPERTY_ENABLE, Qt);
7894 else
7895 ASET (item_properties, ITEM_PROPERTY_ENABLE, XCAR (item));
7897 else if (EQ (tem, QCvisible))
7899 /* If got a visible property and that evaluates to nil
7900 then ignore this item. */
7901 tem = menu_item_eval_property (XCAR (item));
7902 if (NILP (tem))
7903 return 0;
7905 else if (EQ (tem, QChelp))
7906 ASET (item_properties, ITEM_PROPERTY_HELP, XCAR (item));
7907 else if (EQ (tem, QCfilter))
7908 filter = item;
7909 else if (EQ (tem, QCkey_sequence))
7911 tem = XCAR (item);
7912 if (SYMBOLP (tem) || STRINGP (tem) || VECTORP (tem))
7913 /* Be GC protected. Set keyhint to item instead of tem. */
7914 keyhint = item;
7916 else if (EQ (tem, QCkeys))
7918 tem = XCAR (item);
7919 if (CONSP (tem) || STRINGP (tem))
7920 ASET (item_properties, ITEM_PROPERTY_KEYEQ, tem);
7922 else if (EQ (tem, QCbutton) && CONSP (XCAR (item)))
7924 Lisp_Object type;
7925 tem = XCAR (item);
7926 type = XCAR (tem);
7927 if (EQ (type, QCtoggle) || EQ (type, QCradio))
7929 ASET (item_properties, ITEM_PROPERTY_SELECTED,
7930 XCDR (tem));
7931 ASET (item_properties, ITEM_PROPERTY_TYPE, type);
7934 item = XCDR (item);
7937 else if (inmenubar || !NILP (start))
7938 return 0;
7940 else
7941 return 0; /* not a menu item */
7943 /* If item string is not a string, evaluate it to get string.
7944 If we don't get a string, skip this item. */
7945 item_string = AREF (item_properties, ITEM_PROPERTY_NAME);
7946 if (!(STRINGP (item_string)))
7948 item_string = menu_item_eval_property (item_string);
7949 if (!STRINGP (item_string))
7950 return 0;
7951 ASET (item_properties, ITEM_PROPERTY_NAME, item_string);
7954 /* If got a filter apply it on definition. */
7955 def = AREF (item_properties, ITEM_PROPERTY_DEF);
7956 if (!NILP (filter))
7958 def = menu_item_eval_property (list2 (XCAR (filter),
7959 list2 (Qquote, def)));
7961 ASET (item_properties, ITEM_PROPERTY_DEF, def);
7964 /* Enable or disable selection of item. */
7965 tem = AREF (item_properties, ITEM_PROPERTY_ENABLE);
7966 if (!EQ (tem, Qt))
7968 tem = menu_item_eval_property (tem);
7969 if (inmenubar && NILP (tem))
7970 return 0; /* Ignore disabled items in menu bar. */
7971 ASET (item_properties, ITEM_PROPERTY_ENABLE, tem);
7974 /* If we got no definition, this item is just unselectable text which
7975 is OK in a submenu but not in the menubar. */
7976 if (NILP (def))
7977 return (!inmenubar);
7979 /* See if this is a separate pane or a submenu. */
7980 def = AREF (item_properties, ITEM_PROPERTY_DEF);
7981 tem = get_keymap (def, 0, 1);
7982 /* For a subkeymap, just record its details and exit. */
7983 if (CONSP (tem))
7985 ASET (item_properties, ITEM_PROPERTY_MAP, tem);
7986 ASET (item_properties, ITEM_PROPERTY_DEF, tem);
7987 return 1;
7990 /* At the top level in the menu bar, do likewise for commands also.
7991 The menu bar does not display equivalent key bindings anyway.
7992 ITEM_PROPERTY_DEF is already set up properly. */
7993 if (inmenubar > 0)
7994 return 1;
7996 { /* This is a command. See if there is an equivalent key binding. */
7997 Lisp_Object keyeq = AREF (item_properties, ITEM_PROPERTY_KEYEQ);
7998 AUTO_STRING (space_space, " ");
8000 /* The previous code preferred :key-sequence to :keys, so we
8001 preserve this behavior. */
8002 if (STRINGP (keyeq) && !CONSP (keyhint))
8003 keyeq = concat2 (space_space, Fsubstitute_command_keys (keyeq));
8004 else
8006 Lisp_Object prefix = keyeq;
8007 Lisp_Object keys = Qnil;
8009 if (CONSP (prefix))
8011 def = XCAR (prefix);
8012 prefix = XCDR (prefix);
8014 else
8015 def = AREF (item_properties, ITEM_PROPERTY_DEF);
8017 if (CONSP (keyhint) && !NILP (XCAR (keyhint)))
8019 keys = XCAR (keyhint);
8020 tem = Fkey_binding (keys, Qnil, Qnil, Qnil);
8022 /* We have a suggested key. Is it bound to the command? */
8023 if (NILP (tem)
8024 || (!EQ (tem, def)
8025 /* If the command is an alias for another
8026 (such as lmenu.el set it up), check if the
8027 original command matches the cached command. */
8028 && !(SYMBOLP (def)
8029 && EQ (tem, XSYMBOL (def)->function))))
8030 keys = Qnil;
8033 if (NILP (keys))
8034 keys = Fwhere_is_internal (def, Qnil, Qt, Qnil, Qnil);
8036 if (!NILP (keys))
8038 tem = Fkey_description (keys, Qnil);
8039 if (CONSP (prefix))
8041 if (STRINGP (XCAR (prefix)))
8042 tem = concat2 (XCAR (prefix), tem);
8043 if (STRINGP (XCDR (prefix)))
8044 tem = concat2 (tem, XCDR (prefix));
8046 keyeq = concat2 (space_space, tem);
8048 else
8049 keyeq = Qnil;
8052 /* If we have an equivalent key binding, use that. */
8053 ASET (item_properties, ITEM_PROPERTY_KEYEQ, keyeq);
8056 /* Include this when menu help is implemented.
8057 tem = XVECTOR (item_properties)->contents[ITEM_PROPERTY_HELP];
8058 if (!(NILP (tem) || STRINGP (tem)))
8060 tem = menu_item_eval_property (tem);
8061 if (!STRINGP (tem))
8062 tem = Qnil;
8063 XVECTOR (item_properties)->contents[ITEM_PROPERTY_HELP] = tem;
8067 /* Handle radio buttons or toggle boxes. */
8068 tem = AREF (item_properties, ITEM_PROPERTY_SELECTED);
8069 if (!NILP (tem))
8070 ASET (item_properties, ITEM_PROPERTY_SELECTED,
8071 menu_item_eval_property (tem));
8073 return 1;
8078 /***********************************************************************
8079 Tool-bars
8080 ***********************************************************************/
8082 /* A vector holding tool bar items while they are parsed in function
8083 tool_bar_items. Each item occupies TOOL_BAR_ITEM_NSCLOTS elements
8084 in the vector. */
8086 static Lisp_Object tool_bar_items_vector;
8088 /* A vector holding the result of parse_tool_bar_item. Layout is like
8089 the one for a single item in tool_bar_items_vector. */
8091 static Lisp_Object tool_bar_item_properties;
8093 /* Next free index in tool_bar_items_vector. */
8095 static int ntool_bar_items;
8097 /* The symbols `:image' and `:rtl'. */
8099 static Lisp_Object QCimage;
8100 static Lisp_Object QCrtl;
8102 /* Function prototypes. */
8104 static void init_tool_bar_items (Lisp_Object);
8105 static void process_tool_bar_item (Lisp_Object, Lisp_Object, Lisp_Object,
8106 void *);
8107 static bool parse_tool_bar_item (Lisp_Object, Lisp_Object);
8108 static void append_tool_bar_item (void);
8111 /* Return a vector of tool bar items for keymaps currently in effect.
8112 Reuse vector REUSE if non-nil. Return in *NITEMS the number of
8113 tool bar items found. */
8115 Lisp_Object
8116 tool_bar_items (Lisp_Object reuse, int *nitems)
8118 Lisp_Object *maps;
8119 Lisp_Object mapsbuf[3];
8120 ptrdiff_t nmaps, i;
8121 Lisp_Object oquit;
8122 Lisp_Object *tmaps;
8123 USE_SAFE_ALLOCA;
8125 *nitems = 0;
8127 /* In order to build the menus, we need to call the keymap
8128 accessors. They all call QUIT. But this function is called
8129 during redisplay, during which a quit is fatal. So inhibit
8130 quitting while building the menus. We do this instead of
8131 specbind because (1) errors will clear it anyway and (2) this
8132 avoids risk of specpdl overflow. */
8133 oquit = Vinhibit_quit;
8134 Vinhibit_quit = Qt;
8136 /* Initialize tool_bar_items_vector and protect it from GC. */
8137 init_tool_bar_items (reuse);
8139 /* Build list of keymaps in maps. Set nmaps to the number of maps
8140 to process. */
8142 /* Should overriding-terminal-local-map and overriding-local-map apply? */
8143 if (!NILP (Voverriding_local_map_menu_flag)
8144 && !NILP (Voverriding_local_map))
8146 /* Yes, use them (if non-nil) as well as the global map. */
8147 maps = mapsbuf;
8148 nmaps = 0;
8149 if (!NILP (KVAR (current_kboard, Voverriding_terminal_local_map)))
8150 maps[nmaps++] = KVAR (current_kboard, Voverriding_terminal_local_map);
8151 if (!NILP (Voverriding_local_map))
8152 maps[nmaps++] = Voverriding_local_map;
8154 else
8156 /* No, so use major and minor mode keymaps and keymap property.
8157 Note that tool-bar bindings in the local-map and keymap
8158 properties may not work reliable, as they are only
8159 recognized when the tool-bar (or mode-line) is updated,
8160 which does not normally happen after every command. */
8161 Lisp_Object tem;
8162 ptrdiff_t nminor;
8163 nminor = current_minor_maps (NULL, &tmaps);
8164 SAFE_NALLOCA (maps, 1, nminor + 4);
8165 nmaps = 0;
8166 tem = KVAR (current_kboard, Voverriding_terminal_local_map);
8167 if (!NILP (tem) && !NILP (Voverriding_local_map_menu_flag))
8168 maps[nmaps++] = tem;
8169 if (tem = get_local_map (PT, current_buffer, Qkeymap), !NILP (tem))
8170 maps[nmaps++] = tem;
8171 memcpy (maps + nmaps, tmaps, nminor * sizeof (maps[0]));
8172 nmaps += nminor;
8173 maps[nmaps++] = get_local_map (PT, current_buffer, Qlocal_map);
8176 /* Add global keymap at the end. */
8177 maps[nmaps++] = current_global_map;
8179 /* Process maps in reverse order and look up in each map the prefix
8180 key `tool-bar'. */
8181 for (i = nmaps - 1; i >= 0; --i)
8182 if (!NILP (maps[i]))
8184 Lisp_Object keymap;
8186 keymap = get_keymap (access_keymap (maps[i], Qtool_bar, 1, 0, 1), 0, 1);
8187 if (CONSP (keymap))
8188 map_keymap (keymap, process_tool_bar_item, Qnil, NULL, 1);
8191 Vinhibit_quit = oquit;
8192 *nitems = ntool_bar_items / TOOL_BAR_ITEM_NSLOTS;
8193 SAFE_FREE ();
8194 return tool_bar_items_vector;
8198 /* Process the definition of KEY which is DEF. */
8200 static void
8201 process_tool_bar_item (Lisp_Object key, Lisp_Object def, Lisp_Object data, void *args)
8203 int i;
8204 struct gcpro gcpro1, gcpro2;
8206 /* Protect KEY and DEF from GC because parse_tool_bar_item may call
8207 eval. */
8208 GCPRO2 (key, def);
8210 if (EQ (def, Qundefined))
8212 /* If a map has an explicit `undefined' as definition,
8213 discard any previously made item. */
8214 for (i = 0; i < ntool_bar_items; i += TOOL_BAR_ITEM_NSLOTS)
8216 Lisp_Object *v = XVECTOR (tool_bar_items_vector)->contents + i;
8218 if (EQ (key, v[TOOL_BAR_ITEM_KEY]))
8220 if (ntool_bar_items > i + TOOL_BAR_ITEM_NSLOTS)
8221 memmove (v, v + TOOL_BAR_ITEM_NSLOTS,
8222 ((ntool_bar_items - i - TOOL_BAR_ITEM_NSLOTS)
8223 * word_size));
8224 ntool_bar_items -= TOOL_BAR_ITEM_NSLOTS;
8225 break;
8229 else if (parse_tool_bar_item (key, def))
8230 /* Append a new tool bar item to tool_bar_items_vector. Accept
8231 more than one definition for the same key. */
8232 append_tool_bar_item ();
8234 UNGCPRO;
8237 /* Access slot with index IDX of vector tool_bar_item_properties. */
8238 #define PROP(IDX) AREF (tool_bar_item_properties, (IDX))
8239 static void
8240 set_prop (ptrdiff_t idx, Lisp_Object val)
8242 ASET (tool_bar_item_properties, idx, val);
8246 /* Parse a tool bar item specification ITEM for key KEY and return the
8247 result in tool_bar_item_properties. Value is false if ITEM is
8248 invalid.
8250 ITEM is a list `(menu-item CAPTION BINDING PROPS...)'.
8252 CAPTION is the caption of the item, If it's not a string, it is
8253 evaluated to get a string.
8255 BINDING is the tool bar item's binding. Tool-bar items with keymaps
8256 as binding are currently ignored.
8258 The following properties are recognized:
8260 - `:enable FORM'.
8262 FORM is evaluated and specifies whether the tool bar item is
8263 enabled or disabled.
8265 - `:visible FORM'
8267 FORM is evaluated and specifies whether the tool bar item is visible.
8269 - `:filter FUNCTION'
8271 FUNCTION is invoked with one parameter `(quote BINDING)'. Its
8272 result is stored as the new binding.
8274 - `:button (TYPE SELECTED)'
8276 TYPE must be one of `:radio' or `:toggle'. SELECTED is evaluated
8277 and specifies whether the button is selected (pressed) or not.
8279 - `:image IMAGES'
8281 IMAGES is either a single image specification or a vector of four
8282 image specifications. See enum tool_bar_item_images.
8284 - `:help HELP-STRING'.
8286 Gives a help string to display for the tool bar item.
8288 - `:label LABEL-STRING'.
8290 A text label to show with the tool bar button if labels are enabled. */
8292 static bool
8293 parse_tool_bar_item (Lisp_Object key, Lisp_Object item)
8295 Lisp_Object filter = Qnil;
8296 Lisp_Object caption;
8297 int i;
8298 bool have_label = 0;
8300 /* Definition looks like `(menu-item CAPTION BINDING PROPS...)'.
8301 Rule out items that aren't lists, don't start with
8302 `menu-item' or whose rest following `tool-bar-item' is not a
8303 list. */
8304 if (!CONSP (item))
8305 return 0;
8307 /* As an exception, allow old-style menu separators. */
8308 if (STRINGP (XCAR (item)))
8309 item = list1 (XCAR (item));
8310 else if (!EQ (XCAR (item), Qmenu_item)
8311 || (item = XCDR (item), !CONSP (item)))
8312 return 0;
8314 /* Create tool_bar_item_properties vector if necessary. Reset it to
8315 defaults. */
8316 if (VECTORP (tool_bar_item_properties))
8318 for (i = 0; i < TOOL_BAR_ITEM_NSLOTS; ++i)
8319 set_prop (i, Qnil);
8321 else
8322 tool_bar_item_properties
8323 = Fmake_vector (make_number (TOOL_BAR_ITEM_NSLOTS), Qnil);
8325 /* Set defaults. */
8326 set_prop (TOOL_BAR_ITEM_KEY, key);
8327 set_prop (TOOL_BAR_ITEM_ENABLED_P, Qt);
8329 /* Get the caption of the item. If the caption is not a string,
8330 evaluate it to get a string. If we don't get a string, skip this
8331 item. */
8332 caption = XCAR (item);
8333 if (!STRINGP (caption))
8335 caption = menu_item_eval_property (caption);
8336 if (!STRINGP (caption))
8337 return 0;
8339 set_prop (TOOL_BAR_ITEM_CAPTION, caption);
8341 /* If the rest following the caption is not a list, the menu item is
8342 either a separator, or invalid. */
8343 item = XCDR (item);
8344 if (!CONSP (item))
8346 if (menu_separator_name_p (SSDATA (caption)))
8348 set_prop (TOOL_BAR_ITEM_TYPE, Qt);
8349 #if !defined (USE_GTK) && !defined (HAVE_NS)
8350 /* If we use build_desired_tool_bar_string to render the
8351 tool bar, the separator is rendered as an image. */
8352 set_prop (TOOL_BAR_ITEM_IMAGES,
8353 (menu_item_eval_property
8354 (Vtool_bar_separator_image_expression)));
8355 set_prop (TOOL_BAR_ITEM_ENABLED_P, Qnil);
8356 set_prop (TOOL_BAR_ITEM_SELECTED_P, Qnil);
8357 set_prop (TOOL_BAR_ITEM_CAPTION, Qnil);
8358 #endif
8359 return 1;
8361 return 0;
8364 /* Store the binding. */
8365 set_prop (TOOL_BAR_ITEM_BINDING, XCAR (item));
8366 item = XCDR (item);
8368 /* Ignore cached key binding, if any. */
8369 if (CONSP (item) && CONSP (XCAR (item)))
8370 item = XCDR (item);
8372 /* Process the rest of the properties. */
8373 for (; CONSP (item) && CONSP (XCDR (item)); item = XCDR (XCDR (item)))
8375 Lisp_Object ikey, value;
8377 ikey = XCAR (item);
8378 value = XCAR (XCDR (item));
8380 if (EQ (ikey, QCenable))
8382 /* `:enable FORM'. */
8383 if (!NILP (Venable_disabled_menus_and_buttons))
8384 set_prop (TOOL_BAR_ITEM_ENABLED_P, Qt);
8385 else
8386 set_prop (TOOL_BAR_ITEM_ENABLED_P, value);
8388 else if (EQ (ikey, QCvisible))
8390 /* `:visible FORM'. If got a visible property and that
8391 evaluates to nil then ignore this item. */
8392 if (NILP (menu_item_eval_property (value)))
8393 return 0;
8395 else if (EQ (ikey, QChelp))
8396 /* `:help HELP-STRING'. */
8397 set_prop (TOOL_BAR_ITEM_HELP, value);
8398 else if (EQ (ikey, QCvert_only))
8399 /* `:vert-only t/nil'. */
8400 set_prop (TOOL_BAR_ITEM_VERT_ONLY, value);
8401 else if (EQ (ikey, QClabel))
8403 const char *bad_label = "!!?GARBLED ITEM?!!";
8404 /* `:label LABEL-STRING'. */
8405 set_prop (TOOL_BAR_ITEM_LABEL,
8406 STRINGP (value) ? value : build_string (bad_label));
8407 have_label = 1;
8409 else if (EQ (ikey, QCfilter))
8410 /* ':filter FORM'. */
8411 filter = value;
8412 else if (EQ (ikey, QCbutton) && CONSP (value))
8414 /* `:button (TYPE . SELECTED)'. */
8415 Lisp_Object type, selected;
8417 type = XCAR (value);
8418 selected = XCDR (value);
8419 if (EQ (type, QCtoggle) || EQ (type, QCradio))
8421 set_prop (TOOL_BAR_ITEM_SELECTED_P, selected);
8422 set_prop (TOOL_BAR_ITEM_TYPE, type);
8425 else if (EQ (ikey, QCimage)
8426 && (CONSP (value)
8427 || (VECTORP (value) && ASIZE (value) == 4)))
8428 /* Value is either a single image specification or a vector
8429 of 4 such specifications for the different button states. */
8430 set_prop (TOOL_BAR_ITEM_IMAGES, value);
8431 else if (EQ (ikey, QCrtl))
8432 /* ':rtl STRING' */
8433 set_prop (TOOL_BAR_ITEM_RTL_IMAGE, value);
8437 if (!have_label)
8439 /* Try to make one from caption and key. */
8440 Lisp_Object tkey = PROP (TOOL_BAR_ITEM_KEY);
8441 Lisp_Object tcapt = PROP (TOOL_BAR_ITEM_CAPTION);
8442 const char *label = SYMBOLP (tkey) ? SSDATA (SYMBOL_NAME (tkey)) : "";
8443 const char *capt = STRINGP (tcapt) ? SSDATA (tcapt) : "";
8444 ptrdiff_t max_lbl =
8445 2 * max (0, min (tool_bar_max_label_size, STRING_BYTES_BOUND / 2));
8446 char *buf = xmalloc (max_lbl + 1);
8447 Lisp_Object new_lbl;
8448 ptrdiff_t caption_len = strlen (capt);
8450 if (caption_len <= max_lbl && capt[0] != '\0')
8452 strcpy (buf, capt);
8453 while (caption_len > 0 && buf[caption_len - 1] == '.')
8454 caption_len--;
8455 buf[caption_len] = '\0';
8456 label = capt = buf;
8459 if (strlen (label) <= max_lbl && label[0] != '\0')
8461 ptrdiff_t j;
8462 if (label != buf)
8463 strcpy (buf, label);
8465 for (j = 0; buf[j] != '\0'; ++j)
8466 if (buf[j] == '-')
8467 buf[j] = ' ';
8468 label = buf;
8470 else
8471 label = "";
8473 new_lbl = Fupcase_initials (build_string (label));
8474 if (SCHARS (new_lbl) <= tool_bar_max_label_size)
8475 set_prop (TOOL_BAR_ITEM_LABEL, new_lbl);
8476 else
8477 set_prop (TOOL_BAR_ITEM_LABEL, empty_unibyte_string);
8478 xfree (buf);
8481 /* If got a filter apply it on binding. */
8482 if (!NILP (filter))
8483 set_prop (TOOL_BAR_ITEM_BINDING,
8484 (menu_item_eval_property
8485 (list2 (filter,
8486 list2 (Qquote,
8487 PROP (TOOL_BAR_ITEM_BINDING))))));
8489 /* See if the binding is a keymap. Give up if it is. */
8490 if (CONSP (get_keymap (PROP (TOOL_BAR_ITEM_BINDING), 0, 1)))
8491 return 0;
8493 /* Enable or disable selection of item. */
8494 if (!EQ (PROP (TOOL_BAR_ITEM_ENABLED_P), Qt))
8495 set_prop (TOOL_BAR_ITEM_ENABLED_P,
8496 menu_item_eval_property (PROP (TOOL_BAR_ITEM_ENABLED_P)));
8498 /* Handle radio buttons or toggle boxes. */
8499 if (!NILP (PROP (TOOL_BAR_ITEM_SELECTED_P)))
8500 set_prop (TOOL_BAR_ITEM_SELECTED_P,
8501 menu_item_eval_property (PROP (TOOL_BAR_ITEM_SELECTED_P)));
8503 return 1;
8505 #undef PROP
8509 /* Initialize tool_bar_items_vector. REUSE, if non-nil, is a vector
8510 that can be reused. */
8512 static void
8513 init_tool_bar_items (Lisp_Object reuse)
8515 if (VECTORP (reuse))
8516 tool_bar_items_vector = reuse;
8517 else
8518 tool_bar_items_vector = Fmake_vector (make_number (64), Qnil);
8519 ntool_bar_items = 0;
8523 /* Append parsed tool bar item properties from
8524 tool_bar_item_properties */
8526 static void
8527 append_tool_bar_item (void)
8529 ptrdiff_t incr
8530 = (ntool_bar_items
8531 - (ASIZE (tool_bar_items_vector) - TOOL_BAR_ITEM_NSLOTS));
8533 /* Enlarge tool_bar_items_vector if necessary. */
8534 if (incr > 0)
8535 tool_bar_items_vector = larger_vector (tool_bar_items_vector, incr, -1);
8537 /* Append entries from tool_bar_item_properties to the end of
8538 tool_bar_items_vector. */
8539 vcopy (tool_bar_items_vector, ntool_bar_items,
8540 XVECTOR (tool_bar_item_properties)->contents, TOOL_BAR_ITEM_NSLOTS);
8541 ntool_bar_items += TOOL_BAR_ITEM_NSLOTS;
8548 /* Read a character using menus based on the keymap MAP.
8549 Return nil if there are no menus in the maps.
8550 Return t if we displayed a menu but the user rejected it.
8552 PREV_EVENT is the previous input event, or nil if we are reading
8553 the first event of a key sequence.
8555 If USED_MOUSE_MENU is non-null, set *USED_MOUSE_MENU to true
8556 if we used a mouse menu to read the input, or false otherwise. If
8557 USED_MOUSE_MENU is null, don't dereference it.
8559 The prompting is done based on the prompt-string of the map
8560 and the strings associated with various map elements.
8562 This can be done with X menus or with menus put in the minibuf.
8563 These are done in different ways, depending on how the input will be read.
8564 Menus using X are done after auto-saving in read-char, getting the input
8565 event from Fx_popup_menu; menus using the minibuf use read_char recursively
8566 and do auto-saving in the inner call of read_char. */
8568 static Lisp_Object
8569 read_char_x_menu_prompt (Lisp_Object map,
8570 Lisp_Object prev_event, bool *used_mouse_menu)
8572 if (used_mouse_menu)
8573 *used_mouse_menu = 0;
8575 /* Use local over global Menu maps. */
8577 if (! menu_prompting)
8578 return Qnil;
8580 /* If we got to this point via a mouse click,
8581 use a real menu for mouse selection. */
8582 if (EVENT_HAS_PARAMETERS (prev_event)
8583 && !EQ (XCAR (prev_event), Qmenu_bar)
8584 && !EQ (XCAR (prev_event), Qtool_bar))
8586 /* Display the menu and get the selection. */
8587 Lisp_Object value;
8589 value = Fx_popup_menu (prev_event, get_keymap (map, 0, 1));
8590 if (CONSP (value))
8592 Lisp_Object tem;
8594 record_menu_key (XCAR (value));
8596 /* If we got multiple events, unread all but
8597 the first.
8598 There is no way to prevent those unread events
8599 from showing up later in last_nonmenu_event.
8600 So turn symbol and integer events into lists,
8601 to indicate that they came from a mouse menu,
8602 so that when present in last_nonmenu_event
8603 they won't confuse things. */
8604 for (tem = XCDR (value); CONSP (tem); tem = XCDR (tem))
8606 record_menu_key (XCAR (tem));
8607 if (SYMBOLP (XCAR (tem))
8608 || INTEGERP (XCAR (tem)))
8609 XSETCAR (tem, Fcons (XCAR (tem), Qdisabled));
8612 /* If we got more than one event, put all but the first
8613 onto this list to be read later.
8614 Return just the first event now. */
8615 Vunread_command_events
8616 = nconc2 (XCDR (value), Vunread_command_events);
8617 value = XCAR (value);
8619 else if (NILP (value))
8620 value = Qt;
8621 if (used_mouse_menu)
8622 *used_mouse_menu = 1;
8623 return value;
8625 return Qnil ;
8628 static Lisp_Object
8629 read_char_minibuf_menu_prompt (int commandflag,
8630 Lisp_Object map)
8632 Lisp_Object name;
8633 ptrdiff_t nlength;
8634 /* FIXME: Use the minibuffer's frame width. */
8635 ptrdiff_t width = FRAME_COLS (SELECTED_FRAME ()) - 4;
8636 ptrdiff_t idx = -1;
8637 bool nobindings = 1;
8638 Lisp_Object rest, vector;
8639 Lisp_Object prompt_strings = Qnil;
8641 vector = Qnil;
8643 if (! menu_prompting)
8644 return Qnil;
8646 map = get_keymap (map, 0, 1);
8647 name = Fkeymap_prompt (map);
8649 /* If we don't have any menus, just read a character normally. */
8650 if (!STRINGP (name))
8651 return Qnil;
8653 #define PUSH_C_STR(str, listvar) \
8654 listvar = Fcons (build_unibyte_string (str), listvar)
8656 /* Prompt string always starts with map's prompt, and a space. */
8657 prompt_strings = Fcons (name, prompt_strings);
8658 PUSH_C_STR (": ", prompt_strings);
8659 nlength = SCHARS (name) + 2;
8661 rest = map;
8663 /* Present the documented bindings, a line at a time. */
8664 while (1)
8666 bool notfirst = 0;
8667 Lisp_Object menu_strings = prompt_strings;
8668 ptrdiff_t i = nlength;
8669 Lisp_Object obj;
8670 Lisp_Object orig_defn_macro;
8672 /* Loop over elements of map. */
8673 while (i < width)
8675 Lisp_Object elt;
8677 /* FIXME: Use map_keymap to handle new keymap formats. */
8679 /* At end of map, wrap around if just starting,
8680 or end this line if already have something on it. */
8681 if (NILP (rest))
8683 if (notfirst || nobindings)
8684 break;
8685 else
8686 rest = map;
8689 /* Look at the next element of the map. */
8690 if (idx >= 0)
8691 elt = AREF (vector, idx);
8692 else
8693 elt = Fcar_safe (rest);
8695 if (idx < 0 && VECTORP (elt))
8697 /* If we found a dense table in the keymap,
8698 advanced past it, but start scanning its contents. */
8699 rest = Fcdr_safe (rest);
8700 vector = elt;
8701 idx = 0;
8703 else
8705 /* An ordinary element. */
8706 Lisp_Object event, tem;
8708 if (idx < 0)
8710 event = Fcar_safe (elt); /* alist */
8711 elt = Fcdr_safe (elt);
8713 else
8715 XSETINT (event, idx); /* vector */
8718 /* Ignore the element if it has no prompt string. */
8719 if (INTEGERP (event) && parse_menu_item (elt, -1))
8721 /* True if the char to type matches the string. */
8722 bool char_matches;
8723 Lisp_Object upcased_event, downcased_event;
8724 Lisp_Object desc = Qnil;
8725 Lisp_Object s
8726 = AREF (item_properties, ITEM_PROPERTY_NAME);
8728 upcased_event = Fupcase (event);
8729 downcased_event = Fdowncase (event);
8730 char_matches = (XINT (upcased_event) == SREF (s, 0)
8731 || XINT (downcased_event) == SREF (s, 0));
8732 if (! char_matches)
8733 desc = Fsingle_key_description (event, Qnil);
8735 #if 0 /* It is redundant to list the equivalent key bindings because
8736 the prefix is what the user has already typed. */
8738 = XVECTOR (item_properties)->contents[ITEM_PROPERTY_KEYEQ];
8739 if (!NILP (tem))
8740 /* Insert equivalent keybinding. */
8741 s = concat2 (s, tem);
8742 #endif
8744 = AREF (item_properties, ITEM_PROPERTY_TYPE);
8745 if (EQ (tem, QCradio) || EQ (tem, QCtoggle))
8747 /* Insert button prefix. */
8748 Lisp_Object selected
8749 = AREF (item_properties, ITEM_PROPERTY_SELECTED);
8750 AUTO_STRING (radio_yes, "(*) ");
8751 AUTO_STRING (radio_no , "( ) ");
8752 AUTO_STRING (check_yes, "[X] ");
8753 AUTO_STRING (check_no , "[ ] ");
8754 if (EQ (tem, QCradio))
8755 tem = NILP (selected) ? radio_yes : radio_no;
8756 else
8757 tem = NILP (selected) ? check_yes : check_no;
8758 s = concat2 (tem, s);
8762 /* If we have room for the prompt string, add it to this line.
8763 If this is the first on the line, always add it. */
8764 if ((SCHARS (s) + i + 2
8765 + (char_matches ? 0 : SCHARS (desc) + 3))
8766 < width
8767 || !notfirst)
8769 ptrdiff_t thiswidth;
8771 /* Punctuate between strings. */
8772 if (notfirst)
8774 PUSH_C_STR (", ", menu_strings);
8775 i += 2;
8777 notfirst = 1;
8778 nobindings = 0;
8780 /* If the char to type doesn't match the string's
8781 first char, explicitly show what char to type. */
8782 if (! char_matches)
8784 /* Add as much of string as fits. */
8785 thiswidth = min (SCHARS (desc), width - i);
8786 menu_strings
8787 = Fcons (Fsubstring (desc, make_number (0),
8788 make_number (thiswidth)),
8789 menu_strings);
8790 i += thiswidth;
8791 PUSH_C_STR (" = ", menu_strings);
8792 i += 3;
8795 /* Add as much of string as fits. */
8796 thiswidth = min (SCHARS (s), width - i);
8797 menu_strings
8798 = Fcons (Fsubstring (s, make_number (0),
8799 make_number (thiswidth)),
8800 menu_strings);
8801 i += thiswidth;
8803 else
8805 /* If this element does not fit, end the line now,
8806 and save the element for the next line. */
8807 PUSH_C_STR ("...", menu_strings);
8808 break;
8812 /* Move past this element. */
8813 if (idx >= 0 && idx + 1 >= ASIZE (vector))
8814 /* Handle reaching end of dense table. */
8815 idx = -1;
8816 if (idx >= 0)
8817 idx++;
8818 else
8819 rest = Fcdr_safe (rest);
8823 /* Prompt with that and read response. */
8824 message3_nolog (apply1 (intern ("concat"), Fnreverse (menu_strings)));
8826 /* Make believe it's not a keyboard macro in case the help char
8827 is pressed. Help characters are not recorded because menu prompting
8828 is not used on replay. */
8829 orig_defn_macro = KVAR (current_kboard, defining_kbd_macro);
8830 kset_defining_kbd_macro (current_kboard, Qnil);
8832 obj = read_char (commandflag, Qnil, Qt, 0, NULL);
8833 while (BUFFERP (obj));
8834 kset_defining_kbd_macro (current_kboard, orig_defn_macro);
8836 if (!INTEGERP (obj) || XINT (obj) == -2)
8837 return obj;
8839 if (! EQ (obj, menu_prompt_more_char)
8840 && (!INTEGERP (menu_prompt_more_char)
8841 || ! EQ (obj, make_number (Ctl (XINT (menu_prompt_more_char))))))
8843 if (!NILP (KVAR (current_kboard, defining_kbd_macro)))
8844 store_kbd_macro_char (obj);
8845 return obj;
8847 /* Help char - go round again. */
8851 /* Reading key sequences. */
8853 static Lisp_Object
8854 follow_key (Lisp_Object keymap, Lisp_Object key)
8856 return access_keymap (get_keymap (keymap, 0, 1),
8857 key, 1, 0, 1);
8860 static Lisp_Object
8861 active_maps (Lisp_Object first_event)
8863 Lisp_Object position
8864 = CONSP (first_event) ? CAR_SAFE (XCDR (first_event)) : Qnil;
8865 return Fcons (Qkeymap, Fcurrent_active_maps (Qt, position));
8868 /* Structure used to keep track of partial application of key remapping
8869 such as Vfunction_key_map and Vkey_translation_map. */
8870 typedef struct keyremap
8872 /* This is the map originally specified for this use. */
8873 Lisp_Object parent;
8874 /* This is a submap reached by looking up, in PARENT,
8875 the events from START to END. */
8876 Lisp_Object map;
8877 /* Positions [START, END) in the key sequence buffer
8878 are the key that we have scanned so far.
8879 Those events are the ones that we will replace
8880 if PARENT maps them into a key sequence. */
8881 int start, end;
8882 } keyremap;
8884 /* Lookup KEY in MAP.
8885 MAP is a keymap mapping keys to key vectors or functions.
8886 If the mapping is a function and DO_FUNCALL is true,
8887 the function is called with PROMPT as parameter and its return
8888 value is used as the return value of this function (after checking
8889 that it is indeed a vector). */
8891 static Lisp_Object
8892 access_keymap_keyremap (Lisp_Object map, Lisp_Object key, Lisp_Object prompt,
8893 bool do_funcall)
8895 Lisp_Object next;
8897 next = access_keymap (map, key, 1, 0, 1);
8899 /* Handle a symbol whose function definition is a keymap
8900 or an array. */
8901 if (SYMBOLP (next) && !NILP (Ffboundp (next))
8902 && (ARRAYP (XSYMBOL (next)->function)
8903 || KEYMAPP (XSYMBOL (next)->function)))
8904 next = Fautoload_do_load (XSYMBOL (next)->function, next, Qnil);
8906 /* If the keymap gives a function, not an
8907 array, then call the function with one arg and use
8908 its value instead. */
8909 if (do_funcall && FUNCTIONP (next))
8911 Lisp_Object tem;
8912 tem = next;
8914 next = call1 (next, prompt);
8915 /* If the function returned something invalid,
8916 barf--don't ignore it.
8917 (To ignore it safely, we would need to gcpro a bunch of
8918 other variables.) */
8919 if (! (NILP (next) || VECTORP (next) || STRINGP (next)))
8920 error ("Function %s returns invalid key sequence",
8921 SSDATA (SYMBOL_NAME (tem)));
8923 return next;
8926 /* Do one step of the key remapping used for function-key-map and
8927 key-translation-map:
8928 KEYBUF is the buffer holding the input events.
8929 BUFSIZE is its maximum size.
8930 FKEY is a pointer to the keyremap structure to use.
8931 INPUT is the index of the last element in KEYBUF.
8932 DOIT if true says that the remapping can actually take place.
8933 DIFF is used to return the number of keys added/removed by the remapping.
8934 PARENT is the root of the keymap.
8935 PROMPT is the prompt to use if the remapping happens through a function.
8936 Return true if the remapping actually took place. */
8938 static bool
8939 keyremap_step (Lisp_Object *keybuf, int bufsize, volatile keyremap *fkey,
8940 int input, bool doit, int *diff, Lisp_Object prompt)
8942 Lisp_Object next, key;
8944 key = keybuf[fkey->end++];
8946 if (KEYMAPP (fkey->parent))
8947 next = access_keymap_keyremap (fkey->map, key, prompt, doit);
8948 else
8949 next = Qnil;
8951 /* If keybuf[fkey->start..fkey->end] is bound in the
8952 map and we're in a position to do the key remapping, replace it with
8953 the binding and restart with fkey->start at the end. */
8954 if ((VECTORP (next) || STRINGP (next)) && doit)
8956 int len = XFASTINT (Flength (next));
8957 int i;
8959 *diff = len - (fkey->end - fkey->start);
8961 if (bufsize - input <= *diff)
8962 error ("Key sequence too long");
8964 /* Shift the keys that follow fkey->end. */
8965 if (*diff < 0)
8966 for (i = fkey->end; i < input; i++)
8967 keybuf[i + *diff] = keybuf[i];
8968 else if (*diff > 0)
8969 for (i = input - 1; i >= fkey->end; i--)
8970 keybuf[i + *diff] = keybuf[i];
8971 /* Overwrite the old keys with the new ones. */
8972 for (i = 0; i < len; i++)
8973 keybuf[fkey->start + i]
8974 = Faref (next, make_number (i));
8976 fkey->start = fkey->end += *diff;
8977 fkey->map = fkey->parent;
8979 return 1;
8982 fkey->map = get_keymap (next, 0, 1);
8984 /* If we no longer have a bound suffix, try a new position for
8985 fkey->start. */
8986 if (!CONSP (fkey->map))
8988 fkey->end = ++fkey->start;
8989 fkey->map = fkey->parent;
8991 return 0;
8994 static bool
8995 test_undefined (Lisp_Object binding)
8997 return (NILP (binding)
8998 || EQ (binding, Qundefined)
8999 || (SYMBOLP (binding)
9000 && EQ (Fcommand_remapping (binding, Qnil, Qnil), Qundefined)));
9003 /* Read a sequence of keys that ends with a non prefix character,
9004 storing it in KEYBUF, a buffer of size BUFSIZE.
9005 Prompt with PROMPT.
9006 Return the length of the key sequence stored.
9007 Return -1 if the user rejected a command menu.
9009 Echo starting immediately unless `prompt' is 0.
9011 If PREVENT_REDISPLAY is non-zero, avoid redisplay by calling
9012 read_char with a suitable COMMANDFLAG argument.
9014 Where a key sequence ends depends on the currently active keymaps.
9015 These include any minor mode keymaps active in the current buffer,
9016 the current buffer's local map, and the global map.
9018 If a key sequence has no other bindings, we check Vfunction_key_map
9019 to see if some trailing subsequence might be the beginning of a
9020 function key's sequence. If so, we try to read the whole function
9021 key, and substitute its symbolic name into the key sequence.
9023 We ignore unbound `down-' mouse clicks. We turn unbound `drag-' and
9024 `double-' events into similar click events, if that would make them
9025 bound. We try to turn `triple-' events first into `double-' events,
9026 then into clicks.
9028 If we get a mouse click in a mode line, vertical divider, or other
9029 non-text area, we treat the click as if it were prefixed by the
9030 symbol denoting that area - `mode-line', `vertical-line', or
9031 whatever.
9033 If the sequence starts with a mouse click, we read the key sequence
9034 with respect to the buffer clicked on, not the current buffer.
9036 If the user switches frames in the midst of a key sequence, we put
9037 off the switch-frame event until later; the next call to
9038 read_char will return it.
9040 If FIX_CURRENT_BUFFER, we restore current_buffer
9041 from the selected window's buffer. */
9043 static int
9044 read_key_sequence (Lisp_Object *keybuf, int bufsize, Lisp_Object prompt,
9045 bool dont_downcase_last, bool can_return_switch_frame,
9046 bool fix_current_buffer, bool prevent_redisplay)
9048 ptrdiff_t count = SPECPDL_INDEX ();
9050 /* How many keys there are in the current key sequence. */
9051 int t;
9053 /* The length of the echo buffer when we started reading, and
9054 the length of this_command_keys when we started reading. */
9055 ptrdiff_t echo_start IF_LINT (= 0);
9056 ptrdiff_t keys_start;
9058 Lisp_Object current_binding = Qnil;
9059 Lisp_Object first_event = Qnil;
9061 /* Index of the first key that has no binding.
9062 It is useless to try fkey.start larger than that. */
9063 int first_unbound;
9065 /* If t < mock_input, then KEYBUF[t] should be read as the next
9066 input key.
9068 We use this to recover after recognizing a function key. Once we
9069 realize that a suffix of the current key sequence is actually a
9070 function key's escape sequence, we replace the suffix with the
9071 function key's binding from Vfunction_key_map. Now keybuf
9072 contains a new and different key sequence, so the echo area,
9073 this_command_keys, and the submaps and defs arrays are wrong. In
9074 this situation, we set mock_input to t, set t to 0, and jump to
9075 restart_sequence; the loop will read keys from keybuf up until
9076 mock_input, thus rebuilding the state; and then it will resume
9077 reading characters from the keyboard. */
9078 int mock_input = 0;
9080 /* If the sequence is unbound in submaps[], then
9081 keybuf[fkey.start..fkey.end-1] is a prefix in Vfunction_key_map,
9082 and fkey.map is its binding.
9084 These might be > t, indicating that all function key scanning
9085 should hold off until t reaches them. We do this when we've just
9086 recognized a function key, to avoid searching for the function
9087 key's again in Vfunction_key_map. */
9088 keyremap fkey;
9090 /* Likewise, for key_translation_map and input-decode-map. */
9091 keyremap keytran, indec;
9093 /* True if we are trying to map a key by changing an upper-case
9094 letter to lower case, or a shifted function key to an unshifted
9095 one. */
9096 bool shift_translated = 0;
9098 /* If we receive a `switch-frame' or `select-window' event in the middle of
9099 a key sequence, we put it off for later.
9100 While we're reading, we keep the event here. */
9101 Lisp_Object delayed_switch_frame;
9103 Lisp_Object original_uppercase IF_LINT (= Qnil);
9104 int original_uppercase_position = -1;
9106 /* Gets around Microsoft compiler limitations. */
9107 bool dummyflag = 0;
9109 struct buffer *starting_buffer;
9111 /* List of events for which a fake prefix key has been generated. */
9112 Lisp_Object fake_prefixed_keys = Qnil;
9114 struct gcpro gcpro1;
9116 GCPRO1 (fake_prefixed_keys);
9117 raw_keybuf_count = 0;
9119 last_nonmenu_event = Qnil;
9121 delayed_switch_frame = Qnil;
9123 if (INTERACTIVE)
9125 if (!NILP (prompt))
9127 /* Install the string PROMPT as the beginning of the string
9128 of echoing, so that it serves as a prompt for the next
9129 character. */
9130 kset_echo_string (current_kboard, prompt);
9131 current_kboard->echo_after_prompt = SCHARS (prompt);
9132 echo_now ();
9134 else if (cursor_in_echo_area
9135 && echo_keystrokes_p ())
9136 /* This doesn't put in a dash if the echo buffer is empty, so
9137 you don't always see a dash hanging out in the minibuffer. */
9138 echo_dash ();
9141 /* Record the initial state of the echo area and this_command_keys;
9142 we will need to restore them if we replay a key sequence. */
9143 if (INTERACTIVE)
9144 echo_start = echo_length ();
9145 keys_start = this_command_key_count;
9146 this_single_command_key_start = keys_start;
9148 /* We jump here when we need to reinitialize fkey and keytran; this
9149 happens if we switch keyboards between rescans. */
9150 replay_entire_sequence:
9152 indec.map = indec.parent = KVAR (current_kboard, Vinput_decode_map);
9153 fkey.map = fkey.parent = KVAR (current_kboard, Vlocal_function_key_map);
9154 keytran.map = keytran.parent = Vkey_translation_map;
9155 indec.start = indec.end = 0;
9156 fkey.start = fkey.end = 0;
9157 keytran.start = keytran.end = 0;
9159 /* We jump here when the key sequence has been thoroughly changed, and
9160 we need to rescan it starting from the beginning. When we jump here,
9161 keybuf[0..mock_input] holds the sequence we should reread. */
9162 replay_sequence:
9164 starting_buffer = current_buffer;
9165 first_unbound = bufsize + 1;
9167 /* Build our list of keymaps.
9168 If we recognize a function key and replace its escape sequence in
9169 keybuf with its symbol, or if the sequence starts with a mouse
9170 click and we need to switch buffers, we jump back here to rebuild
9171 the initial keymaps from the current buffer. */
9172 current_binding = active_maps (first_event);
9174 /* Start from the beginning in keybuf. */
9175 t = 0;
9177 /* These are no-ops the first time through, but if we restart, they
9178 revert the echo area and this_command_keys to their original state. */
9179 this_command_key_count = keys_start;
9180 if (INTERACTIVE && t < mock_input)
9181 echo_truncate (echo_start);
9183 /* If the best binding for the current key sequence is a keymap, or
9184 we may be looking at a function key's escape sequence, keep on
9185 reading. */
9186 while (!NILP (current_binding)
9187 /* Keep reading as long as there's a prefix binding. */
9188 ? KEYMAPP (current_binding)
9189 /* Don't return in the middle of a possible function key sequence,
9190 if the only bindings we found were via case conversion.
9191 Thus, if ESC O a has a function-key-map translation
9192 and ESC o has a binding, don't return after ESC O,
9193 so that we can translate ESC O plus the next character. */
9194 : (/* indec.start < t || fkey.start < t || */ keytran.start < t))
9196 Lisp_Object key;
9197 bool used_mouse_menu = 0;
9199 /* Where the last real key started. If we need to throw away a
9200 key that has expanded into more than one element of keybuf
9201 (say, a mouse click on the mode line which is being treated
9202 as [mode-line (mouse-...)], then we backtrack to this point
9203 of keybuf. */
9204 int last_real_key_start;
9206 /* These variables are analogous to echo_start and keys_start;
9207 while those allow us to restart the entire key sequence,
9208 echo_local_start and keys_local_start allow us to throw away
9209 just one key. */
9210 ptrdiff_t echo_local_start IF_LINT (= 0);
9211 int keys_local_start;
9212 Lisp_Object new_binding;
9214 eassert (indec.end == t || (indec.end > t && indec.end <= mock_input));
9215 eassert (indec.start <= indec.end);
9216 eassert (fkey.start <= fkey.end);
9217 eassert (keytran.start <= keytran.end);
9218 /* key-translation-map is applied *after* function-key-map
9219 which is itself applied *after* input-decode-map. */
9220 eassert (fkey.end <= indec.start);
9221 eassert (keytran.end <= fkey.start);
9223 if (/* first_unbound < indec.start && first_unbound < fkey.start && */
9224 first_unbound < keytran.start)
9225 { /* The prefix upto first_unbound has no binding and has
9226 no translation left to do either, so we know it's unbound.
9227 If we don't stop now, we risk staying here indefinitely
9228 (if the user keeps entering fkey or keytran prefixes
9229 like C-c ESC ESC ESC ESC ...) */
9230 int i;
9231 for (i = first_unbound + 1; i < t; i++)
9232 keybuf[i - first_unbound - 1] = keybuf[i];
9233 mock_input = t - first_unbound - 1;
9234 indec.end = indec.start -= first_unbound + 1;
9235 indec.map = indec.parent;
9236 fkey.end = fkey.start -= first_unbound + 1;
9237 fkey.map = fkey.parent;
9238 keytran.end = keytran.start -= first_unbound + 1;
9239 keytran.map = keytran.parent;
9240 goto replay_sequence;
9243 if (t >= bufsize)
9244 error ("Key sequence too long");
9246 if (INTERACTIVE)
9247 echo_local_start = echo_length ();
9248 keys_local_start = this_command_key_count;
9250 replay_key:
9251 /* These are no-ops, unless we throw away a keystroke below and
9252 jumped back up to replay_key; in that case, these restore the
9253 variables to their original state, allowing us to replay the
9254 loop. */
9255 if (INTERACTIVE && t < mock_input)
9256 echo_truncate (echo_local_start);
9257 this_command_key_count = keys_local_start;
9259 /* By default, assume each event is "real". */
9260 last_real_key_start = t;
9262 /* Does mock_input indicate that we are re-reading a key sequence? */
9263 if (t < mock_input)
9265 key = keybuf[t];
9266 add_command_key (key);
9267 if (echo_keystrokes_p ()
9268 && current_kboard->immediate_echo)
9270 echo_add_key (key);
9271 echo_dash ();
9275 /* If not, we should actually read a character. */
9276 else
9279 KBOARD *interrupted_kboard = current_kboard;
9280 struct frame *interrupted_frame = SELECTED_FRAME ();
9281 /* Calling read_char with COMMANDFLAG = -2 avoids
9282 redisplay in read_char and its subroutines. */
9283 key = read_char (prevent_redisplay ? -2 : NILP (prompt),
9284 current_binding, last_nonmenu_event,
9285 &used_mouse_menu, NULL);
9286 if ((INTEGERP (key) && XINT (key) == -2) /* wrong_kboard_jmpbuf */
9287 /* When switching to a new tty (with a new keyboard),
9288 read_char returns the new buffer, rather than -2
9289 (Bug#5095). This is because `terminal-init-xterm'
9290 calls read-char, which eats the wrong_kboard_jmpbuf
9291 return. Any better way to fix this? -- cyd */
9292 || (interrupted_kboard != current_kboard))
9294 bool found = 0;
9295 struct kboard *k;
9297 for (k = all_kboards; k; k = k->next_kboard)
9298 if (k == interrupted_kboard)
9299 found = 1;
9301 if (!found)
9303 /* Don't touch interrupted_kboard when it's been
9304 deleted. */
9305 delayed_switch_frame = Qnil;
9306 goto replay_entire_sequence;
9309 if (!NILP (delayed_switch_frame))
9311 kset_kbd_queue
9312 (interrupted_kboard,
9313 Fcons (delayed_switch_frame,
9314 KVAR (interrupted_kboard, kbd_queue)));
9315 delayed_switch_frame = Qnil;
9318 while (t > 0)
9319 kset_kbd_queue
9320 (interrupted_kboard,
9321 Fcons (keybuf[--t], KVAR (interrupted_kboard, kbd_queue)));
9323 /* If the side queue is non-empty, ensure it begins with a
9324 switch-frame, so we'll replay it in the right context. */
9325 if (CONSP (KVAR (interrupted_kboard, kbd_queue))
9326 && (key = XCAR (KVAR (interrupted_kboard, kbd_queue)),
9327 !(EVENT_HAS_PARAMETERS (key)
9328 && EQ (EVENT_HEAD_KIND (EVENT_HEAD (key)),
9329 Qswitch_frame))))
9331 Lisp_Object frame;
9332 XSETFRAME (frame, interrupted_frame);
9333 kset_kbd_queue
9334 (interrupted_kboard,
9335 Fcons (make_lispy_switch_frame (frame),
9336 KVAR (interrupted_kboard, kbd_queue)));
9338 mock_input = 0;
9339 goto replay_entire_sequence;
9343 /* read_char returns t when it shows a menu and the user rejects it.
9344 Just return -1. */
9345 if (EQ (key, Qt))
9347 unbind_to (count, Qnil);
9348 UNGCPRO;
9349 return -1;
9352 /* read_char returns -1 at the end of a macro.
9353 Emacs 18 handles this by returning immediately with a
9354 zero, so that's what we'll do. */
9355 if (INTEGERP (key) && XINT (key) == -1)
9357 t = 0;
9358 /* The Microsoft C compiler can't handle the goto that
9359 would go here. */
9360 dummyflag = 1;
9361 break;
9364 /* If the current buffer has been changed from under us, the
9365 keymap may have changed, so replay the sequence. */
9366 if (BUFFERP (key))
9368 timer_resume_idle ();
9370 mock_input = t;
9371 /* Reset the current buffer from the selected window
9372 in case something changed the former and not the latter.
9373 This is to be more consistent with the behavior
9374 of the command_loop_1. */
9375 if (fix_current_buffer)
9377 if (! FRAME_LIVE_P (XFRAME (selected_frame)))
9378 Fkill_emacs (Qnil);
9379 if (XBUFFER (XWINDOW (selected_window)->contents)
9380 != current_buffer)
9381 Fset_buffer (XWINDOW (selected_window)->contents);
9384 goto replay_sequence;
9387 /* If we have a quit that was typed in another frame, and
9388 quit_throw_to_read_char switched buffers,
9389 replay to get the right keymap. */
9390 if (INTEGERP (key)
9391 && XINT (key) == quit_char
9392 && current_buffer != starting_buffer)
9394 GROW_RAW_KEYBUF;
9395 ASET (raw_keybuf, raw_keybuf_count, key);
9396 raw_keybuf_count++;
9397 keybuf[t++] = key;
9398 mock_input = t;
9399 Vquit_flag = Qnil;
9400 goto replay_sequence;
9403 Vquit_flag = Qnil;
9405 if (EVENT_HAS_PARAMETERS (key)
9406 /* Either a `switch-frame' or a `select-window' event. */
9407 && EQ (EVENT_HEAD_KIND (EVENT_HEAD (key)), Qswitch_frame))
9409 /* If we're at the beginning of a key sequence, and the caller
9410 says it's okay, go ahead and return this event. If we're
9411 in the midst of a key sequence, delay it until the end. */
9412 if (t > 0 || !can_return_switch_frame)
9414 delayed_switch_frame = key;
9415 goto replay_key;
9419 if (NILP (first_event))
9421 first_event = key;
9422 /* Even if first_event does not specify a particular
9423 window/position, it's important to recompute the maps here
9424 since a long time might have passed since we entered
9425 read_key_sequence, and a timer (or process-filter or
9426 special-event-map, ...) might have switched the current buffer
9427 or the selected window from under us in the mean time. */
9428 if (fix_current_buffer
9429 && (XBUFFER (XWINDOW (selected_window)->contents)
9430 != current_buffer))
9431 Fset_buffer (XWINDOW (selected_window)->contents);
9432 current_binding = active_maps (first_event);
9435 GROW_RAW_KEYBUF;
9436 ASET (raw_keybuf, raw_keybuf_count, key);
9437 raw_keybuf_count++;
9440 /* Clicks in non-text areas get prefixed by the symbol
9441 in their CHAR-ADDRESS field. For example, a click on
9442 the mode line is prefixed by the symbol `mode-line'.
9444 Furthermore, key sequences beginning with mouse clicks
9445 are read using the keymaps of the buffer clicked on, not
9446 the current buffer. So we may have to switch the buffer
9447 here.
9449 When we turn one event into two events, we must make sure
9450 that neither of the two looks like the original--so that,
9451 if we replay the events, they won't be expanded again.
9452 If not for this, such reexpansion could happen either here
9453 or when user programs play with this-command-keys. */
9454 if (EVENT_HAS_PARAMETERS (key))
9456 Lisp_Object kind = EVENT_HEAD_KIND (EVENT_HEAD (key));
9457 if (EQ (kind, Qmouse_click))
9459 Lisp_Object window = POSN_WINDOW (EVENT_START (key));
9460 Lisp_Object posn = POSN_POSN (EVENT_START (key));
9462 if (CONSP (posn)
9463 || (!NILP (fake_prefixed_keys)
9464 && !NILP (Fmemq (key, fake_prefixed_keys))))
9466 /* We're looking a second time at an event for which
9467 we generated a fake prefix key. Set
9468 last_real_key_start appropriately. */
9469 if (t > 0)
9470 last_real_key_start = t - 1;
9473 if (last_real_key_start == 0)
9475 /* Key sequences beginning with mouse clicks are
9476 read using the keymaps in the buffer clicked on,
9477 not the current buffer. If we're at the
9478 beginning of a key sequence, switch buffers. */
9479 if (WINDOWP (window)
9480 && BUFFERP (XWINDOW (window)->contents)
9481 && XBUFFER (XWINDOW (window)->contents) != current_buffer)
9483 ASET (raw_keybuf, raw_keybuf_count, key);
9484 raw_keybuf_count++;
9485 keybuf[t] = key;
9486 mock_input = t + 1;
9488 /* Arrange to go back to the original buffer once we're
9489 done reading the key sequence. Note that we can't
9490 use save_excursion_{save,restore} here, because they
9491 save point as well as the current buffer; we don't
9492 want to save point, because redisplay may change it,
9493 to accommodate a Fset_window_start or something. We
9494 don't want to do this at the top of the function,
9495 because we may get input from a subprocess which
9496 wants to change the selected window and stuff (say,
9497 emacsclient). */
9498 record_unwind_current_buffer ();
9500 if (! FRAME_LIVE_P (XFRAME (selected_frame)))
9501 Fkill_emacs (Qnil);
9502 set_buffer_internal (XBUFFER (XWINDOW (window)->contents));
9503 goto replay_sequence;
9507 /* Expand mode-line and scroll-bar events into two events:
9508 use posn as a fake prefix key. */
9509 if (SYMBOLP (posn)
9510 && (NILP (fake_prefixed_keys)
9511 || NILP (Fmemq (key, fake_prefixed_keys))))
9513 if (bufsize - t <= 1)
9514 error ("Key sequence too long");
9516 keybuf[t] = posn;
9517 keybuf[t + 1] = key;
9518 mock_input = t + 2;
9520 /* Record that a fake prefix key has been generated
9521 for KEY. Don't modify the event; this would
9522 prevent proper action when the event is pushed
9523 back into unread-command-events. */
9524 fake_prefixed_keys = Fcons (key, fake_prefixed_keys);
9525 goto replay_key;
9528 else if (CONSP (XCDR (key))
9529 && CONSP (EVENT_START (key))
9530 && CONSP (XCDR (EVENT_START (key))))
9532 Lisp_Object posn;
9534 posn = POSN_POSN (EVENT_START (key));
9535 /* Handle menu-bar events:
9536 insert the dummy prefix event `menu-bar'. */
9537 if (EQ (posn, Qmenu_bar) || EQ (posn, Qtool_bar))
9539 if (bufsize - t <= 1)
9540 error ("Key sequence too long");
9541 keybuf[t] = posn;
9542 keybuf[t + 1] = key;
9544 /* Zap the position in key, so we know that we've
9545 expanded it, and don't try to do so again. */
9546 POSN_SET_POSN (EVENT_START (key), list1 (posn));
9548 mock_input = t + 2;
9549 goto replay_sequence;
9551 else if (CONSP (posn))
9553 /* We're looking at the second event of a
9554 sequence which we expanded before. Set
9555 last_real_key_start appropriately. */
9556 if (last_real_key_start == t && t > 0)
9557 last_real_key_start = t - 1;
9562 /* We have finally decided that KEY is something we might want
9563 to look up. */
9564 new_binding = follow_key (current_binding, key);
9566 /* If KEY wasn't bound, we'll try some fallbacks. */
9567 if (!NILP (new_binding))
9568 /* This is needed for the following scenario:
9569 event 0: a down-event that gets dropped by calling replay_key.
9570 event 1: some normal prefix like C-h.
9571 After event 0, first_unbound is 0, after event 1 indec.start,
9572 fkey.start, and keytran.start are all 1, so when we see that
9573 C-h is bound, we need to update first_unbound. */
9574 first_unbound = max (t + 1, first_unbound);
9575 else
9577 Lisp_Object head;
9579 /* Remember the position to put an upper bound on indec.start. */
9580 first_unbound = min (t, first_unbound);
9582 head = EVENT_HEAD (key);
9584 if (SYMBOLP (head))
9586 Lisp_Object breakdown;
9587 int modifiers;
9589 breakdown = parse_modifiers (head);
9590 modifiers = XINT (XCAR (XCDR (breakdown)));
9591 /* Attempt to reduce an unbound mouse event to a simpler
9592 event that is bound:
9593 Drags reduce to clicks.
9594 Double-clicks reduce to clicks.
9595 Triple-clicks reduce to double-clicks, then to clicks.
9596 Down-clicks are eliminated.
9597 Double-downs reduce to downs, then are eliminated.
9598 Triple-downs reduce to double-downs, then to downs,
9599 then are eliminated. */
9600 if (modifiers & (down_modifier | drag_modifier
9601 | double_modifier | triple_modifier))
9603 while (modifiers & (down_modifier | drag_modifier
9604 | double_modifier | triple_modifier))
9606 Lisp_Object new_head, new_click;
9607 if (modifiers & triple_modifier)
9608 modifiers ^= (double_modifier | triple_modifier);
9609 else if (modifiers & double_modifier)
9610 modifiers &= ~double_modifier;
9611 else if (modifiers & drag_modifier)
9612 modifiers &= ~drag_modifier;
9613 else
9615 /* Dispose of this `down' event by simply jumping
9616 back to replay_key, to get another event.
9618 Note that if this event came from mock input,
9619 then just jumping back to replay_key will just
9620 hand it to us again. So we have to wipe out any
9621 mock input.
9623 We could delete keybuf[t] and shift everything
9624 after that to the left by one spot, but we'd also
9625 have to fix up any variable that points into
9626 keybuf, and shifting isn't really necessary
9627 anyway.
9629 Adding prefixes for non-textual mouse clicks
9630 creates two characters of mock input, and both
9631 must be thrown away. If we're only looking at
9632 the prefix now, we can just jump back to
9633 replay_key. On the other hand, if we've already
9634 processed the prefix, and now the actual click
9635 itself is giving us trouble, then we've lost the
9636 state of the keymaps we want to backtrack to, and
9637 we need to replay the whole sequence to rebuild
9640 Beyond that, only function key expansion could
9641 create more than two keys, but that should never
9642 generate mouse events, so it's okay to zero
9643 mock_input in that case too.
9645 FIXME: The above paragraph seems just plain
9646 wrong, if you consider things like
9647 xterm-mouse-mode. -stef
9649 Isn't this just the most wonderful code ever? */
9651 /* If mock_input > t + 1, the above simplification
9652 will actually end up dropping keys on the floor.
9653 This is probably OK for now, but even
9654 if mock_input <= t + 1, we need to adjust indec,
9655 fkey, and keytran.
9656 Typical case [header-line down-mouse-N]:
9657 mock_input = 2, t = 1, fkey.end = 1,
9658 last_real_key_start = 0. */
9659 if (indec.end > last_real_key_start)
9661 indec.end = indec.start
9662 = min (last_real_key_start, indec.start);
9663 indec.map = indec.parent;
9664 if (fkey.end > last_real_key_start)
9666 fkey.end = fkey.start
9667 = min (last_real_key_start, fkey.start);
9668 fkey.map = fkey.parent;
9669 if (keytran.end > last_real_key_start)
9671 keytran.end = keytran.start
9672 = min (last_real_key_start, keytran.start);
9673 keytran.map = keytran.parent;
9677 if (t == last_real_key_start)
9679 mock_input = 0;
9680 goto replay_key;
9682 else
9684 mock_input = last_real_key_start;
9685 goto replay_sequence;
9689 new_head
9690 = apply_modifiers (modifiers, XCAR (breakdown));
9691 new_click = list2 (new_head, EVENT_START (key));
9693 /* Look for a binding for this new key. */
9694 new_binding = follow_key (current_binding, new_click);
9696 /* If that click is bound, go for it. */
9697 if (!NILP (new_binding))
9699 current_binding = new_binding;
9700 key = new_click;
9701 break;
9703 /* Otherwise, we'll leave key set to the drag event. */
9708 current_binding = new_binding;
9710 keybuf[t++] = key;
9711 /* Normally, last_nonmenu_event gets the previous key we read.
9712 But when a mouse popup menu is being used,
9713 we don't update last_nonmenu_event; it continues to hold the mouse
9714 event that preceded the first level of menu. */
9715 if (!used_mouse_menu)
9716 last_nonmenu_event = key;
9718 /* Record what part of this_command_keys is the current key sequence. */
9719 this_single_command_key_start = this_command_key_count - t;
9721 /* Look for this sequence in input-decode-map.
9722 Scan from indec.end until we find a bound suffix. */
9723 while (indec.end < t)
9725 struct gcpro gcpro1, gcpro2, gcpro3, gcpro4;
9726 bool done;
9727 int diff;
9729 GCPRO4 (indec.map, fkey.map, keytran.map, delayed_switch_frame);
9730 done = keyremap_step (keybuf, bufsize, &indec, max (t, mock_input),
9731 1, &diff, prompt);
9732 UNGCPRO;
9733 if (done)
9735 mock_input = diff + max (t, mock_input);
9736 goto replay_sequence;
9740 if (!KEYMAPP (current_binding)
9741 && !test_undefined (current_binding)
9742 && indec.start >= t)
9743 /* There is a binding and it's not a prefix.
9744 (and it doesn't have any input-decode-map translation pending).
9745 There is thus no function-key in this sequence.
9746 Moving fkey.start is important in this case to allow keytran.start
9747 to go over the sequence before we return (since we keep the
9748 invariant that keytran.end <= fkey.start). */
9750 if (fkey.start < t)
9751 (fkey.start = fkey.end = t, fkey.map = fkey.parent);
9753 else
9754 /* If the sequence is unbound, see if we can hang a function key
9755 off the end of it. */
9756 /* Continue scan from fkey.end until we find a bound suffix. */
9757 while (fkey.end < indec.start)
9759 struct gcpro gcpro1, gcpro2, gcpro3, gcpro4;
9760 bool done;
9761 int diff;
9763 GCPRO4 (indec.map, fkey.map, keytran.map, delayed_switch_frame);
9764 done = keyremap_step (keybuf, bufsize, &fkey,
9765 max (t, mock_input),
9766 /* If there's a binding (i.e.
9767 first_binding >= nmaps) we don't want
9768 to apply this function-key-mapping. */
9769 fkey.end + 1 == t
9770 && (test_undefined (current_binding)),
9771 &diff, prompt);
9772 UNGCPRO;
9773 if (done)
9775 mock_input = diff + max (t, mock_input);
9776 /* Adjust the input-decode-map counters. */
9777 indec.end += diff;
9778 indec.start += diff;
9780 goto replay_sequence;
9784 /* Look for this sequence in key-translation-map.
9785 Scan from keytran.end until we find a bound suffix. */
9786 while (keytran.end < fkey.start)
9788 struct gcpro gcpro1, gcpro2, gcpro3, gcpro4;
9789 bool done;
9790 int diff;
9792 GCPRO4 (indec.map, fkey.map, keytran.map, delayed_switch_frame);
9793 done = keyremap_step (keybuf, bufsize, &keytran, max (t, mock_input),
9794 1, &diff, prompt);
9795 UNGCPRO;
9796 if (done)
9798 mock_input = diff + max (t, mock_input);
9799 /* Adjust the function-key-map and input-decode-map counters. */
9800 indec.end += diff;
9801 indec.start += diff;
9802 fkey.end += diff;
9803 fkey.start += diff;
9805 goto replay_sequence;
9809 /* If KEY is not defined in any of the keymaps,
9810 and cannot be part of a function key or translation,
9811 and is an upper case letter
9812 use the corresponding lower-case letter instead. */
9813 if (NILP (current_binding)
9814 && /* indec.start >= t && fkey.start >= t && */ keytran.start >= t
9815 && INTEGERP (key)
9816 && ((CHARACTERP (make_number (XINT (key) & ~CHAR_MODIFIER_MASK))
9817 && uppercasep (XINT (key) & ~CHAR_MODIFIER_MASK))
9818 || (XINT (key) & shift_modifier)))
9820 Lisp_Object new_key;
9822 original_uppercase = key;
9823 original_uppercase_position = t - 1;
9825 if (XINT (key) & shift_modifier)
9826 XSETINT (new_key, XINT (key) & ~shift_modifier);
9827 else
9828 XSETINT (new_key, (downcase (XINT (key) & ~CHAR_MODIFIER_MASK)
9829 | (XINT (key) & CHAR_MODIFIER_MASK)));
9831 /* We have to do this unconditionally, regardless of whether
9832 the lower-case char is defined in the keymaps, because they
9833 might get translated through function-key-map. */
9834 keybuf[t - 1] = new_key;
9835 mock_input = max (t, mock_input);
9836 shift_translated = 1;
9838 goto replay_sequence;
9841 if (NILP (current_binding)
9842 && help_char_p (EVENT_HEAD (key)) && t > 1)
9844 read_key_sequence_cmd = Vprefix_help_command;
9845 /* The Microsoft C compiler can't handle the goto that
9846 would go here. */
9847 dummyflag = 1;
9848 break;
9851 /* If KEY is not defined in any of the keymaps,
9852 and cannot be part of a function key or translation,
9853 and is a shifted function key,
9854 use the corresponding unshifted function key instead. */
9855 if (NILP (current_binding)
9856 && /* indec.start >= t && fkey.start >= t && */ keytran.start >= t)
9858 Lisp_Object breakdown = parse_modifiers (key);
9859 int modifiers
9860 = CONSP (breakdown) ? (XINT (XCAR (XCDR (breakdown)))) : 0;
9862 if (modifiers & shift_modifier
9863 /* Treat uppercase keys as shifted. */
9864 || (INTEGERP (key)
9865 && (KEY_TO_CHAR (key)
9866 < XCHAR_TABLE (BVAR (current_buffer, downcase_table))->header.size)
9867 && uppercasep (KEY_TO_CHAR (key))))
9869 Lisp_Object new_key
9870 = (modifiers & shift_modifier
9871 ? apply_modifiers (modifiers & ~shift_modifier,
9872 XCAR (breakdown))
9873 : make_number (downcase (KEY_TO_CHAR (key)) | modifiers));
9875 original_uppercase = key;
9876 original_uppercase_position = t - 1;
9878 /* We have to do this unconditionally, regardless of whether
9879 the lower-case char is defined in the keymaps, because they
9880 might get translated through function-key-map. */
9881 keybuf[t - 1] = new_key;
9882 mock_input = max (t, mock_input);
9883 /* Reset fkey (and consequently keytran) to apply
9884 function-key-map on the result, so that S-backspace is
9885 correctly mapped to DEL (via backspace). OTOH,
9886 input-decode-map doesn't need to go through it again. */
9887 fkey.start = fkey.end = 0;
9888 keytran.start = keytran.end = 0;
9889 shift_translated = 1;
9891 goto replay_sequence;
9895 if (!dummyflag)
9896 read_key_sequence_cmd = current_binding;
9897 read_key_sequence_remapped
9898 /* Remap command through active keymaps.
9899 Do the remapping here, before the unbind_to so it uses the keymaps
9900 of the appropriate buffer. */
9901 = SYMBOLP (read_key_sequence_cmd)
9902 ? Fcommand_remapping (read_key_sequence_cmd, Qnil, Qnil)
9903 : Qnil;
9905 unread_switch_frame = delayed_switch_frame;
9906 unbind_to (count, Qnil);
9908 /* Don't downcase the last character if the caller says don't.
9909 Don't downcase it if the result is undefined, either. */
9910 if ((dont_downcase_last || NILP (current_binding))
9911 && t > 0
9912 && t - 1 == original_uppercase_position)
9914 keybuf[t - 1] = original_uppercase;
9915 shift_translated = 0;
9918 if (shift_translated)
9919 Vthis_command_keys_shift_translated = Qt;
9921 /* Occasionally we fabricate events, perhaps by expanding something
9922 according to function-key-map, or by adding a prefix symbol to a
9923 mouse click in the scroll bar or modeline. In this cases, return
9924 the entire generated key sequence, even if we hit an unbound
9925 prefix or a definition before the end. This means that you will
9926 be able to push back the event properly, and also means that
9927 read-key-sequence will always return a logical unit.
9929 Better ideas? */
9930 for (; t < mock_input; t++)
9932 if (echo_keystrokes_p ())
9933 echo_char (keybuf[t]);
9934 add_command_key (keybuf[t]);
9937 UNGCPRO;
9938 return t;
9941 static Lisp_Object
9942 read_key_sequence_vs (Lisp_Object prompt, Lisp_Object continue_echo,
9943 Lisp_Object dont_downcase_last,
9944 Lisp_Object can_return_switch_frame,
9945 Lisp_Object cmd_loop, bool allow_string)
9947 Lisp_Object keybuf[30];
9948 register int i;
9949 struct gcpro gcpro1;
9950 ptrdiff_t count = SPECPDL_INDEX ();
9952 if (!NILP (prompt))
9953 CHECK_STRING (prompt);
9954 QUIT;
9956 specbind (Qinput_method_exit_on_first_char,
9957 (NILP (cmd_loop) ? Qt : Qnil));
9958 specbind (Qinput_method_use_echo_area,
9959 (NILP (cmd_loop) ? Qt : Qnil));
9961 memset (keybuf, 0, sizeof keybuf);
9962 GCPRO1 (keybuf[0]);
9963 gcpro1.nvars = ARRAYELTS (keybuf);
9965 if (NILP (continue_echo))
9967 this_command_key_count = 0;
9968 this_command_key_count_reset = 0;
9969 this_single_command_key_start = 0;
9972 #ifdef HAVE_WINDOW_SYSTEM
9973 if (display_hourglass_p)
9974 cancel_hourglass ();
9975 #endif
9977 i = read_key_sequence (keybuf, ARRAYELTS (keybuf),
9978 prompt, ! NILP (dont_downcase_last),
9979 ! NILP (can_return_switch_frame), 0, 0);
9981 #if 0 /* The following is fine for code reading a key sequence and
9982 then proceeding with a lengthy computation, but it's not good
9983 for code reading keys in a loop, like an input method. */
9984 #ifdef HAVE_WINDOW_SYSTEM
9985 if (display_hourglass_p)
9986 start_hourglass ();
9987 #endif
9988 #endif
9990 if (i == -1)
9992 Vquit_flag = Qt;
9993 QUIT;
9995 UNGCPRO;
9996 return unbind_to (count,
9997 ((allow_string ? make_event_array : Fvector)
9998 (i, keybuf)));
10001 DEFUN ("read-key-sequence", Fread_key_sequence, Sread_key_sequence, 1, 5, 0,
10002 doc: /* Read a sequence of keystrokes and return as a string or vector.
10003 The sequence is sufficient to specify a non-prefix command in the
10004 current local and global maps.
10006 First arg PROMPT is a prompt string. If nil, do not prompt specially.
10007 Second (optional) arg CONTINUE-ECHO, if non-nil, means this key echos
10008 as a continuation of the previous key.
10010 The third (optional) arg DONT-DOWNCASE-LAST, if non-nil, means do not
10011 convert the last event to lower case. (Normally any upper case event
10012 is converted to lower case if the original event is undefined and the lower
10013 case equivalent is defined.) A non-nil value is appropriate for reading
10014 a key sequence to be defined.
10016 A C-g typed while in this function is treated like any other character,
10017 and `quit-flag' is not set.
10019 If the key sequence starts with a mouse click, then the sequence is read
10020 using the keymaps of the buffer of the window clicked in, not the buffer
10021 of the selected window as normal.
10023 `read-key-sequence' drops unbound button-down events, since you normally
10024 only care about the click or drag events which follow them. If a drag
10025 or multi-click event is unbound, but the corresponding click event would
10026 be bound, `read-key-sequence' turns the event into a click event at the
10027 drag's starting position. This means that you don't have to distinguish
10028 between click and drag, double, or triple events unless you want to.
10030 `read-key-sequence' prefixes mouse events on mode lines, the vertical
10031 lines separating windows, and scroll bars with imaginary keys
10032 `mode-line', `vertical-line', and `vertical-scroll-bar'.
10034 Optional fourth argument CAN-RETURN-SWITCH-FRAME non-nil means that this
10035 function will process a switch-frame event if the user switches frames
10036 before typing anything. If the user switches frames in the middle of a
10037 key sequence, or at the start of the sequence but CAN-RETURN-SWITCH-FRAME
10038 is nil, then the event will be put off until after the current key sequence.
10040 `read-key-sequence' checks `function-key-map' for function key
10041 sequences, where they wouldn't conflict with ordinary bindings. See
10042 `function-key-map' for more details.
10044 The optional fifth argument CMD-LOOP, if non-nil, means
10045 that this key sequence is being read by something that will
10046 read commands one after another. It should be nil if the caller
10047 will read just one key sequence. */)
10048 (Lisp_Object prompt, Lisp_Object continue_echo, Lisp_Object dont_downcase_last, Lisp_Object can_return_switch_frame, Lisp_Object cmd_loop)
10050 return read_key_sequence_vs (prompt, continue_echo, dont_downcase_last,
10051 can_return_switch_frame, cmd_loop, true);
10054 DEFUN ("read-key-sequence-vector", Fread_key_sequence_vector,
10055 Sread_key_sequence_vector, 1, 5, 0,
10056 doc: /* Like `read-key-sequence' but always return a vector. */)
10057 (Lisp_Object prompt, Lisp_Object continue_echo, Lisp_Object dont_downcase_last, Lisp_Object can_return_switch_frame, Lisp_Object cmd_loop)
10059 return read_key_sequence_vs (prompt, continue_echo, dont_downcase_last,
10060 can_return_switch_frame, cmd_loop, false);
10063 /* Return true if input events are pending. */
10065 bool
10066 detect_input_pending (void)
10068 return input_pending || get_input_pending (0);
10071 /* Return true if input events other than mouse movements are
10072 pending. */
10074 bool
10075 detect_input_pending_ignore_squeezables (void)
10077 return input_pending || get_input_pending (READABLE_EVENTS_IGNORE_SQUEEZABLES);
10080 /* Return true if input events are pending, and run any pending timers. */
10082 bool
10083 detect_input_pending_run_timers (bool do_display)
10085 unsigned old_timers_run = timers_run;
10087 if (!input_pending)
10088 get_input_pending (READABLE_EVENTS_DO_TIMERS_NOW);
10090 if (old_timers_run != timers_run && do_display)
10091 redisplay_preserve_echo_area (8);
10093 return input_pending;
10096 /* This is called in some cases before a possible quit.
10097 It cases the next call to detect_input_pending to recompute input_pending.
10098 So calling this function unnecessarily can't do any harm. */
10100 void
10101 clear_input_pending (void)
10103 input_pending = 0;
10106 /* Return true if there are pending requeued events.
10107 This isn't used yet. The hope is to make wait_reading_process_output
10108 call it, and return if it runs Lisp code that unreads something.
10109 The problem is, kbd_buffer_get_event needs to be fixed to know what
10110 to do in that case. It isn't trivial. */
10112 bool
10113 requeued_events_pending_p (void)
10115 return (!NILP (Vunread_command_events));
10118 DEFUN ("input-pending-p", Finput_pending_p, Sinput_pending_p, 0, 1, 0,
10119 doc: /* Return t if command input is currently available with no wait.
10120 Actually, the value is nil only if we can be sure that no input is available;
10121 if there is a doubt, the value is t.
10123 If CHECK-TIMERS is non-nil, timers that are ready to run will do so. */)
10124 (Lisp_Object check_timers)
10126 if (!NILP (Vunread_command_events)
10127 || !NILP (Vunread_post_input_method_events)
10128 || !NILP (Vunread_input_method_events))
10129 return (Qt);
10131 /* Process non-user-visible events (Bug#10195). */
10132 process_special_events ();
10134 return (get_input_pending ((NILP (check_timers)
10135 ? 0 : READABLE_EVENTS_DO_TIMERS_NOW)
10136 | READABLE_EVENTS_FILTER_EVENTS)
10137 ? Qt : Qnil);
10140 DEFUN ("recent-keys", Frecent_keys, Srecent_keys, 0, 1, 0,
10141 doc: /* Return vector of last few events, not counting those from keyboard macros.
10142 If INCLUDE-CMDS is non-nil, include the commands that were run,
10143 represented as events of the form (nil . COMMAND). */)
10144 (Lisp_Object include_cmds)
10146 bool cmds = !NILP (include_cmds);
10148 if (!total_keys
10149 || (cmds && total_keys < NUM_RECENT_KEYS))
10150 return Fvector (total_keys,
10151 XVECTOR (recent_keys)->contents);
10152 else
10154 Lisp_Object es = Qnil;
10155 int i = (total_keys < NUM_RECENT_KEYS
10156 ? 0 : recent_keys_index);
10157 eassert (recent_keys_index < NUM_RECENT_KEYS);
10160 Lisp_Object e = AREF (recent_keys, i);
10161 if (cmds || !CONSP (e) || !NILP (XCAR (e)))
10162 es = Fcons (e, es);
10163 if (++i >= NUM_RECENT_KEYS)
10164 i = 0;
10165 } while (i != recent_keys_index);
10166 es = Fnreverse (es);
10167 return Fvconcat (1, &es);
10171 DEFUN ("this-command-keys", Fthis_command_keys, Sthis_command_keys, 0, 0, 0,
10172 doc: /* Return the key sequence that invoked this command.
10173 However, if the command has called `read-key-sequence', it returns
10174 the last key sequence that has been read.
10175 The value is a string or a vector.
10177 See also `this-command-keys-vector'. */)
10178 (void)
10180 return make_event_array (this_command_key_count,
10181 XVECTOR (this_command_keys)->contents);
10184 DEFUN ("this-command-keys-vector", Fthis_command_keys_vector, Sthis_command_keys_vector, 0, 0, 0,
10185 doc: /* Return the key sequence that invoked this command, as a vector.
10186 However, if the command has called `read-key-sequence', it returns
10187 the last key sequence that has been read.
10189 See also `this-command-keys'. */)
10190 (void)
10192 return Fvector (this_command_key_count,
10193 XVECTOR (this_command_keys)->contents);
10196 DEFUN ("this-single-command-keys", Fthis_single_command_keys,
10197 Sthis_single_command_keys, 0, 0, 0,
10198 doc: /* Return the key sequence that invoked this command.
10199 More generally, it returns the last key sequence read, either by
10200 the command loop or by `read-key-sequence'.
10201 Unlike `this-command-keys', this function's value
10202 does not include prefix arguments.
10203 The value is always a vector. */)
10204 (void)
10206 return Fvector (this_command_key_count
10207 - this_single_command_key_start,
10208 (XVECTOR (this_command_keys)->contents
10209 + this_single_command_key_start));
10212 DEFUN ("this-single-command-raw-keys", Fthis_single_command_raw_keys,
10213 Sthis_single_command_raw_keys, 0, 0, 0,
10214 doc: /* Return the raw events that were read for this command.
10215 More generally, it returns the last key sequence read, either by
10216 the command loop or by `read-key-sequence'.
10217 Unlike `this-single-command-keys', this function's value
10218 shows the events before all translations (except for input methods).
10219 The value is always a vector. */)
10220 (void)
10222 return Fvector (raw_keybuf_count, XVECTOR (raw_keybuf)->contents);
10225 DEFUN ("reset-this-command-lengths", Freset_this_command_lengths,
10226 Sreset_this_command_lengths, 0, 0, 0,
10227 doc: /* Make the unread events replace the last command and echo.
10228 Used in `universal-argument-other-key'.
10230 `universal-argument-other-key' rereads the event just typed.
10231 It then gets translated through `function-key-map'.
10232 The translated event has to replace the real events,
10233 both in the value of (this-command-keys) and in echoing.
10234 To achieve this, `universal-argument-other-key' calls
10235 `reset-this-command-lengths', which discards the record of reading
10236 these events the first time. */)
10237 (void)
10239 this_command_key_count = before_command_key_count;
10240 if (this_command_key_count < this_single_command_key_start)
10241 this_single_command_key_start = this_command_key_count;
10243 echo_truncate (before_command_echo_length);
10245 /* Cause whatever we put into unread-command-events
10246 to echo as if it were being freshly read from the keyboard. */
10247 this_command_key_count_reset = 1;
10249 return Qnil;
10252 DEFUN ("clear-this-command-keys", Fclear_this_command_keys,
10253 Sclear_this_command_keys, 0, 1, 0,
10254 doc: /* Clear out the vector that `this-command-keys' returns.
10255 Also clear the record of the last 100 events, unless optional arg
10256 KEEP-RECORD is non-nil. */)
10257 (Lisp_Object keep_record)
10259 int i;
10261 this_command_key_count = 0;
10262 this_command_key_count_reset = 0;
10264 if (NILP (keep_record))
10266 for (i = 0; i < ASIZE (recent_keys); ++i)
10267 ASET (recent_keys, i, Qnil);
10268 total_keys = 0;
10269 recent_keys_index = 0;
10271 return Qnil;
10274 DEFUN ("recursion-depth", Frecursion_depth, Srecursion_depth, 0, 0, 0,
10275 doc: /* Return the current depth in recursive edits. */)
10276 (void)
10278 Lisp_Object temp;
10279 /* Wrap around reliably on integer overflow. */
10280 EMACS_INT sum = (command_loop_level & INTMASK) + (minibuf_level & INTMASK);
10281 XSETINT (temp, sum);
10282 return temp;
10285 DEFUN ("open-dribble-file", Fopen_dribble_file, Sopen_dribble_file, 1, 1,
10286 "FOpen dribble file: ",
10287 doc: /* Start writing all keyboard characters to a dribble file called FILE.
10288 If FILE is nil, close any open dribble file.
10289 The file will be closed when Emacs exits.
10291 Be aware that this records ALL characters you type!
10292 This may include sensitive information such as passwords. */)
10293 (Lisp_Object file)
10295 if (dribble)
10297 block_input ();
10298 fclose (dribble);
10299 unblock_input ();
10300 dribble = 0;
10302 if (!NILP (file))
10304 int fd;
10305 Lisp_Object encfile;
10307 file = Fexpand_file_name (file, Qnil);
10308 encfile = ENCODE_FILE (file);
10309 fd = emacs_open (SSDATA (encfile), O_WRONLY | O_CREAT | O_EXCL, 0600);
10310 if (fd < 0 && errno == EEXIST && unlink (SSDATA (encfile)) == 0)
10311 fd = emacs_open (SSDATA (encfile), O_WRONLY | O_CREAT | O_EXCL, 0600);
10312 dribble = fd < 0 ? 0 : fdopen (fd, "w");
10313 if (dribble == 0)
10314 report_file_error ("Opening dribble", file);
10316 return Qnil;
10319 DEFUN ("discard-input", Fdiscard_input, Sdiscard_input, 0, 0, 0,
10320 doc: /* Discard the contents of the terminal input buffer.
10321 Also end any kbd macro being defined. */)
10322 (void)
10324 if (!NILP (KVAR (current_kboard, defining_kbd_macro)))
10326 /* Discard the last command from the macro. */
10327 Fcancel_kbd_macro_events ();
10328 end_kbd_macro ();
10331 Vunread_command_events = Qnil;
10333 discard_tty_input ();
10335 kbd_fetch_ptr = kbd_store_ptr;
10336 input_pending = 0;
10338 return Qnil;
10341 DEFUN ("suspend-emacs", Fsuspend_emacs, Ssuspend_emacs, 0, 1, "",
10342 doc: /* Stop Emacs and return to superior process. You can resume later.
10343 If `cannot-suspend' is non-nil, or if the system doesn't support job
10344 control, run a subshell instead.
10346 If optional arg STUFFSTRING is non-nil, its characters are stuffed
10347 to be read as terminal input by Emacs's parent, after suspension.
10349 Before suspending, run the normal hook `suspend-hook'.
10350 After resumption run the normal hook `suspend-resume-hook'.
10352 Some operating systems cannot stop the Emacs process and resume it later.
10353 On such systems, Emacs starts a subshell instead of suspending. */)
10354 (Lisp_Object stuffstring)
10356 ptrdiff_t count = SPECPDL_INDEX ();
10357 int old_height, old_width;
10358 int width, height;
10359 struct gcpro gcpro1;
10360 Lisp_Object hook;
10362 if (tty_list && tty_list->next)
10363 error ("There are other tty frames open; close them before suspending Emacs");
10365 if (!NILP (stuffstring))
10366 CHECK_STRING (stuffstring);
10368 /* Run the functions in suspend-hook. */
10369 hook = intern ("suspend-hook");
10370 Frun_hooks (1, &hook);
10372 GCPRO1 (stuffstring);
10373 get_tty_size (fileno (CURTTY ()->input), &old_width, &old_height);
10374 reset_all_sys_modes ();
10375 /* sys_suspend can get an error if it tries to fork a subshell
10376 and the system resources aren't available for that. */
10377 record_unwind_protect_void (init_all_sys_modes);
10378 stuff_buffered_input (stuffstring);
10379 if (cannot_suspend)
10380 sys_subshell ();
10381 else
10382 sys_suspend ();
10383 unbind_to (count, Qnil);
10385 /* Check if terminal/window size has changed.
10386 Note that this is not useful when we are running directly
10387 with a window system; but suspend should be disabled in that case. */
10388 get_tty_size (fileno (CURTTY ()->input), &width, &height);
10389 if (width != old_width || height != old_height)
10390 change_frame_size (SELECTED_FRAME (), width,
10391 height - FRAME_MENU_BAR_LINES (SELECTED_FRAME ()),
10392 0, 0, 0, 0);
10394 /* Run suspend-resume-hook. */
10395 hook = intern ("suspend-resume-hook");
10396 Frun_hooks (1, &hook);
10398 UNGCPRO;
10399 return Qnil;
10402 /* If STUFFSTRING is a string, stuff its contents as pending terminal input.
10403 Then in any case stuff anything Emacs has read ahead and not used. */
10405 void
10406 stuff_buffered_input (Lisp_Object stuffstring)
10408 #ifdef SIGTSTP /* stuff_char is defined if SIGTSTP. */
10409 register unsigned char *p;
10411 if (STRINGP (stuffstring))
10413 register ptrdiff_t count;
10415 p = SDATA (stuffstring);
10416 count = SBYTES (stuffstring);
10417 while (count-- > 0)
10418 stuff_char (*p++);
10419 stuff_char ('\n');
10422 /* Anything we have read ahead, put back for the shell to read. */
10423 /* ?? What should this do when we have multiple keyboards??
10424 Should we ignore anything that was typed in at the "wrong" kboard?
10426 rms: we should stuff everything back into the kboard
10427 it came from. */
10428 for (; kbd_fetch_ptr != kbd_store_ptr; kbd_fetch_ptr++)
10431 if (kbd_fetch_ptr == kbd_buffer + KBD_BUFFER_SIZE)
10432 kbd_fetch_ptr = kbd_buffer;
10433 if (kbd_fetch_ptr->kind == ASCII_KEYSTROKE_EVENT)
10434 stuff_char (kbd_fetch_ptr->code);
10436 clear_event (kbd_fetch_ptr);
10439 input_pending = 0;
10440 #endif /* SIGTSTP */
10443 void
10444 set_waiting_for_input (struct timespec *time_to_clear)
10446 input_available_clear_time = time_to_clear;
10448 /* Tell handle_interrupt to throw back to read_char, */
10449 waiting_for_input = 1;
10451 /* If handle_interrupt was called before and buffered a C-g,
10452 make it run again now, to avoid timing error. */
10453 if (!NILP (Vquit_flag))
10454 quit_throw_to_read_char (0);
10457 void
10458 clear_waiting_for_input (void)
10460 /* Tell handle_interrupt not to throw back to read_char, */
10461 waiting_for_input = 0;
10462 input_available_clear_time = 0;
10465 /* The SIGINT handler.
10467 If we have a frame on the controlling tty, we assume that the
10468 SIGINT was generated by C-g, so we call handle_interrupt.
10469 Otherwise, tell QUIT to kill Emacs. */
10471 static void
10472 handle_interrupt_signal (int sig)
10474 /* See if we have an active terminal on our controlling tty. */
10475 struct terminal *terminal = get_named_terminal ("/dev/tty");
10476 if (!terminal)
10478 /* If there are no frames there, let's pretend that we are a
10479 well-behaving UN*X program and quit. We must not call Lisp
10480 in a signal handler, so tell QUIT to exit when it is
10481 safe. */
10482 Vquit_flag = Qkill_emacs;
10484 else
10486 /* Otherwise, the SIGINT was probably generated by C-g. */
10488 /* Set internal_last_event_frame to the top frame of the
10489 controlling tty, if we have a frame there. We disable the
10490 interrupt key on secondary ttys, so the SIGINT must have come
10491 from the controlling tty. */
10492 internal_last_event_frame = terminal->display_info.tty->top_frame;
10494 handle_interrupt (1);
10498 static void
10499 deliver_interrupt_signal (int sig)
10501 deliver_process_signal (sig, handle_interrupt_signal);
10505 /* If Emacs is stuck because `inhibit-quit' is true, then keep track
10506 of the number of times C-g has been requested. If C-g is pressed
10507 enough times, then quit anyway. See bug#6585. */
10508 static int volatile force_quit_count;
10510 /* This routine is called at interrupt level in response to C-g.
10512 It is called from the SIGINT handler or kbd_buffer_store_event.
10514 If `waiting_for_input' is non zero, then unless `echoing' is
10515 nonzero, immediately throw back to read_char.
10517 Otherwise it sets the Lisp variable quit-flag not-nil. This causes
10518 eval to throw, when it gets a chance. If quit-flag is already
10519 non-nil, it stops the job right away. */
10521 static void
10522 handle_interrupt (bool in_signal_handler)
10524 char c;
10526 cancel_echoing ();
10528 /* XXX This code needs to be revised for multi-tty support. */
10529 if (!NILP (Vquit_flag) && get_named_terminal ("/dev/tty"))
10531 if (! in_signal_handler)
10533 /* If SIGINT isn't blocked, don't let us be interrupted by
10534 a SIGINT. It might be harmful due to non-reentrancy
10535 in I/O functions. */
10536 sigset_t blocked;
10537 sigemptyset (&blocked);
10538 sigaddset (&blocked, SIGINT);
10539 pthread_sigmask (SIG_BLOCK, &blocked, 0);
10542 fflush (stdout);
10543 reset_all_sys_modes ();
10545 #ifdef SIGTSTP
10547 * On systems which can suspend the current process and return to the original
10548 * shell, this command causes the user to end up back at the shell.
10549 * The "Auto-save" and "Abort" questions are not asked until
10550 * the user elects to return to emacs, at which point he can save the current
10551 * job and either dump core or continue.
10553 sys_suspend ();
10554 #else
10555 /* Perhaps should really fork an inferior shell?
10556 But that would not provide any way to get back
10557 to the original shell, ever. */
10558 printf ("No support for stopping a process on this operating system;\n");
10559 printf ("you can continue or abort.\n");
10560 #endif /* not SIGTSTP */
10561 #ifdef MSDOS
10562 /* We must remain inside the screen area when the internal terminal
10563 is used. Note that [Enter] is not echoed by dos. */
10564 cursor_to (SELECTED_FRAME (), 0, 0);
10565 #endif
10566 /* It doesn't work to autosave while GC is in progress;
10567 the code used for auto-saving doesn't cope with the mark bit. */
10568 if (!gc_in_progress)
10570 printf ("Auto-save? (y or n) ");
10571 fflush (stdout);
10572 if (((c = getchar ()) & ~040) == 'Y')
10574 Fdo_auto_save (Qt, Qnil);
10575 #ifdef MSDOS
10576 printf ("\r\nAuto-save done");
10577 #else /* not MSDOS */
10578 printf ("Auto-save done\n");
10579 #endif /* not MSDOS */
10581 while (c != '\n') c = getchar ();
10583 else
10585 /* During GC, it must be safe to reenable quitting again. */
10586 Vinhibit_quit = Qnil;
10587 #ifdef MSDOS
10588 printf ("\r\n");
10589 #endif /* not MSDOS */
10590 printf ("Garbage collection in progress; cannot auto-save now\r\n");
10591 printf ("but will instead do a real quit after garbage collection ends\r\n");
10592 fflush (stdout);
10595 #ifdef MSDOS
10596 printf ("\r\nAbort? (y or n) ");
10597 #else /* not MSDOS */
10598 printf ("Abort (and dump core)? (y or n) ");
10599 #endif /* not MSDOS */
10600 fflush (stdout);
10601 if (((c = getchar ()) & ~040) == 'Y')
10602 emacs_abort ();
10603 while (c != '\n') c = getchar ();
10604 #ifdef MSDOS
10605 printf ("\r\nContinuing...\r\n");
10606 #else /* not MSDOS */
10607 printf ("Continuing...\n");
10608 #endif /* not MSDOS */
10609 fflush (stdout);
10610 init_all_sys_modes ();
10612 else
10614 /* If executing a function that wants to be interrupted out of
10615 and the user has not deferred quitting by binding `inhibit-quit'
10616 then quit right away. */
10617 if (immediate_quit && NILP (Vinhibit_quit))
10619 struct gl_state_s saved;
10620 struct gcpro gcpro1, gcpro2, gcpro3, gcpro4;
10622 immediate_quit = 0;
10623 pthread_sigmask (SIG_SETMASK, &empty_mask, 0);
10624 saved = gl_state;
10625 GCPRO4 (saved.object, saved.global_code,
10626 saved.current_syntax_table, saved.old_prop);
10627 Fsignal (Qquit, Qnil);
10628 gl_state = saved;
10629 UNGCPRO;
10631 else
10632 { /* Else request quit when it's safe. */
10633 int count = NILP (Vquit_flag) ? 1 : force_quit_count + 1;
10634 force_quit_count = count;
10635 if (count == 3)
10637 immediate_quit = 1;
10638 Vinhibit_quit = Qnil;
10640 Vquit_flag = Qt;
10644 pthread_sigmask (SIG_SETMASK, &empty_mask, 0);
10646 /* TODO: The longjmp in this call throws the NS event loop integration off,
10647 and it seems to do fine without this. Probably some attention
10648 needs to be paid to the setting of waiting_for_input in
10649 wait_reading_process_output() under HAVE_NS because of the call
10650 to ns_select there (needed because otherwise events aren't picked up
10651 outside of polling since we don't get SIGIO like X and we don't have a
10652 separate event loop thread like W32. */
10653 #ifndef HAVE_NS
10654 if (waiting_for_input && !echoing)
10655 quit_throw_to_read_char (in_signal_handler);
10656 #endif
10659 /* Handle a C-g by making read_char return C-g. */
10661 static void
10662 quit_throw_to_read_char (bool from_signal)
10664 /* When not called from a signal handler it is safe to call
10665 Lisp. */
10666 if (!from_signal && EQ (Vquit_flag, Qkill_emacs))
10667 Fkill_emacs (Qnil);
10669 /* Prevent another signal from doing this before we finish. */
10670 clear_waiting_for_input ();
10671 input_pending = 0;
10673 Vunread_command_events = Qnil;
10675 if (FRAMEP (internal_last_event_frame)
10676 && !EQ (internal_last_event_frame, selected_frame))
10677 do_switch_frame (make_lispy_switch_frame (internal_last_event_frame),
10678 0, 0, Qnil);
10680 sys_longjmp (getcjmp, 1);
10683 DEFUN ("set-input-interrupt-mode", Fset_input_interrupt_mode,
10684 Sset_input_interrupt_mode, 1, 1, 0,
10685 doc: /* Set interrupt mode of reading keyboard input.
10686 If INTERRUPT is non-nil, Emacs will use input interrupts;
10687 otherwise Emacs uses CBREAK mode.
10689 See also `current-input-mode'. */)
10690 (Lisp_Object interrupt)
10692 bool new_interrupt_input;
10693 #ifdef USABLE_SIGIO
10694 #ifdef HAVE_X_WINDOWS
10695 if (x_display_list != NULL)
10697 /* When using X, don't give the user a real choice,
10698 because we haven't implemented the mechanisms to support it. */
10699 new_interrupt_input = 1;
10701 else
10702 #endif /* HAVE_X_WINDOWS */
10703 new_interrupt_input = !NILP (interrupt);
10704 #else /* not USABLE_SIGIO */
10705 new_interrupt_input = 0;
10706 #endif /* not USABLE_SIGIO */
10708 if (new_interrupt_input != interrupt_input)
10710 #ifdef POLL_FOR_INPUT
10711 stop_polling ();
10712 #endif
10713 #ifndef DOS_NT
10714 /* this causes startup screen to be restored and messes with the mouse */
10715 reset_all_sys_modes ();
10716 interrupt_input = new_interrupt_input;
10717 init_all_sys_modes ();
10718 #else
10719 interrupt_input = new_interrupt_input;
10720 #endif
10722 #ifdef POLL_FOR_INPUT
10723 poll_suppress_count = 1;
10724 start_polling ();
10725 #endif
10727 return Qnil;
10730 DEFUN ("set-output-flow-control", Fset_output_flow_control, Sset_output_flow_control, 1, 2, 0,
10731 doc: /* Enable or disable ^S/^Q flow control for output to TERMINAL.
10732 If FLOW is non-nil, flow control is enabled and you cannot use C-s or
10733 C-q in key sequences.
10735 This setting only has an effect on tty terminals and only when
10736 Emacs reads input in CBREAK mode; see `set-input-interrupt-mode'.
10738 See also `current-input-mode'. */)
10739 (Lisp_Object flow, Lisp_Object terminal)
10741 struct terminal *t = decode_tty_terminal (terminal);
10742 struct tty_display_info *tty;
10744 if (!t)
10745 return Qnil;
10746 tty = t->display_info.tty;
10748 if (tty->flow_control != !NILP (flow))
10750 #ifndef DOS_NT
10751 /* This causes startup screen to be restored and messes with the mouse. */
10752 reset_sys_modes (tty);
10753 #endif
10755 tty->flow_control = !NILP (flow);
10757 #ifndef DOS_NT
10758 init_sys_modes (tty);
10759 #endif
10761 return Qnil;
10764 DEFUN ("set-input-meta-mode", Fset_input_meta_mode, Sset_input_meta_mode, 1, 2, 0,
10765 doc: /* Enable or disable 8-bit input on TERMINAL.
10766 If META is t, Emacs will accept 8-bit input, and interpret the 8th
10767 bit as the Meta modifier.
10769 If META is nil, Emacs will ignore the top bit, on the assumption it is
10770 parity.
10772 Otherwise, Emacs will accept and pass through 8-bit input without
10773 specially interpreting the top bit.
10775 This setting only has an effect on tty terminal devices.
10777 Optional parameter TERMINAL specifies the tty terminal device to use.
10778 It may be a terminal object, a frame, or nil for the terminal used by
10779 the currently selected frame.
10781 See also `current-input-mode'. */)
10782 (Lisp_Object meta, Lisp_Object terminal)
10784 struct terminal *t = decode_tty_terminal (terminal);
10785 struct tty_display_info *tty;
10786 int new_meta;
10788 if (!t)
10789 return Qnil;
10790 tty = t->display_info.tty;
10792 if (NILP (meta))
10793 new_meta = 0;
10794 else if (EQ (meta, Qt))
10795 new_meta = 1;
10796 else
10797 new_meta = 2;
10799 if (tty->meta_key != new_meta)
10801 #ifndef DOS_NT
10802 /* this causes startup screen to be restored and messes with the mouse */
10803 reset_sys_modes (tty);
10804 #endif
10806 tty->meta_key = new_meta;
10808 #ifndef DOS_NT
10809 init_sys_modes (tty);
10810 #endif
10812 return Qnil;
10815 DEFUN ("set-quit-char", Fset_quit_char, Sset_quit_char, 1, 1, 0,
10816 doc: /* Specify character used for quitting.
10817 QUIT must be an ASCII character.
10819 This function only has an effect on the controlling tty of the Emacs
10820 process.
10822 See also `current-input-mode'. */)
10823 (Lisp_Object quit)
10825 struct terminal *t = get_named_terminal ("/dev/tty");
10826 struct tty_display_info *tty;
10828 if (!t)
10829 return Qnil;
10830 tty = t->display_info.tty;
10832 if (NILP (quit) || !INTEGERP (quit) || XINT (quit) < 0 || XINT (quit) > 0400)
10833 error ("QUIT must be an ASCII character");
10835 #ifndef DOS_NT
10836 /* this causes startup screen to be restored and messes with the mouse */
10837 reset_sys_modes (tty);
10838 #endif
10840 /* Don't let this value be out of range. */
10841 quit_char = XINT (quit) & (tty->meta_key == 0 ? 0177 : 0377);
10843 #ifndef DOS_NT
10844 init_sys_modes (tty);
10845 #endif
10847 return Qnil;
10850 DEFUN ("set-input-mode", Fset_input_mode, Sset_input_mode, 3, 4, 0,
10851 doc: /* Set mode of reading keyboard input.
10852 First arg INTERRUPT non-nil means use input interrupts;
10853 nil means use CBREAK mode.
10854 Second arg FLOW non-nil means use ^S/^Q flow control for output to terminal
10855 (no effect except in CBREAK mode).
10856 Third arg META t means accept 8-bit input (for a Meta key).
10857 META nil means ignore the top bit, on the assumption it is parity.
10858 Otherwise, accept 8-bit input and don't use the top bit for Meta.
10859 Optional fourth arg QUIT if non-nil specifies character to use for quitting.
10860 See also `current-input-mode'. */)
10861 (Lisp_Object interrupt, Lisp_Object flow, Lisp_Object meta, Lisp_Object quit)
10863 Fset_input_interrupt_mode (interrupt);
10864 Fset_output_flow_control (flow, Qnil);
10865 Fset_input_meta_mode (meta, Qnil);
10866 if (!NILP (quit))
10867 Fset_quit_char (quit);
10868 return Qnil;
10871 DEFUN ("current-input-mode", Fcurrent_input_mode, Scurrent_input_mode, 0, 0, 0,
10872 doc: /* Return information about the way Emacs currently reads keyboard input.
10873 The value is a list of the form (INTERRUPT FLOW META QUIT), where
10874 INTERRUPT is non-nil if Emacs is using interrupt-driven input; if
10875 nil, Emacs is using CBREAK mode.
10876 FLOW is non-nil if Emacs uses ^S/^Q flow control for output to the
10877 terminal; this does not apply if Emacs uses interrupt-driven input.
10878 META is t if accepting 8-bit input with 8th bit as Meta flag.
10879 META nil means ignoring the top bit, on the assumption it is parity.
10880 META is neither t nor nil if accepting 8-bit input and using
10881 all 8 bits as the character code.
10882 QUIT is the character Emacs currently uses to quit.
10883 The elements of this list correspond to the arguments of
10884 `set-input-mode'. */)
10885 (void)
10887 Lisp_Object val[4];
10888 struct frame *sf = XFRAME (selected_frame);
10890 val[0] = interrupt_input ? Qt : Qnil;
10891 if (FRAME_TERMCAP_P (sf) || FRAME_MSDOS_P (sf))
10893 val[1] = FRAME_TTY (sf)->flow_control ? Qt : Qnil;
10894 val[2] = (FRAME_TTY (sf)->meta_key == 2
10895 ? make_number (0)
10896 : (CURTTY ()->meta_key == 1 ? Qt : Qnil));
10898 else
10900 val[1] = Qnil;
10901 val[2] = Qt;
10903 XSETFASTINT (val[3], quit_char);
10905 return Flist (ARRAYELTS (val), val);
10908 DEFUN ("posn-at-x-y", Fposn_at_x_y, Sposn_at_x_y, 2, 4, 0,
10909 doc: /* Return position information for pixel coordinates X and Y.
10910 By default, X and Y are relative to text area of the selected window.
10911 Optional third arg FRAME-OR-WINDOW non-nil specifies frame or window.
10912 If optional fourth arg WHOLE is non-nil, X is relative to the left
10913 edge of the window.
10915 The return value is similar to a mouse click position:
10916 (WINDOW AREA-OR-POS (X . Y) TIMESTAMP OBJECT POS (COL . ROW)
10917 IMAGE (DX . DY) (WIDTH . HEIGHT))
10918 The `posn-' functions access elements of such lists. */)
10919 (Lisp_Object x, Lisp_Object y, Lisp_Object frame_or_window, Lisp_Object whole)
10921 CHECK_NATNUM (x);
10922 CHECK_NATNUM (y);
10924 if (NILP (frame_or_window))
10925 frame_or_window = selected_window;
10927 if (WINDOWP (frame_or_window))
10929 struct window *w = decode_live_window (frame_or_window);
10931 XSETINT (x, (XINT (x)
10932 + WINDOW_LEFT_EDGE_X (w)
10933 + (NILP (whole)
10934 ? window_box_left_offset (w, TEXT_AREA)
10935 : 0)));
10936 XSETINT (y, WINDOW_TO_FRAME_PIXEL_Y (w, XINT (y)));
10937 frame_or_window = w->frame;
10940 CHECK_LIVE_FRAME (frame_or_window);
10942 return make_lispy_position (XFRAME (frame_or_window), x, y, 0);
10945 DEFUN ("posn-at-point", Fposn_at_point, Sposn_at_point, 0, 2, 0,
10946 doc: /* Return position information for buffer POS in WINDOW.
10947 POS defaults to point in WINDOW; WINDOW defaults to the selected window.
10949 Return nil if position is not visible in window. Otherwise,
10950 the return value is similar to that returned by `event-start' for
10951 a mouse click at the upper left corner of the glyph corresponding
10952 to the given buffer position:
10953 (WINDOW AREA-OR-POS (X . Y) TIMESTAMP OBJECT POS (COL . ROW)
10954 IMAGE (DX . DY) (WIDTH . HEIGHT))
10955 The `posn-' functions access elements of such lists. */)
10956 (Lisp_Object pos, Lisp_Object window)
10958 Lisp_Object tem;
10960 if (NILP (window))
10961 window = selected_window;
10963 tem = Fpos_visible_in_window_p (pos, window, Qt);
10964 if (!NILP (tem))
10966 Lisp_Object x = XCAR (tem);
10967 Lisp_Object y = XCAR (XCDR (tem));
10969 /* Point invisible due to hscrolling? */
10970 if (XINT (x) < 0)
10971 return Qnil;
10972 tem = Fposn_at_x_y (x, y, window, Qnil);
10975 return tem;
10978 /* Set up a new kboard object with reasonable initial values.
10979 TYPE is a window system for which this keyboard is used. */
10981 static void
10982 init_kboard (KBOARD *kb, Lisp_Object type)
10984 kset_overriding_terminal_local_map (kb, Qnil);
10985 kset_last_command (kb, Qnil);
10986 kset_real_last_command (kb, Qnil);
10987 kset_keyboard_translate_table (kb, Qnil);
10988 kset_last_repeatable_command (kb, Qnil);
10989 kset_prefix_arg (kb, Qnil);
10990 kset_last_prefix_arg (kb, Qnil);
10991 kset_kbd_queue (kb, Qnil);
10992 kb->kbd_queue_has_data = 0;
10993 kb->immediate_echo = 0;
10994 kset_echo_string (kb, Qnil);
10995 kb->echo_after_prompt = -1;
10996 kb->kbd_macro_buffer = 0;
10997 kb->kbd_macro_bufsize = 0;
10998 kset_defining_kbd_macro (kb, Qnil);
10999 kset_last_kbd_macro (kb, Qnil);
11000 kb->reference_count = 0;
11001 kset_system_key_alist (kb, Qnil);
11002 kset_system_key_syms (kb, Qnil);
11003 kset_window_system (kb, type);
11004 kset_input_decode_map (kb, Fmake_sparse_keymap (Qnil));
11005 kset_local_function_key_map (kb, Fmake_sparse_keymap (Qnil));
11006 Fset_keymap_parent (KVAR (kb, Vlocal_function_key_map), Vfunction_key_map);
11007 kset_default_minibuffer_frame (kb, Qnil);
11010 /* Allocate and basically initialize keyboard
11011 object to use with window system TYPE. */
11013 KBOARD *
11014 allocate_kboard (Lisp_Object type)
11016 KBOARD *kb = xmalloc (sizeof *kb);
11018 init_kboard (kb, type);
11019 kb->next_kboard = all_kboards;
11020 all_kboards = kb;
11021 return kb;
11025 * Destroy the contents of a kboard object, but not the object itself.
11026 * We use this just before deleting it, or if we're going to initialize
11027 * it a second time.
11029 static void
11030 wipe_kboard (KBOARD *kb)
11032 xfree (kb->kbd_macro_buffer);
11035 /* Free KB and memory referenced from it. */
11037 void
11038 delete_kboard (KBOARD *kb)
11040 KBOARD **kbp;
11042 for (kbp = &all_kboards; *kbp != kb; kbp = &(*kbp)->next_kboard)
11043 if (*kbp == NULL)
11044 emacs_abort ();
11045 *kbp = kb->next_kboard;
11047 /* Prevent a dangling reference to KB. */
11048 if (kb == current_kboard
11049 && FRAMEP (selected_frame)
11050 && FRAME_LIVE_P (XFRAME (selected_frame)))
11052 current_kboard = FRAME_KBOARD (XFRAME (selected_frame));
11053 single_kboard = 0;
11054 if (current_kboard == kb)
11055 emacs_abort ();
11058 wipe_kboard (kb);
11059 xfree (kb);
11062 void
11063 init_keyboard (void)
11065 /* This is correct before outermost invocation of the editor loop. */
11066 command_loop_level = -1;
11067 immediate_quit = 0;
11068 quit_char = Ctl ('g');
11069 Vunread_command_events = Qnil;
11070 timer_idleness_start_time = invalid_timespec ();
11071 total_keys = 0;
11072 recent_keys_index = 0;
11073 kbd_fetch_ptr = kbd_buffer;
11074 kbd_store_ptr = kbd_buffer;
11075 do_mouse_tracking = Qnil;
11076 input_pending = 0;
11077 interrupt_input_blocked = 0;
11078 pending_signals = 0;
11080 /* This means that command_loop_1 won't try to select anything the first
11081 time through. */
11082 internal_last_event_frame = Qnil;
11083 Vlast_event_frame = internal_last_event_frame;
11085 current_kboard = initial_kboard;
11086 /* Re-initialize the keyboard again. */
11087 wipe_kboard (current_kboard);
11088 /* A value of nil for Vwindow_system normally means a tty, but we also use
11089 it for the initial terminal since there is no window system there. */
11090 init_kboard (current_kboard, Qnil);
11092 if (!noninteractive)
11094 /* Before multi-tty support, these handlers used to be installed
11095 only if the current session was a tty session. Now an Emacs
11096 session may have multiple display types, so we always handle
11097 SIGINT. There is special code in handle_interrupt_signal to exit
11098 Emacs on SIGINT when there are no termcap frames on the
11099 controlling terminal. */
11100 struct sigaction action;
11101 emacs_sigaction_init (&action, deliver_interrupt_signal);
11102 sigaction (SIGINT, &action, 0);
11103 #ifndef DOS_NT
11104 /* For systems with SysV TERMIO, C-g is set up for both SIGINT and
11105 SIGQUIT and we can't tell which one it will give us. */
11106 sigaction (SIGQUIT, &action, 0);
11107 #endif /* not DOS_NT */
11109 #ifdef USABLE_SIGIO
11110 if (!noninteractive)
11112 struct sigaction action;
11113 emacs_sigaction_init (&action, deliver_input_available_signal);
11114 sigaction (SIGIO, &action, 0);
11116 #endif
11118 /* Use interrupt input by default, if it works and noninterrupt input
11119 has deficiencies. */
11121 #ifdef INTERRUPT_INPUT
11122 interrupt_input = 1;
11123 #else
11124 interrupt_input = 0;
11125 #endif
11127 pthread_sigmask (SIG_SETMASK, &empty_mask, 0);
11128 dribble = 0;
11130 if (keyboard_init_hook)
11131 (*keyboard_init_hook) ();
11133 #ifdef POLL_FOR_INPUT
11134 poll_timer = NULL;
11135 poll_suppress_count = 1;
11136 start_polling ();
11137 #endif
11140 /* This type's only use is in syms_of_keyboard, to initialize the
11141 event header symbols and put properties on them. */
11142 struct event_head {
11143 Lisp_Object *var;
11144 const char *name;
11145 Lisp_Object *kind;
11148 static const struct event_head head_table[] = {
11149 {&Qmouse_movement, "mouse-movement", &Qmouse_movement},
11150 {&Qscroll_bar_movement, "scroll-bar-movement", &Qmouse_movement},
11151 {&Qswitch_frame, "switch-frame", &Qswitch_frame},
11152 {&Qfocus_in, "focus-in", &Qfocus_in},
11153 {&Qfocus_out, "focus-out", &Qfocus_out},
11154 {&Qdelete_frame, "delete-frame", &Qdelete_frame},
11155 {&Qiconify_frame, "iconify-frame", &Qiconify_frame},
11156 {&Qmake_frame_visible, "make-frame-visible", &Qmake_frame_visible},
11157 /* `select-window' should be handled just like `switch-frame'
11158 in read_key_sequence. */
11159 {&Qselect_window, "select-window", &Qswitch_frame}
11162 void
11163 syms_of_keyboard (void)
11165 pending_funcalls = Qnil;
11166 staticpro (&pending_funcalls);
11168 Vlispy_mouse_stem = build_pure_c_string ("mouse");
11169 staticpro (&Vlispy_mouse_stem);
11171 regular_top_level_message = build_pure_c_string ("Back to top level");
11172 #ifdef HAVE_STACK_OVERFLOW_HANDLING
11173 recover_top_level_message
11174 = build_pure_c_string ("Re-entering top level after C stack overflow");
11175 #endif
11176 DEFVAR_LISP ("internal--top-level-message", Vinternal__top_level_message,
11177 doc: /* Message displayed by `normal-top-level'. */);
11178 Vinternal__top_level_message = regular_top_level_message;
11180 /* Tool-bars. */
11181 DEFSYM (QCimage, ":image");
11182 DEFSYM (Qhelp_echo, "help-echo");
11183 DEFSYM (QCrtl, ":rtl");
11185 staticpro (&item_properties);
11186 item_properties = Qnil;
11188 staticpro (&tool_bar_item_properties);
11189 tool_bar_item_properties = Qnil;
11190 staticpro (&tool_bar_items_vector);
11191 tool_bar_items_vector = Qnil;
11193 DEFSYM (Qtimer_event_handler, "timer-event-handler");
11194 DEFSYM (Qdisabled_command_function, "disabled-command-function");
11195 DEFSYM (Qself_insert_command, "self-insert-command");
11196 DEFSYM (Qforward_char, "forward-char");
11197 DEFSYM (Qbackward_char, "backward-char");
11198 DEFSYM (Qdisabled, "disabled");
11199 DEFSYM (Qundefined, "undefined");
11200 DEFSYM (Qpre_command_hook, "pre-command-hook");
11201 DEFSYM (Qpost_command_hook, "post-command-hook");
11202 DEFSYM (Qdeferred_action_function, "deferred-action-function");
11203 DEFSYM (Qdelayed_warnings_hook, "delayed-warnings-hook");
11204 DEFSYM (Qfunction_key, "function-key");
11205 DEFSYM (Qmouse_click, "mouse-click");
11206 DEFSYM (Qdrag_n_drop, "drag-n-drop");
11207 DEFSYM (Qsave_session, "save-session");
11208 DEFSYM (Qconfig_changed_event, "config-changed-event");
11209 DEFSYM (Qmenu_enable, "menu-enable");
11211 #ifdef HAVE_NTGUI
11212 DEFSYM (Qlanguage_change, "language-change");
11213 #endif
11215 #ifdef HAVE_DBUS
11216 DEFSYM (Qdbus_event, "dbus-event");
11217 #endif
11219 #ifdef HAVE_XWIDGETS
11220 Qxwidget_event = intern ("xwidget-event");
11221 staticpro (&Qxwidget_event);
11222 #endif /* HAVE_XWIDGETS */
11223 #ifdef USE_FILE_NOTIFY
11224 DEFSYM (Qfile_notify, "file-notify");
11225 #endif /* USE_FILE_NOTIFY */
11227 DEFSYM (QCenable, ":enable");
11228 DEFSYM (QCvisible, ":visible");
11229 DEFSYM (QChelp, ":help");
11230 DEFSYM (QCfilter, ":filter");
11231 DEFSYM (QCbutton, ":button");
11232 DEFSYM (QCkeys, ":keys");
11233 DEFSYM (QCkey_sequence, ":key-sequence");
11234 DEFSYM (QCtoggle, ":toggle");
11235 DEFSYM (QCradio, ":radio");
11236 DEFSYM (QClabel, ":label");
11237 DEFSYM (QCvert_only, ":vert-only");
11239 DEFSYM (Qmode_line, "mode-line");
11240 DEFSYM (Qvertical_line, "vertical-line");
11241 DEFSYM (Qmenu_bar, "menu-bar");
11242 DEFSYM (Qright_divider, "right-divider");
11243 DEFSYM (Qbottom_divider, "bottom-divider");
11245 DEFSYM (Qmouse_fixup_help_message, "mouse-fixup-help-message");
11247 DEFSYM (Qabove_handle, "above-handle");
11248 DEFSYM (Qhandle, "handle");
11249 DEFSYM (Qbelow_handle, "below-handle");
11250 DEFSYM (Qup, "up");
11251 DEFSYM (Qdown, "down");
11252 DEFSYM (Qtop, "top");
11253 DEFSYM (Qbottom, "bottom");
11254 DEFSYM (Qend_scroll, "end-scroll");
11255 DEFSYM (Qratio, "ratio");
11256 DEFSYM (Qbefore_handle, "before-handle");
11257 DEFSYM (Qhorizontal_handle, "horizontal-handle");
11258 DEFSYM (Qafter_handle, "after-handle");
11259 DEFSYM (Qleft, "left");
11260 DEFSYM (Qright, "right");
11261 DEFSYM (Qleftmost, "leftmost");
11262 DEFSYM (Qrightmost, "rightmost");
11264 DEFSYM (Qevent_kind, "event-kind");
11265 DEFSYM (Qevent_symbol_elements, "event-symbol-elements");
11266 DEFSYM (Qevent_symbol_element_mask, "event-symbol-element-mask");
11267 DEFSYM (Qmodifier_cache, "modifier-cache");
11269 DEFSYM (Qrecompute_lucid_menubar, "recompute-lucid-menubar");
11270 DEFSYM (Qactivate_menubar_hook, "activate-menubar-hook");
11272 DEFSYM (Qpolling_period, "polling-period");
11274 DEFSYM (Qgui_set_selection, "gui-set-selection");
11275 DEFSYM (QPRIMARY, "PRIMARY");
11276 DEFSYM (Qhandle_switch_frame, "handle-switch-frame");
11277 DEFSYM (Qhandle_select_window, "handle-select-window");
11279 DEFSYM (Qinput_method_function, "input-method-function");
11280 DEFSYM (Qinput_method_exit_on_first_char, "input-method-exit-on-first-char");
11281 DEFSYM (Qinput_method_use_echo_area, "input-method-use-echo-area");
11283 DEFSYM (Qhelp_form_show, "help-form-show");
11285 DEFSYM (Qecho_keystrokes, "echo-keystrokes");
11287 Fset (Qinput_method_exit_on_first_char, Qnil);
11288 Fset (Qinput_method_use_echo_area, Qnil);
11291 int i;
11292 int len = ARRAYELTS (head_table);
11294 for (i = 0; i < len; i++)
11296 const struct event_head *p = &head_table[i];
11297 *p->var = intern_c_string (p->name);
11298 staticpro (p->var);
11299 Fput (*p->var, Qevent_kind, *p->kind);
11300 Fput (*p->var, Qevent_symbol_elements, list1 (*p->var));
11304 button_down_location = Fmake_vector (make_number (5), Qnil);
11305 staticpro (&button_down_location);
11306 mouse_syms = Fmake_vector (make_number (5), Qnil);
11307 staticpro (&mouse_syms);
11308 wheel_syms = Fmake_vector (make_number (ARRAYELTS (lispy_wheel_names)),
11309 Qnil);
11310 staticpro (&wheel_syms);
11313 int i;
11314 int len = ARRAYELTS (modifier_names);
11316 modifier_symbols = Fmake_vector (make_number (len), Qnil);
11317 for (i = 0; i < len; i++)
11318 if (modifier_names[i])
11319 ASET (modifier_symbols, i, intern_c_string (modifier_names[i]));
11320 staticpro (&modifier_symbols);
11323 recent_keys = Fmake_vector (make_number (NUM_RECENT_KEYS), Qnil);
11324 staticpro (&recent_keys);
11326 this_command_keys = Fmake_vector (make_number (40), Qnil);
11327 staticpro (&this_command_keys);
11329 raw_keybuf = Fmake_vector (make_number (30), Qnil);
11330 staticpro (&raw_keybuf);
11332 DEFSYM (Qcommand_execute, "command-execute");
11334 accent_key_syms = Qnil;
11335 staticpro (&accent_key_syms);
11337 func_key_syms = Qnil;
11338 staticpro (&func_key_syms);
11340 drag_n_drop_syms = Qnil;
11341 staticpro (&drag_n_drop_syms);
11343 unread_switch_frame = Qnil;
11344 staticpro (&unread_switch_frame);
11346 internal_last_event_frame = Qnil;
11347 staticpro (&internal_last_event_frame);
11349 read_key_sequence_cmd = Qnil;
11350 staticpro (&read_key_sequence_cmd);
11351 read_key_sequence_remapped = Qnil;
11352 staticpro (&read_key_sequence_remapped);
11354 menu_bar_one_keymap_changed_items = Qnil;
11355 staticpro (&menu_bar_one_keymap_changed_items);
11357 menu_bar_items_vector = Qnil;
11358 staticpro (&menu_bar_items_vector);
11360 help_form_saved_window_configs = Qnil;
11361 staticpro (&help_form_saved_window_configs);
11363 defsubr (&Scurrent_idle_time);
11364 defsubr (&Sevent_symbol_parse_modifiers);
11365 defsubr (&Sevent_convert_list);
11366 defsubr (&Sread_key_sequence);
11367 defsubr (&Sread_key_sequence_vector);
11368 defsubr (&Srecursive_edit);
11369 defsubr (&Strack_mouse);
11370 defsubr (&Sinput_pending_p);
11371 defsubr (&Srecent_keys);
11372 defsubr (&Sthis_command_keys);
11373 defsubr (&Sthis_command_keys_vector);
11374 defsubr (&Sthis_single_command_keys);
11375 defsubr (&Sthis_single_command_raw_keys);
11376 defsubr (&Sreset_this_command_lengths);
11377 defsubr (&Sclear_this_command_keys);
11378 defsubr (&Ssuspend_emacs);
11379 defsubr (&Sabort_recursive_edit);
11380 defsubr (&Sexit_recursive_edit);
11381 defsubr (&Srecursion_depth);
11382 defsubr (&Scommand_error_default_function);
11383 defsubr (&Stop_level);
11384 defsubr (&Sdiscard_input);
11385 defsubr (&Sopen_dribble_file);
11386 defsubr (&Sset_input_interrupt_mode);
11387 defsubr (&Sset_output_flow_control);
11388 defsubr (&Sset_input_meta_mode);
11389 defsubr (&Sset_quit_char);
11390 defsubr (&Sset_input_mode);
11391 defsubr (&Scurrent_input_mode);
11392 defsubr (&Sposn_at_point);
11393 defsubr (&Sposn_at_x_y);
11395 DEFVAR_LISP ("last-command-event", last_command_event,
11396 doc: /* Last input event that was part of a command. */);
11398 DEFVAR_LISP ("last-nonmenu-event", last_nonmenu_event,
11399 doc: /* Last input event in a command, except for mouse menu events.
11400 Mouse menus give back keys that don't look like mouse events;
11401 this variable holds the actual mouse event that led to the menu,
11402 so that you can determine whether the command was run by mouse or not. */);
11404 DEFVAR_LISP ("last-input-event", last_input_event,
11405 doc: /* Last input event. */);
11407 DEFVAR_LISP ("unread-command-events", Vunread_command_events,
11408 doc: /* List of events to be read as the command input.
11409 These events are processed first, before actual keyboard input.
11410 Events read from this list are not normally added to `this-command-keys',
11411 as they will already have been added once as they were read for the first time.
11412 An element of the form (t . EVENT) forces EVENT to be added to that list. */);
11413 Vunread_command_events = Qnil;
11415 DEFVAR_LISP ("unread-post-input-method-events", Vunread_post_input_method_events,
11416 doc: /* List of events to be processed as input by input methods.
11417 These events are processed before `unread-command-events'
11418 and actual keyboard input, but are not given to `input-method-function'. */);
11419 Vunread_post_input_method_events = Qnil;
11421 DEFVAR_LISP ("unread-input-method-events", Vunread_input_method_events,
11422 doc: /* List of events to be processed as input by input methods.
11423 These events are processed after `unread-command-events', but
11424 before actual keyboard input.
11425 If there's an active input method, the events are given to
11426 `input-method-function'. */);
11427 Vunread_input_method_events = Qnil;
11429 DEFVAR_LISP ("meta-prefix-char", meta_prefix_char,
11430 doc: /* Meta-prefix character code.
11431 Meta-foo as command input turns into this character followed by foo. */);
11432 XSETINT (meta_prefix_char, 033);
11434 DEFVAR_KBOARD ("last-command", Vlast_command,
11435 doc: /* The last command executed.
11436 Normally a symbol with a function definition, but can be whatever was found
11437 in the keymap, or whatever the variable `this-command' was set to by that
11438 command.
11440 The value `mode-exit' is special; it means that the previous command
11441 read an event that told it to exit, and it did so and unread that event.
11442 In other words, the present command is the event that made the previous
11443 command exit.
11445 The value `kill-region' is special; it means that the previous command
11446 was a kill command.
11448 `last-command' has a separate binding for each terminal device.
11449 See Info node `(elisp)Multiple Terminals'. */);
11451 DEFVAR_KBOARD ("real-last-command", Vreal_last_command,
11452 doc: /* Same as `last-command', but never altered by Lisp code.
11453 Taken from the previous value of `real-this-command'. */);
11455 DEFVAR_KBOARD ("last-repeatable-command", Vlast_repeatable_command,
11456 doc: /* Last command that may be repeated.
11457 The last command executed that was not bound to an input event.
11458 This is the command `repeat' will try to repeat.
11459 Taken from a previous value of `real-this-command'. */);
11461 DEFVAR_LISP ("this-command", Vthis_command,
11462 doc: /* The command now being executed.
11463 The command can set this variable; whatever is put here
11464 will be in `last-command' during the following command. */);
11465 Vthis_command = Qnil;
11467 DEFVAR_LISP ("real-this-command", Vreal_this_command,
11468 doc: /* This is like `this-command', except that commands should never modify it. */);
11469 Vreal_this_command = Qnil;
11471 DEFVAR_LISP ("this-command-keys-shift-translated",
11472 Vthis_command_keys_shift_translated,
11473 doc: /* Non-nil if the key sequence activating this command was shift-translated.
11474 Shift-translation occurs when there is no binding for the key sequence
11475 as entered, but a binding was found by changing an upper-case letter
11476 to lower-case, or a shifted function key to an unshifted one. */);
11477 Vthis_command_keys_shift_translated = Qnil;
11479 DEFVAR_LISP ("this-original-command", Vthis_original_command,
11480 doc: /* The command bound to the current key sequence before remapping.
11481 It equals `this-command' if the original command was not remapped through
11482 any of the active keymaps. Otherwise, the value of `this-command' is the
11483 result of looking up the original command in the active keymaps. */);
11484 Vthis_original_command = Qnil;
11486 DEFVAR_INT ("auto-save-interval", auto_save_interval,
11487 doc: /* Number of input events between auto-saves.
11488 Zero means disable autosaving due to number of characters typed. */);
11489 auto_save_interval = 300;
11491 DEFVAR_LISP ("auto-save-timeout", Vauto_save_timeout,
11492 doc: /* Number of seconds idle time before auto-save.
11493 Zero or nil means disable auto-saving due to idleness.
11494 After auto-saving due to this many seconds of idle time,
11495 Emacs also does a garbage collection if that seems to be warranted. */);
11496 XSETFASTINT (Vauto_save_timeout, 30);
11498 DEFVAR_LISP ("echo-keystrokes", Vecho_keystrokes,
11499 doc: /* Nonzero means echo unfinished commands after this many seconds of pause.
11500 The value may be integer or floating point.
11501 If the value is zero, don't echo at all. */);
11502 Vecho_keystrokes = make_number (1);
11504 DEFVAR_INT ("polling-period", polling_period,
11505 doc: /* Interval between polling for input during Lisp execution.
11506 The reason for polling is to make C-g work to stop a running program.
11507 Polling is needed only when using X windows and SIGIO does not work.
11508 Polling is automatically disabled in all other cases. */);
11509 polling_period = 2;
11511 DEFVAR_LISP ("double-click-time", Vdouble_click_time,
11512 doc: /* Maximum time between mouse clicks to make a double-click.
11513 Measured in milliseconds. The value nil means disable double-click
11514 recognition; t means double-clicks have no time limit and are detected
11515 by position only. */);
11516 Vdouble_click_time = make_number (500);
11518 DEFVAR_INT ("double-click-fuzz", double_click_fuzz,
11519 doc: /* Maximum mouse movement between clicks to make a double-click.
11520 On window-system frames, value is the number of pixels the mouse may have
11521 moved horizontally or vertically between two clicks to make a double-click.
11522 On non window-system frames, value is interpreted in units of 1/8 characters
11523 instead of pixels.
11525 This variable is also the threshold for motion of the mouse
11526 to count as a drag. */);
11527 double_click_fuzz = 3;
11529 DEFVAR_INT ("num-input-keys", num_input_keys,
11530 doc: /* Number of complete key sequences read as input so far.
11531 This includes key sequences read from keyboard macros.
11532 The number is effectively the number of interactive command invocations. */);
11533 num_input_keys = 0;
11535 DEFVAR_INT ("num-nonmacro-input-events", num_nonmacro_input_events,
11536 doc: /* Number of input events read from the keyboard so far.
11537 This does not include events generated by keyboard macros. */);
11538 num_nonmacro_input_events = 0;
11540 DEFVAR_LISP ("last-event-frame", Vlast_event_frame,
11541 doc: /* The frame in which the most recently read event occurred.
11542 If the last event came from a keyboard macro, this is set to `macro'. */);
11543 Vlast_event_frame = Qnil;
11545 /* This variable is set up in sysdep.c. */
11546 DEFVAR_LISP ("tty-erase-char", Vtty_erase_char,
11547 doc: /* The ERASE character as set by the user with stty. */);
11549 DEFVAR_LISP ("help-char", Vhelp_char,
11550 doc: /* Character to recognize as meaning Help.
11551 When it is read, do `(eval help-form)', and display result if it's a string.
11552 If the value of `help-form' is nil, this char can be read normally. */);
11553 XSETINT (Vhelp_char, Ctl ('H'));
11555 DEFVAR_LISP ("help-event-list", Vhelp_event_list,
11556 doc: /* List of input events to recognize as meaning Help.
11557 These work just like the value of `help-char' (see that). */);
11558 Vhelp_event_list = Qnil;
11560 DEFVAR_LISP ("help-form", Vhelp_form,
11561 doc: /* Form to execute when character `help-char' is read.
11562 If the form returns a string, that string is displayed.
11563 If `help-form' is nil, the help char is not recognized. */);
11564 Vhelp_form = Qnil;
11566 DEFVAR_LISP ("prefix-help-command", Vprefix_help_command,
11567 doc: /* Command to run when `help-char' character follows a prefix key.
11568 This command is used only when there is no actual binding
11569 for that character after that prefix key. */);
11570 Vprefix_help_command = Qnil;
11572 DEFVAR_LISP ("top-level", Vtop_level,
11573 doc: /* Form to evaluate when Emacs starts up.
11574 Useful to set before you dump a modified Emacs. */);
11575 Vtop_level = Qnil;
11577 DEFVAR_KBOARD ("keyboard-translate-table", Vkeyboard_translate_table,
11578 doc: /* Translate table for local keyboard input, or nil.
11579 If non-nil, the value should be a char-table. Each character read
11580 from the keyboard is looked up in this char-table. If the value found
11581 there is non-nil, then it is used instead of the actual input character.
11583 The value can also be a string or vector, but this is considered obsolete.
11584 If it is a string or vector of length N, character codes N and up are left
11585 untranslated. In a vector, an element which is nil means "no translation".
11587 This is applied to the characters supplied to input methods, not their
11588 output. See also `translation-table-for-input'.
11590 This variable has a separate binding for each terminal.
11591 See Info node `(elisp)Multiple Terminals'. */);
11593 DEFVAR_BOOL ("cannot-suspend", cannot_suspend,
11594 doc: /* Non-nil means to always spawn a subshell instead of suspending.
11595 \(Even if the operating system has support for stopping a process.\) */);
11596 cannot_suspend = 0;
11598 DEFVAR_BOOL ("menu-prompting", menu_prompting,
11599 doc: /* Non-nil means prompt with menus when appropriate.
11600 This is done when reading from a keymap that has a prompt string,
11601 for elements that have prompt strings.
11602 The menu is displayed on the screen
11603 if X menus were enabled at configuration
11604 time and the previous event was a mouse click prefix key.
11605 Otherwise, menu prompting uses the echo area. */);
11606 menu_prompting = 1;
11608 DEFVAR_LISP ("menu-prompt-more-char", menu_prompt_more_char,
11609 doc: /* Character to see next line of menu prompt.
11610 Type this character while in a menu prompt to rotate around the lines of it. */);
11611 XSETINT (menu_prompt_more_char, ' ');
11613 DEFVAR_INT ("extra-keyboard-modifiers", extra_keyboard_modifiers,
11614 doc: /* A mask of additional modifier keys to use with every keyboard character.
11615 Emacs applies the modifiers of the character stored here to each keyboard
11616 character it reads. For example, after evaluating the expression
11617 (setq extra-keyboard-modifiers ?\\C-x)
11618 all input characters will have the control modifier applied to them.
11620 Note that the character ?\\C-@, equivalent to the integer zero, does
11621 not count as a control character; rather, it counts as a character
11622 with no modifiers; thus, setting `extra-keyboard-modifiers' to zero
11623 cancels any modification. */);
11624 extra_keyboard_modifiers = 0;
11626 DEFVAR_LISP ("deactivate-mark", Vdeactivate_mark,
11627 doc: /* If an editing command sets this to t, deactivate the mark afterward.
11628 The command loop sets this to nil before each command,
11629 and tests the value when the command returns.
11630 Buffer modification stores t in this variable. */);
11631 Vdeactivate_mark = Qnil;
11632 DEFSYM (Qdeactivate_mark, "deactivate-mark");
11633 Fmake_variable_buffer_local (Qdeactivate_mark);
11635 DEFVAR_LISP ("pre-command-hook", Vpre_command_hook,
11636 doc: /* Normal hook run before each command is executed.
11637 If an unhandled error happens in running this hook,
11638 the function in which the error occurred is unconditionally removed, since
11639 otherwise the error might happen repeatedly and make Emacs nonfunctional. */);
11640 Vpre_command_hook = Qnil;
11642 DEFVAR_LISP ("post-command-hook", Vpost_command_hook,
11643 doc: /* Normal hook run after each command is executed.
11644 If an unhandled error happens in running this hook,
11645 the function in which the error occurred is unconditionally removed, since
11646 otherwise the error might happen repeatedly and make Emacs nonfunctional. */);
11647 Vpost_command_hook = Qnil;
11649 #if 0
11650 DEFVAR_LISP ("echo-area-clear-hook", ...,
11651 doc: /* Normal hook run when clearing the echo area. */);
11652 #endif
11653 DEFSYM (Qecho_area_clear_hook, "echo-area-clear-hook");
11654 Fset (Qecho_area_clear_hook, Qnil);
11656 DEFVAR_LISP ("lucid-menu-bar-dirty-flag", Vlucid_menu_bar_dirty_flag,
11657 doc: /* Non-nil means menu bar, specified Lucid style, needs to be recomputed. */);
11658 Vlucid_menu_bar_dirty_flag = Qnil;
11660 DEFVAR_LISP ("menu-bar-final-items", Vmenu_bar_final_items,
11661 doc: /* List of menu bar items to move to the end of the menu bar.
11662 The elements of the list are event types that may have menu bar bindings. */);
11663 Vmenu_bar_final_items = Qnil;
11665 DEFVAR_LISP ("tool-bar-separator-image-expression", Vtool_bar_separator_image_expression,
11666 doc: /* Expression evaluating to the image spec for a tool-bar separator.
11667 This is used internally by graphical displays that do not render
11668 tool-bar separators natively. Otherwise it is unused (e.g. on GTK). */);
11669 Vtool_bar_separator_image_expression = Qnil;
11671 DEFVAR_KBOARD ("overriding-terminal-local-map",
11672 Voverriding_terminal_local_map,
11673 doc: /* Per-terminal keymap that takes precedence over all other keymaps.
11674 This variable is intended to let commands such as `universal-argument'
11675 set up a different keymap for reading the next command.
11677 `overriding-terminal-local-map' has a separate binding for each
11678 terminal device. See Info node `(elisp)Multiple Terminals'. */);
11680 DEFVAR_LISP ("overriding-local-map", Voverriding_local_map,
11681 doc: /* Keymap that replaces (overrides) local keymaps.
11682 If this variable is non-nil, Emacs looks up key bindings in this
11683 keymap INSTEAD OF the keymap char property, minor mode maps, and the
11684 buffer's local map. Hence, the only active keymaps would be
11685 `overriding-terminal-local-map', this keymap, and `global-keymap', in
11686 order of precedence. */);
11687 Voverriding_local_map = Qnil;
11689 DEFVAR_LISP ("overriding-local-map-menu-flag", Voverriding_local_map_menu_flag,
11690 doc: /* Non-nil means `overriding-local-map' applies to the menu bar.
11691 Otherwise, the menu bar continues to reflect the buffer's local map
11692 and the minor mode maps regardless of `overriding-local-map'. */);
11693 Voverriding_local_map_menu_flag = Qnil;
11695 DEFVAR_LISP ("special-event-map", Vspecial_event_map,
11696 doc: /* Keymap defining bindings for special events to execute at low level. */);
11697 Vspecial_event_map = list1 (intern_c_string ("keymap"));
11699 DEFVAR_LISP ("track-mouse", do_mouse_tracking,
11700 doc: /* Non-nil means generate motion events for mouse motion. */);
11702 DEFVAR_KBOARD ("system-key-alist", Vsystem_key_alist,
11703 doc: /* Alist of system-specific X windows key symbols.
11704 Each element should have the form (N . SYMBOL) where N is the
11705 numeric keysym code (sans the \"system-specific\" bit 1<<28)
11706 and SYMBOL is its name.
11708 `system-key-alist' has a separate binding for each terminal device.
11709 See Info node `(elisp)Multiple Terminals'. */);
11711 DEFVAR_KBOARD ("local-function-key-map", Vlocal_function_key_map,
11712 doc: /* Keymap that translates key sequences to key sequences during input.
11713 This is used mainly for mapping key sequences into some preferred
11714 key events (symbols).
11716 The `read-key-sequence' function replaces any subsequence bound by
11717 `local-function-key-map' with its binding. More precisely, when the
11718 active keymaps have no binding for the current key sequence but
11719 `local-function-key-map' binds a suffix of the sequence to a vector or
11720 string, `read-key-sequence' replaces the matching suffix with its
11721 binding, and continues with the new sequence.
11723 If the binding is a function, it is called with one argument (the prompt)
11724 and its return value (a key sequence) is used.
11726 The events that come from bindings in `local-function-key-map' are not
11727 themselves looked up in `local-function-key-map'.
11729 For example, suppose `local-function-key-map' binds `ESC O P' to [f1].
11730 Typing `ESC O P' to `read-key-sequence' would return [f1]. Typing
11731 `C-x ESC O P' would return [?\\C-x f1]. If [f1] were a prefix key,
11732 typing `ESC O P x' would return [f1 x].
11734 `local-function-key-map' has a separate binding for each terminal
11735 device. See Info node `(elisp)Multiple Terminals'. If you need to
11736 define a binding on all terminals, change `function-key-map'
11737 instead. Initially, `local-function-key-map' is an empty keymap that
11738 has `function-key-map' as its parent on all terminal devices. */);
11740 DEFVAR_KBOARD ("input-decode-map", Vinput_decode_map,
11741 doc: /* Keymap that decodes input escape sequences.
11742 This is used mainly for mapping ASCII function key sequences into
11743 real Emacs function key events (symbols).
11745 The `read-key-sequence' function replaces any subsequence bound by
11746 `input-decode-map' with its binding. Contrary to `function-key-map',
11747 this map applies its rebinding regardless of the presence of an ordinary
11748 binding. So it is more like `key-translation-map' except that it applies
11749 before `function-key-map' rather than after.
11751 If the binding is a function, it is called with one argument (the prompt)
11752 and its return value (a key sequence) is used.
11754 The events that come from bindings in `input-decode-map' are not
11755 themselves looked up in `input-decode-map'. */);
11757 DEFVAR_LISP ("function-key-map", Vfunction_key_map,
11758 doc: /* The parent keymap of all `local-function-key-map' instances.
11759 Function key definitions that apply to all terminal devices should go
11760 here. If a mapping is defined in both the current
11761 `local-function-key-map' binding and this variable, then the local
11762 definition will take precedence. */);
11763 Vfunction_key_map = Fmake_sparse_keymap (Qnil);
11765 DEFVAR_LISP ("key-translation-map", Vkey_translation_map,
11766 doc: /* Keymap of key translations that can override keymaps.
11767 This keymap works like `input-decode-map', but comes after `function-key-map'.
11768 Another difference is that it is global rather than terminal-local. */);
11769 Vkey_translation_map = Fmake_sparse_keymap (Qnil);
11771 DEFVAR_LISP ("deferred-action-list", Vdeferred_action_list,
11772 doc: /* List of deferred actions to be performed at a later time.
11773 The precise format isn't relevant here; we just check whether it is nil. */);
11774 Vdeferred_action_list = Qnil;
11776 DEFVAR_LISP ("deferred-action-function", Vdeferred_action_function,
11777 doc: /* Function to call to handle deferred actions, after each command.
11778 This function is called with no arguments after each command
11779 whenever `deferred-action-list' is non-nil. */);
11780 Vdeferred_action_function = Qnil;
11782 DEFVAR_LISP ("delayed-warnings-list", Vdelayed_warnings_list,
11783 doc: /* List of warnings to be displayed after this command.
11784 Each element must be a list (TYPE MESSAGE [LEVEL [BUFFER-NAME]]),
11785 as per the args of `display-warning' (which see).
11786 If this variable is non-nil, `delayed-warnings-hook' will be run
11787 immediately after running `post-command-hook'. */);
11788 Vdelayed_warnings_list = Qnil;
11790 DEFVAR_LISP ("timer-list", Vtimer_list,
11791 doc: /* List of active absolute time timers in order of increasing time. */);
11792 Vtimer_list = Qnil;
11794 DEFVAR_LISP ("timer-idle-list", Vtimer_idle_list,
11795 doc: /* List of active idle-time timers in order of increasing time. */);
11796 Vtimer_idle_list = Qnil;
11798 DEFVAR_LISP ("input-method-function", Vinput_method_function,
11799 doc: /* If non-nil, the function that implements the current input method.
11800 It's called with one argument, a printing character that was just read.
11801 \(That means a character with code 040...0176.)
11802 Typically this function uses `read-event' to read additional events.
11803 When it does so, it should first bind `input-method-function' to nil
11804 so it will not be called recursively.
11806 The function should return a list of zero or more events
11807 to be used as input. If it wants to put back some events
11808 to be reconsidered, separately, by the input method,
11809 it can add them to the beginning of `unread-command-events'.
11811 The input method function can find in `input-method-previous-message'
11812 the previous echo area message.
11814 The input method function should refer to the variables
11815 `input-method-use-echo-area' and `input-method-exit-on-first-char'
11816 for guidance on what to do. */);
11817 Vinput_method_function = Qnil;
11819 DEFVAR_LISP ("input-method-previous-message",
11820 Vinput_method_previous_message,
11821 doc: /* When `input-method-function' is called, hold the previous echo area message.
11822 This variable exists because `read-event' clears the echo area
11823 before running the input method. It is nil if there was no message. */);
11824 Vinput_method_previous_message = Qnil;
11826 DEFVAR_LISP ("show-help-function", Vshow_help_function,
11827 doc: /* If non-nil, the function that implements the display of help.
11828 It's called with one argument, the help string to display. */);
11829 Vshow_help_function = Qnil;
11831 DEFVAR_LISP ("disable-point-adjustment", Vdisable_point_adjustment,
11832 doc: /* If non-nil, suppress point adjustment after executing a command.
11834 After a command is executed, if point is moved into a region that has
11835 special properties (e.g. composition, display), we adjust point to
11836 the boundary of the region. But, when a command sets this variable to
11837 non-nil, we suppress the point adjustment.
11839 This variable is set to nil before reading a command, and is checked
11840 just after executing the command. */);
11841 Vdisable_point_adjustment = Qnil;
11843 DEFVAR_LISP ("global-disable-point-adjustment",
11844 Vglobal_disable_point_adjustment,
11845 doc: /* If non-nil, always suppress point adjustment.
11847 The default value is nil, in which case, point adjustment are
11848 suppressed only after special commands that set
11849 `disable-point-adjustment' (which see) to non-nil. */);
11850 Vglobal_disable_point_adjustment = Qnil;
11852 DEFVAR_LISP ("minibuffer-message-timeout", Vminibuffer_message_timeout,
11853 doc: /* How long to display an echo-area message when the minibuffer is active.
11854 If the value is not a number, such messages don't time out. */);
11855 Vminibuffer_message_timeout = make_number (2);
11857 DEFVAR_LISP ("throw-on-input", Vthrow_on_input,
11858 doc: /* If non-nil, any keyboard input throws to this symbol.
11859 The value of that variable is passed to `quit-flag' and later causes a
11860 peculiar kind of quitting. */);
11861 Vthrow_on_input = Qnil;
11863 DEFVAR_LISP ("command-error-function", Vcommand_error_function,
11864 doc: /* Function to output error messages.
11865 Called with three arguments:
11866 - the error data, a list of the form (SIGNALED-CONDITION . SIGNAL-DATA)
11867 such as what `condition-case' would bind its variable to,
11868 - the context (a string which normally goes at the start of the message),
11869 - the Lisp function within which the error was signaled. */);
11870 Vcommand_error_function = intern ("command-error-default-function");
11872 DEFVAR_LISP ("enable-disabled-menus-and-buttons",
11873 Venable_disabled_menus_and_buttons,
11874 doc: /* If non-nil, don't ignore events produced by disabled menu items and tool-bar.
11876 Help functions bind this to allow help on disabled menu items
11877 and tool-bar buttons. */);
11878 Venable_disabled_menus_and_buttons = Qnil;
11880 DEFVAR_LISP ("select-active-regions",
11881 Vselect_active_regions,
11882 doc: /* If non-nil, an active region automatically sets the primary selection.
11883 If the value is `only', only temporarily active regions (usually made
11884 by mouse-dragging or shift-selection) set the window selection.
11886 This takes effect only when Transient Mark mode is enabled. */);
11887 Vselect_active_regions = Qt;
11889 DEFVAR_LISP ("saved-region-selection",
11890 Vsaved_region_selection,
11891 doc: /* Contents of active region prior to buffer modification.
11892 If `select-active-regions' is non-nil, Emacs sets this to the
11893 text in the region before modifying the buffer. The next call to
11894 the function `deactivate-mark' uses this to set the window selection. */);
11895 Vsaved_region_selection = Qnil;
11897 DEFVAR_LISP ("selection-inhibit-update-commands",
11898 Vselection_inhibit_update_commands,
11899 doc: /* List of commands which should not update the selection.
11900 Normally, if `select-active-regions' is non-nil and the mark remains
11901 active after a command (i.e. the mark was not deactivated), the Emacs
11902 command loop sets the selection to the text in the region. However,
11903 if the command is in this list, the selection is not updated. */);
11904 Vselection_inhibit_update_commands
11905 = list2 (Qhandle_switch_frame, Qhandle_select_window);
11907 DEFVAR_LISP ("debug-on-event",
11908 Vdebug_on_event,
11909 doc: /* Enter debugger on this event. When Emacs
11910 receives the special event specified by this variable, it will try to
11911 break into the debugger as soon as possible instead of processing the
11912 event normally through `special-event-map'.
11914 Currently, the only supported values for this
11915 variable are `sigusr1' and `sigusr2'. */);
11916 Vdebug_on_event = intern_c_string ("sigusr2");
11918 /* Create the initial keyboard. Qt means 'unset'. */
11919 initial_kboard = allocate_kboard (Qt);
11922 void
11923 keys_of_keyboard (void)
11925 initial_define_key (global_map, Ctl ('Z'), "suspend-emacs");
11926 initial_define_key (control_x_map, Ctl ('Z'), "suspend-emacs");
11927 initial_define_key (meta_map, Ctl ('C'), "exit-recursive-edit");
11928 initial_define_key (global_map, Ctl (']'), "abort-recursive-edit");
11929 initial_define_key (meta_map, 'x', "execute-extended-command");
11931 initial_define_lispy_key (Vspecial_event_map, "delete-frame",
11932 "handle-delete-frame");
11933 initial_define_lispy_key (Vspecial_event_map, "ns-put-working-text",
11934 "ns-put-working-text");
11935 initial_define_lispy_key (Vspecial_event_map, "ns-unput-working-text",
11936 "ns-unput-working-text");
11937 /* Here we used to use `ignore-event' which would simple set prefix-arg to
11938 current-prefix-arg, as is done in `handle-switch-frame'.
11939 But `handle-switch-frame is not run from the special-map.
11940 Commands from that map are run in a special way that automatically
11941 preserves the prefix-arg. Restoring the prefix arg here is not just
11942 redundant but harmful:
11943 - C-u C-x v =
11944 - current-prefix-arg is set to non-nil, prefix-arg is set to nil.
11945 - after the first prompt, the exit-minibuffer-hook is run which may
11946 iconify a frame and thus push a `iconify-frame' event.
11947 - after running exit-minibuffer-hook, current-prefix-arg is
11948 restored to the non-nil value it had before the prompt.
11949 - we enter the second prompt.
11950 current-prefix-arg is non-nil, prefix-arg is nil.
11951 - before running the first real event, we run the special iconify-frame
11952 event, but we pass the `special' arg to command-execute so
11953 current-prefix-arg and prefix-arg are left untouched.
11954 - here we foolishly copy the non-nil current-prefix-arg to prefix-arg.
11955 - the next key event will have a spuriously non-nil current-prefix-arg. */
11956 initial_define_lispy_key (Vspecial_event_map, "iconify-frame",
11957 "ignore");
11958 initial_define_lispy_key (Vspecial_event_map, "make-frame-visible",
11959 "ignore");
11960 /* Handling it at such a low-level causes read_key_sequence to get
11961 * confused because it doesn't realize that the current_buffer was
11962 * changed by read_char.
11964 * initial_define_lispy_key (Vspecial_event_map, "select-window",
11965 * "handle-select-window"); */
11966 initial_define_lispy_key (Vspecial_event_map, "save-session",
11967 "handle-save-session");
11969 #ifdef HAVE_DBUS
11970 /* Define a special event which is raised for dbus callback
11971 functions. */
11972 initial_define_lispy_key (Vspecial_event_map, "dbus-event",
11973 "dbus-handle-event");
11974 #endif
11976 #ifdef USE_FILE_NOTIFY
11977 /* Define a special event which is raised for notification callback
11978 functions. */
11979 initial_define_lispy_key (Vspecial_event_map, "file-notify",
11980 "file-notify-handle-event");
11981 #endif /* USE_FILE_NOTIFY */
11983 initial_define_lispy_key (Vspecial_event_map, "config-changed-event",
11984 "ignore");
11985 #if defined (WINDOWSNT)
11986 initial_define_lispy_key (Vspecial_event_map, "language-change",
11987 "ignore");
11988 #endif
11989 initial_define_lispy_key (Vspecial_event_map, "focus-in",
11990 "handle-focus-in");
11991 initial_define_lispy_key (Vspecial_event_map, "focus-out",
11992 "handle-focus-out");
11995 /* Mark the pointers in the kboard objects.
11996 Called by Fgarbage_collect. */
11997 void
11998 mark_kboards (void)
12000 KBOARD *kb;
12001 Lisp_Object *p;
12002 for (kb = all_kboards; kb; kb = kb->next_kboard)
12004 if (kb->kbd_macro_buffer)
12005 for (p = kb->kbd_macro_buffer; p < kb->kbd_macro_ptr; p++)
12006 mark_object (*p);
12007 mark_object (KVAR (kb, Voverriding_terminal_local_map));
12008 mark_object (KVAR (kb, Vlast_command));
12009 mark_object (KVAR (kb, Vreal_last_command));
12010 mark_object (KVAR (kb, Vkeyboard_translate_table));
12011 mark_object (KVAR (kb, Vlast_repeatable_command));
12012 mark_object (KVAR (kb, Vprefix_arg));
12013 mark_object (KVAR (kb, Vlast_prefix_arg));
12014 mark_object (KVAR (kb, kbd_queue));
12015 mark_object (KVAR (kb, defining_kbd_macro));
12016 mark_object (KVAR (kb, Vlast_kbd_macro));
12017 mark_object (KVAR (kb, Vsystem_key_alist));
12018 mark_object (KVAR (kb, system_key_syms));
12019 mark_object (KVAR (kb, Vwindow_system));
12020 mark_object (KVAR (kb, Vinput_decode_map));
12021 mark_object (KVAR (kb, Vlocal_function_key_map));
12022 mark_object (KVAR (kb, Vdefault_minibuffer_frame));
12023 mark_object (KVAR (kb, echo_string));
12026 struct input_event *event;
12027 for (event = kbd_fetch_ptr; event != kbd_store_ptr; event++)
12029 if (event == kbd_buffer + KBD_BUFFER_SIZE)
12030 event = kbd_buffer;
12031 /* These two special event types has no Lisp_Objects to mark. */
12032 if (event->kind != SELECTION_REQUEST_EVENT
12033 && event->kind != SELECTION_CLEAR_EVENT)
12035 mark_object (event->x);
12036 mark_object (event->y);
12037 mark_object (event->frame_or_window);
12038 mark_object (event->arg);