]> code.delx.au - gnu-emacs/blob - src/keyboard.c
Further Unicode restrictive fixups
[gnu-emacs] / src / keyboard.c
1 /* Keyboard and mouse input; editor command loop.
2
3 Copyright (C) 1985-1989, 1993-1997, 1999-2015 Free Software Foundation,
4 Inc.
5
6 This file is part of GNU Emacs.
7
8 GNU Emacs is free software: you can redistribute it and/or modify
9 it under the terms of the GNU General Public License as published by
10 the Free Software Foundation, either version 3 of the License, or
11 (at your option) any later version.
12
13 GNU Emacs is distributed in the hope that it will be useful,
14 but WITHOUT ANY WARRANTY; without even the implied warranty of
15 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
16 GNU General Public License for more details.
17
18 You should have received a copy of the GNU General Public License
19 along with GNU Emacs. If not, see <http://www.gnu.org/licenses/>. */
20
21 #include <config.h>
22
23 #include <sys/stat.h>
24
25 #include "lisp.h"
26 #include "coding.h"
27 #include "termchar.h"
28 #include "termopts.h"
29 #include "frame.h"
30 #include "termhooks.h"
31 #include "macros.h"
32 #include "keyboard.h"
33 #include "window.h"
34 #include "commands.h"
35 #include "character.h"
36 #include "buffer.h"
37 #include "dispextern.h"
38 #include "syntax.h"
39 #include "intervals.h"
40 #include "keymap.h"
41 #include "blockinput.h"
42 #include "systime.h"
43 #include "atimer.h"
44 #include "process.h"
45 #include <errno.h>
46
47 #ifdef HAVE_PTHREAD
48 #include <pthread.h>
49 #endif
50 #ifdef MSDOS
51 #include "msdos.h"
52 #include <time.h>
53 #else /* not MSDOS */
54 #include <sys/ioctl.h>
55 #endif /* not MSDOS */
56
57 #if defined USABLE_FIONREAD && defined USG5_4
58 # include <sys/filio.h>
59 #endif
60
61 #include "syssignal.h"
62
63 #include <sys/types.h>
64 #include <unistd.h>
65 #include <fcntl.h>
66
67 #ifdef HAVE_WINDOW_SYSTEM
68 #include TERM_HEADER
69 #endif /* HAVE_WINDOW_SYSTEM */
70
71 /* Variables for blockinput.h: */
72
73 /* Positive if interrupt input is blocked right now. */
74 volatile int interrupt_input_blocked;
75
76 /* True means an input interrupt or alarm signal has arrived.
77 The QUIT macro checks this. */
78 volatile bool pending_signals;
79
80 #define KBD_BUFFER_SIZE 4096
81
82 KBOARD *initial_kboard;
83 KBOARD *current_kboard;
84 static KBOARD *all_kboards;
85
86 /* True in the single-kboard state, false in the any-kboard state. */
87 static bool single_kboard;
88
89 #define NUM_RECENT_KEYS (300)
90
91 /* Index for storing next element into recent_keys. */
92 static int recent_keys_index;
93
94 /* Total number of elements stored into recent_keys. */
95 static int total_keys;
96
97 /* This vector holds the last NUM_RECENT_KEYS keystrokes. */
98 static Lisp_Object recent_keys;
99
100 /* Vector holding the key sequence that invoked the current command.
101 It is reused for each command, and it may be longer than the current
102 sequence; this_command_key_count indicates how many elements
103 actually mean something.
104 It's easier to staticpro a single Lisp_Object than an array. */
105 Lisp_Object this_command_keys;
106 ptrdiff_t this_command_key_count;
107
108 /* This vector is used as a buffer to record the events that were actually read
109 by read_key_sequence. */
110 static Lisp_Object raw_keybuf;
111 static int raw_keybuf_count;
112
113 #define GROW_RAW_KEYBUF \
114 if (raw_keybuf_count == ASIZE (raw_keybuf)) \
115 raw_keybuf = larger_vector (raw_keybuf, 1, -1)
116
117 /* Number of elements of this_command_keys
118 that precede this key sequence. */
119 static ptrdiff_t this_single_command_key_start;
120
121 #ifdef HAVE_STACK_OVERFLOW_HANDLING
122
123 /* For longjmp to recover from C stack overflow. */
124 sigjmp_buf return_to_command_loop;
125
126 /* Message displayed by Vtop_level when recovering from C stack overflow. */
127 static Lisp_Object recover_top_level_message;
128
129 #endif /* HAVE_STACK_OVERFLOW_HANDLING */
130
131 /* Message normally displayed by Vtop_level. */
132 static Lisp_Object regular_top_level_message;
133
134 /* For longjmp to where kbd input is being done. */
135
136 static sys_jmp_buf getcjmp;
137
138 /* True while doing kbd input. */
139 bool waiting_for_input;
140
141 /* True while displaying for echoing. Delays C-g throwing. */
142
143 static bool echoing;
144
145 /* Non-null means we can start echoing at the next input pause even
146 though there is something in the echo area. */
147
148 static struct kboard *ok_to_echo_at_next_pause;
149
150 /* The kboard last echoing, or null for none. Reset to 0 in
151 cancel_echoing. If non-null, and a current echo area message
152 exists, and echo_message_buffer is eq to the current message
153 buffer, we know that the message comes from echo_kboard. */
154
155 struct kboard *echo_kboard;
156
157 /* The buffer used for echoing. Set in echo_now, reset in
158 cancel_echoing. */
159
160 Lisp_Object echo_message_buffer;
161
162 /* True means C-g should cause immediate error-signal. */
163 bool immediate_quit;
164
165 /* Character that causes a quit. Normally C-g.
166
167 If we are running on an ordinary terminal, this must be an ordinary
168 ASCII char, since we want to make it our interrupt character.
169
170 If we are not running on an ordinary terminal, it still needs to be
171 an ordinary ASCII char. This character needs to be recognized in
172 the input interrupt handler. At this point, the keystroke is
173 represented as a struct input_event, while the desired quit
174 character is specified as a lispy event. The mapping from struct
175 input_events to lispy events cannot run in an interrupt handler,
176 and the reverse mapping is difficult for anything but ASCII
177 keystrokes.
178
179 FOR THESE ELABORATE AND UNSATISFYING REASONS, quit_char must be an
180 ASCII character. */
181 int quit_char;
182
183 /* Current depth in recursive edits. */
184 EMACS_INT command_loop_level;
185
186 /* If not Qnil, this is a switch-frame event which we decided to put
187 off until the end of a key sequence. This should be read as the
188 next command input, after any unread_command_events.
189
190 read_key_sequence uses this to delay switch-frame events until the
191 end of the key sequence; Fread_char uses it to put off switch-frame
192 events until a non-ASCII event is acceptable as input. */
193 Lisp_Object unread_switch_frame;
194
195 /* Last size recorded for a current buffer which is not a minibuffer. */
196 static ptrdiff_t last_non_minibuf_size;
197
198 /* Total number of times read_char has returned, modulo UINTMAX_MAX + 1. */
199 uintmax_t num_input_events;
200
201 /* Value of num_nonmacro_input_events as of last auto save. */
202
203 static EMACS_INT last_auto_save;
204
205 /* The value of point when the last command was started. */
206 static ptrdiff_t last_point_position;
207
208 /* The frame in which the last input event occurred, or Qmacro if the
209 last event came from a macro. We use this to determine when to
210 generate switch-frame events. This may be cleared by functions
211 like Fselect_frame, to make sure that a switch-frame event is
212 generated by the next character.
213
214 FIXME: This is modified by a signal handler so it should be volatile.
215 It's exported to Lisp, though, so it can't simply be marked
216 'volatile' here. */
217 Lisp_Object internal_last_event_frame;
218
219 /* `read_key_sequence' stores here the command definition of the
220 key sequence that it reads. */
221 static Lisp_Object read_key_sequence_cmd;
222 static Lisp_Object read_key_sequence_remapped;
223
224 /* File in which we write all commands we read. */
225 static FILE *dribble;
226
227 /* True if input is available. */
228 bool input_pending;
229
230 /* True if more input was available last time we read an event.
231
232 Since redisplay can take a significant amount of time and is not
233 indispensable to perform the user's commands, when input arrives
234 "too fast", Emacs skips redisplay. More specifically, if the next
235 command has already been input when we finish the previous command,
236 we skip the intermediate redisplay.
237
238 This is useful to try and make sure Emacs keeps up with fast input
239 rates, such as auto-repeating keys. But in some cases, this proves
240 too conservative: we may end up disabling redisplay for the whole
241 duration of a key repetition, even though we could afford to
242 redisplay every once in a while.
243
244 So we "sample" the input_pending flag before running a command and
245 use *that* value after running the command to decide whether to
246 skip redisplay or not. This way, we only skip redisplay if we
247 really can't keep up with the repeat rate.
248
249 This only makes a difference if the next input arrives while running the
250 command, which is very unlikely if the command is executed quickly.
251 IOW this tends to avoid skipping redisplay after a long running command
252 (which is a case where skipping redisplay is not very useful since the
253 redisplay time is small compared to the time it took to run the command).
254
255 A typical use case is when scrolling. Scrolling time can be split into:
256 - Time to do jit-lock on the newly displayed portion of buffer.
257 - Time to run the actual scroll command.
258 - Time to perform the redisplay.
259 Jit-lock can happen either during the command or during the redisplay.
260 In the most painful cases, the jit-lock time is the one that dominates.
261 Also jit-lock can be tweaked (via jit-lock-defer) to delay its job, at the
262 cost of temporary inaccuracy in display and scrolling.
263 So without input_was_pending, what typically happens is the following:
264 - when the command starts, there's no pending input (yet).
265 - the scroll command triggers jit-lock.
266 - during the long jit-lock time the next input arrives.
267 - at the end of the command, we check input_pending and hence decide to
268 skip redisplay.
269 - we read the next input and start over.
270 End result: all the hard work of jit-locking is "wasted" since redisplay
271 doesn't actually happens (at least not before the input rate slows down).
272 With input_was_pending redisplay is still skipped if Emacs can't keep up
273 with the input rate, but if it can keep up just enough that there's no
274 input_pending when we begin the command, then redisplay is not skipped
275 which results in better feedback to the user. */
276 static bool input_was_pending;
277
278 /* Circular buffer for pre-read keyboard input. */
279
280 static union buffered_input_event kbd_buffer[KBD_BUFFER_SIZE];
281
282 /* Pointer to next available character in kbd_buffer.
283 If kbd_fetch_ptr == kbd_store_ptr, the buffer is empty.
284 This may be kbd_buffer + KBD_BUFFER_SIZE, meaning that the
285 next available char is in kbd_buffer[0]. */
286 static union buffered_input_event *kbd_fetch_ptr;
287
288 /* Pointer to next place to store character in kbd_buffer. This
289 may be kbd_buffer + KBD_BUFFER_SIZE, meaning that the next
290 character should go in kbd_buffer[0]. */
291 static union buffered_input_event *volatile kbd_store_ptr;
292
293 /* The above pair of variables forms a "queue empty" flag. When we
294 enqueue a non-hook event, we increment kbd_store_ptr. When we
295 dequeue a non-hook event, we increment kbd_fetch_ptr. We say that
296 there is input available if the two pointers are not equal.
297
298 Why not just have a flag set and cleared by the enqueuing and
299 dequeuing functions? Such a flag could be screwed up by interrupts
300 at inopportune times. */
301
302 static void recursive_edit_unwind (Lisp_Object buffer);
303 static Lisp_Object command_loop (void);
304
305 static void echo_now (void);
306 static ptrdiff_t echo_length (void);
307
308 /* Incremented whenever a timer is run. */
309 unsigned timers_run;
310
311 /* Address (if not 0) of struct timespec to zero out if a SIGIO interrupt
312 happens. */
313 struct timespec *input_available_clear_time;
314
315 /* True means use SIGIO interrupts; false means use CBREAK mode.
316 Default is true if INTERRUPT_INPUT is defined. */
317 bool interrupt_input;
318
319 /* Nonzero while interrupts are temporarily deferred during redisplay. */
320 bool interrupts_deferred;
321
322 /* The time when Emacs started being idle. */
323
324 static struct timespec timer_idleness_start_time;
325
326 /* After Emacs stops being idle, this saves the last value
327 of timer_idleness_start_time from when it was idle. */
328
329 static struct timespec timer_last_idleness_start_time;
330
331 \f
332 /* Global variable declarations. */
333
334 /* Flags for readable_events. */
335 #define READABLE_EVENTS_DO_TIMERS_NOW (1 << 0)
336 #define READABLE_EVENTS_FILTER_EVENTS (1 << 1)
337 #define READABLE_EVENTS_IGNORE_SQUEEZABLES (1 << 2)
338
339 /* Function for init_keyboard to call with no args (if nonzero). */
340 static void (*keyboard_init_hook) (void);
341
342 static bool get_input_pending (int);
343 static bool readable_events (int);
344 static Lisp_Object read_char_x_menu_prompt (Lisp_Object,
345 Lisp_Object, bool *);
346 static Lisp_Object read_char_minibuf_menu_prompt (int, Lisp_Object);
347 static Lisp_Object make_lispy_event (struct input_event *);
348 static Lisp_Object make_lispy_movement (struct frame *, Lisp_Object,
349 enum scroll_bar_part,
350 Lisp_Object, Lisp_Object,
351 Time);
352 static Lisp_Object modify_event_symbol (ptrdiff_t, int, Lisp_Object,
353 Lisp_Object, const char *const *,
354 Lisp_Object *, ptrdiff_t);
355 static Lisp_Object make_lispy_switch_frame (Lisp_Object);
356 static Lisp_Object make_lispy_focus_in (Lisp_Object);
357 #ifdef HAVE_WINDOW_SYSTEM
358 static Lisp_Object make_lispy_focus_out (Lisp_Object);
359 #endif /* HAVE_WINDOW_SYSTEM */
360 static bool help_char_p (Lisp_Object);
361 static void save_getcjmp (sys_jmp_buf);
362 static void restore_getcjmp (sys_jmp_buf);
363 static Lisp_Object apply_modifiers (int, Lisp_Object);
364 static void restore_kboard_configuration (int);
365 static void handle_interrupt (bool);
366 static _Noreturn void quit_throw_to_read_char (bool);
367 static void timer_start_idle (void);
368 static void timer_stop_idle (void);
369 static void timer_resume_idle (void);
370 static void deliver_user_signal (int);
371 static char *find_user_signal_name (int);
372 static void store_user_signal_events (void);
373
374 /* These setters are used only in this file, so they can be private. */
375 static void
376 kset_echo_string (struct kboard *kb, Lisp_Object val)
377 {
378 kb->echo_string_ = val;
379 }
380 static void
381 kset_echo_prompt (struct kboard *kb, Lisp_Object val)
382 {
383 kb->echo_prompt_ = val;
384 }
385 static void
386 kset_kbd_queue (struct kboard *kb, Lisp_Object val)
387 {
388 kb->kbd_queue_ = val;
389 }
390 static void
391 kset_keyboard_translate_table (struct kboard *kb, Lisp_Object val)
392 {
393 kb->Vkeyboard_translate_table_ = val;
394 }
395 static void
396 kset_last_prefix_arg (struct kboard *kb, Lisp_Object val)
397 {
398 kb->Vlast_prefix_arg_ = val;
399 }
400 static void
401 kset_last_repeatable_command (struct kboard *kb, Lisp_Object val)
402 {
403 kb->Vlast_repeatable_command_ = val;
404 }
405 static void
406 kset_local_function_key_map (struct kboard *kb, Lisp_Object val)
407 {
408 kb->Vlocal_function_key_map_ = val;
409 }
410 static void
411 kset_overriding_terminal_local_map (struct kboard *kb, Lisp_Object val)
412 {
413 kb->Voverriding_terminal_local_map_ = val;
414 }
415 static void
416 kset_real_last_command (struct kboard *kb, Lisp_Object val)
417 {
418 kb->Vreal_last_command_ = val;
419 }
420 static void
421 kset_system_key_syms (struct kboard *kb, Lisp_Object val)
422 {
423 kb->system_key_syms_ = val;
424 }
425
426 \f
427 /* Add C to the echo string, without echoing it immediately. C can be
428 a character, which is pretty-printed, or a symbol, whose name is
429 printed. */
430
431 static void
432 echo_add_key (Lisp_Object c)
433 {
434 char initbuf[KEY_DESCRIPTION_SIZE + 100];
435 ptrdiff_t size = sizeof initbuf;
436 char *buffer = initbuf;
437 char *ptr = buffer;
438 Lisp_Object echo_string = KVAR (current_kboard, echo_string);
439 USE_SAFE_ALLOCA;
440
441 if (STRINGP (echo_string) && SCHARS (echo_string) > 0)
442 /* Add a space at the end as a separator between keys. */
443 ptr++[0] = ' ';
444
445 /* If someone has passed us a composite event, use its head symbol. */
446 c = EVENT_HEAD (c);
447
448 if (INTEGERP (c))
449 ptr = push_key_description (XINT (c), ptr);
450 else if (SYMBOLP (c))
451 {
452 Lisp_Object name = SYMBOL_NAME (c);
453 ptrdiff_t nbytes = SBYTES (name);
454
455 if (size - (ptr - buffer) < nbytes)
456 {
457 ptrdiff_t offset = ptr - buffer;
458 size = max (2 * size, size + nbytes);
459 buffer = SAFE_ALLOCA (size);
460 ptr = buffer + offset;
461 }
462
463 ptr += copy_text (SDATA (name), (unsigned char *) ptr, nbytes,
464 STRING_MULTIBYTE (name), 1);
465 }
466
467 if ((NILP (echo_string) || SCHARS (echo_string) == 0)
468 && help_char_p (c))
469 {
470 static const char text[] = " (Type ? for further options)";
471 int len = sizeof text - 1;
472
473 if (size - (ptr - buffer) < len)
474 {
475 ptrdiff_t offset = ptr - buffer;
476 size += len;
477 buffer = SAFE_ALLOCA (size);
478 ptr = buffer + offset;
479 }
480
481 memcpy (ptr, text, len);
482 ptr += len;
483 }
484
485 kset_echo_string
486 (current_kboard,
487 concat2 (echo_string, make_string (buffer, ptr - buffer)));
488 SAFE_FREE ();
489 }
490
491 /* Temporarily add a dash to the end of the echo string if it's not
492 empty, so that it serves as a mini-prompt for the very next
493 character. */
494
495 static void
496 echo_dash (void)
497 {
498 /* Do nothing if not echoing at all. */
499 if (NILP (KVAR (current_kboard, echo_string)))
500 return;
501
502 if (!current_kboard->immediate_echo
503 && SCHARS (KVAR (current_kboard, echo_string)) == 0)
504 return;
505
506 /* Do nothing if we just printed a prompt. */
507 if (STRINGP (KVAR (current_kboard, echo_prompt))
508 && (SCHARS (KVAR (current_kboard, echo_prompt))
509 == SCHARS (KVAR (current_kboard, echo_string))))
510 return;
511
512 /* Do nothing if we have already put a dash at the end. */
513 if (SCHARS (KVAR (current_kboard, echo_string)) > 1)
514 {
515 Lisp_Object last_char, prev_char, idx;
516
517 idx = make_number (SCHARS (KVAR (current_kboard, echo_string)) - 2);
518 prev_char = Faref (KVAR (current_kboard, echo_string), idx);
519
520 idx = make_number (SCHARS (KVAR (current_kboard, echo_string)) - 1);
521 last_char = Faref (KVAR (current_kboard, echo_string), idx);
522
523 if (XINT (last_char) == '-' && XINT (prev_char) != ' ')
524 return;
525 }
526
527 /* Put a dash at the end of the buffer temporarily,
528 but make it go away when the next character is added. */
529 AUTO_STRING (dash, "-");
530 kset_echo_string (current_kboard,
531 concat2 (KVAR (current_kboard, echo_string), dash));
532 echo_now ();
533 }
534
535 static void
536 echo_update (void)
537 {
538 if (current_kboard->immediate_echo)
539 {
540 ptrdiff_t i;
541 Lisp_Object prompt = KVAR (current_kboard, echo_prompt);
542 Lisp_Object prefix = call0 (Qinternal_echo_keystrokes_prefix);
543 kset_echo_string (current_kboard,
544 NILP (prompt) ? prefix
545 : NILP (prefix) ? prompt
546 : concat2 (prompt, prefix));
547
548 for (i = 0; i < this_command_key_count; i++)
549 {
550 Lisp_Object c;
551
552 c = AREF (this_command_keys, i);
553 if (! (EVENT_HAS_PARAMETERS (c)
554 && EQ (EVENT_HEAD_KIND (EVENT_HEAD (c)), Qmouse_movement)))
555 echo_add_key (c);
556 }
557
558 echo_now ();
559 }
560 }
561
562 /* Display the current echo string, and begin echoing if not already
563 doing so. */
564
565 static void
566 echo_now (void)
567 {
568 if (!current_kboard->immediate_echo)
569 {
570 current_kboard->immediate_echo = true;
571 echo_update ();
572 /* Put a dash at the end to invite the user to type more. */
573 echo_dash ();
574 }
575
576 echoing = true;
577 /* FIXME: Use call (Qmessage) so it can be advised (e.g. emacspeak). */
578 message3_nolog (KVAR (current_kboard, echo_string));
579 echoing = false;
580
581 /* Record in what buffer we echoed, and from which kboard. */
582 echo_message_buffer = echo_area_buffer[0];
583 echo_kboard = current_kboard;
584
585 if (waiting_for_input && !NILP (Vquit_flag))
586 quit_throw_to_read_char (0);
587 }
588
589 /* Turn off echoing, for the start of a new command. */
590
591 void
592 cancel_echoing (void)
593 {
594 current_kboard->immediate_echo = false;
595 kset_echo_prompt (current_kboard, Qnil);
596 kset_echo_string (current_kboard, Qnil);
597 ok_to_echo_at_next_pause = NULL;
598 echo_kboard = NULL;
599 echo_message_buffer = Qnil;
600 }
601
602 /* Return the length of the current echo string. */
603
604 static ptrdiff_t
605 echo_length (void)
606 {
607 return (STRINGP (KVAR (current_kboard, echo_string))
608 ? SCHARS (KVAR (current_kboard, echo_string))
609 : 0);
610 }
611
612 /* Truncate the current echo message to its first LEN chars.
613 This and echo_char get used by read_key_sequence when the user
614 switches frames while entering a key sequence. */
615
616 static void
617 echo_truncate (ptrdiff_t nchars)
618 {
619 if (STRINGP (KVAR (current_kboard, echo_string)))
620 kset_echo_string (current_kboard,
621 Fsubstring (KVAR (current_kboard, echo_string),
622 make_number (0), make_number (nchars)));
623 truncate_echo_area (nchars);
624 }
625
626 \f
627 /* Functions for manipulating this_command_keys. */
628 static void
629 add_command_key (Lisp_Object key)
630 {
631 if (this_command_key_count >= ASIZE (this_command_keys))
632 this_command_keys = larger_vector (this_command_keys, 1, -1);
633
634 ASET (this_command_keys, this_command_key_count, key);
635 ++this_command_key_count;
636 }
637
638 \f
639 Lisp_Object
640 recursive_edit_1 (void)
641 {
642 ptrdiff_t count = SPECPDL_INDEX ();
643 Lisp_Object val;
644
645 if (command_loop_level > 0)
646 {
647 specbind (Qstandard_output, Qt);
648 specbind (Qstandard_input, Qt);
649 }
650
651 #ifdef HAVE_WINDOW_SYSTEM
652 /* The command loop has started an hourglass timer, so we have to
653 cancel it here, otherwise it will fire because the recursive edit
654 can take some time. Do not check for display_hourglass_p here,
655 because it could already be nil. */
656 cancel_hourglass ();
657 #endif
658
659 /* This function may have been called from a debugger called from
660 within redisplay, for instance by Edebugging a function called
661 from fontification-functions. We want to allow redisplay in
662 the debugging session.
663
664 The recursive edit is left with a `(throw exit ...)'. The `exit'
665 tag is not caught anywhere in redisplay, i.e. when we leave the
666 recursive edit, the original redisplay leading to the recursive
667 edit will be unwound. The outcome should therefore be safe. */
668 specbind (Qinhibit_redisplay, Qnil);
669 redisplaying_p = 0;
670
671 val = command_loop ();
672 if (EQ (val, Qt))
673 Fsignal (Qquit, Qnil);
674 /* Handle throw from read_minibuf when using minibuffer
675 while it's active but we're in another window. */
676 if (STRINGP (val))
677 xsignal1 (Qerror, val);
678
679 return unbind_to (count, Qnil);
680 }
681
682 /* When an auto-save happens, record the "time", and don't do again soon. */
683
684 void
685 record_auto_save (void)
686 {
687 last_auto_save = num_nonmacro_input_events;
688 }
689
690 /* Make an auto save happen as soon as possible at command level. */
691
692 #ifdef SIGDANGER
693 void
694 force_auto_save_soon (void)
695 {
696 last_auto_save = - auto_save_interval - 1;
697
698 record_asynch_buffer_change ();
699 }
700 #endif
701 \f
702 DEFUN ("recursive-edit", Frecursive_edit, Srecursive_edit, 0, 0, "",
703 doc: /* Invoke the editor command loop recursively.
704 To get out of the recursive edit, a command can throw to `exit' -- for
705 instance (throw \\='exit nil).
706 If you throw a value other than t, `recursive-edit' returns normally
707 to the function that called it. Throwing a t value causes
708 `recursive-edit' to quit, so that control returns to the command loop
709 one level up.
710
711 This function is called by the editor initialization to begin editing. */)
712 (void)
713 {
714 ptrdiff_t count = SPECPDL_INDEX ();
715 Lisp_Object buffer;
716
717 /* If we enter while input is blocked, don't lock up here.
718 This may happen through the debugger during redisplay. */
719 if (input_blocked_p ())
720 return Qnil;
721
722 if (command_loop_level >= 0
723 && current_buffer != XBUFFER (XWINDOW (selected_window)->contents))
724 buffer = Fcurrent_buffer ();
725 else
726 buffer = Qnil;
727
728 /* Don't do anything interesting between the increment and the
729 record_unwind_protect! Otherwise, we could get distracted and
730 never decrement the counter again. */
731 command_loop_level++;
732 update_mode_lines = 17;
733 record_unwind_protect (recursive_edit_unwind, buffer);
734
735 /* If we leave recursive_edit_1 below with a `throw' for instance,
736 like it is done in the splash screen display, we have to
737 make sure that we restore single_kboard as command_loop_1
738 would have done if it were left normally. */
739 if (command_loop_level > 0)
740 temporarily_switch_to_single_kboard (SELECTED_FRAME ());
741
742 recursive_edit_1 ();
743 return unbind_to (count, Qnil);
744 }
745
746 void
747 recursive_edit_unwind (Lisp_Object buffer)
748 {
749 if (BUFFERP (buffer))
750 Fset_buffer (buffer);
751
752 command_loop_level--;
753 update_mode_lines = 18;
754 }
755
756 \f
757 #if 0 /* These two functions are now replaced with
758 temporarily_switch_to_single_kboard. */
759 static void
760 any_kboard_state ()
761 {
762 #if 0 /* Theory: if there's anything in Vunread_command_events,
763 it will right away be read by read_key_sequence,
764 and then if we do switch KBOARDS, it will go into the side
765 queue then. So we don't need to do anything special here -- rms. */
766 if (CONSP (Vunread_command_events))
767 {
768 current_kboard->kbd_queue
769 = nconc2 (Vunread_command_events, current_kboard->kbd_queue);
770 current_kboard->kbd_queue_has_data = true;
771 }
772 Vunread_command_events = Qnil;
773 #endif
774 single_kboard = false;
775 }
776
777 /* Switch to the single-kboard state, making current_kboard
778 the only KBOARD from which further input is accepted. */
779
780 void
781 single_kboard_state ()
782 {
783 single_kboard = true;
784 }
785 #endif
786
787 /* If we're in single_kboard state for kboard KBOARD,
788 get out of it. */
789
790 void
791 not_single_kboard_state (KBOARD *kboard)
792 {
793 if (kboard == current_kboard)
794 single_kboard = false;
795 }
796
797 /* Maintain a stack of kboards, so other parts of Emacs
798 can switch temporarily to the kboard of a given frame
799 and then revert to the previous status. */
800
801 struct kboard_stack
802 {
803 KBOARD *kboard;
804 struct kboard_stack *next;
805 };
806
807 static struct kboard_stack *kboard_stack;
808
809 void
810 push_kboard (struct kboard *k)
811 {
812 struct kboard_stack *p = xmalloc (sizeof *p);
813
814 p->next = kboard_stack;
815 p->kboard = current_kboard;
816 kboard_stack = p;
817
818 current_kboard = k;
819 }
820
821 void
822 pop_kboard (void)
823 {
824 struct terminal *t;
825 struct kboard_stack *p = kboard_stack;
826 bool found = false;
827 for (t = terminal_list; t; t = t->next_terminal)
828 {
829 if (t->kboard == p->kboard)
830 {
831 current_kboard = p->kboard;
832 found = true;
833 break;
834 }
835 }
836 if (!found)
837 {
838 /* The terminal we remembered has been deleted. */
839 current_kboard = FRAME_KBOARD (SELECTED_FRAME ());
840 single_kboard = false;
841 }
842 kboard_stack = p->next;
843 xfree (p);
844 }
845
846 /* Switch to single_kboard mode, making current_kboard the only KBOARD
847 from which further input is accepted. If F is non-nil, set its
848 KBOARD as the current keyboard.
849
850 This function uses record_unwind_protect_int to return to the previous
851 state later.
852
853 If Emacs is already in single_kboard mode, and F's keyboard is
854 locked, then this function will throw an error. */
855
856 void
857 temporarily_switch_to_single_kboard (struct frame *f)
858 {
859 bool was_locked = single_kboard;
860 if (was_locked)
861 {
862 if (f != NULL && FRAME_KBOARD (f) != current_kboard)
863 /* We can not switch keyboards while in single_kboard mode.
864 In rare cases, Lisp code may call `recursive-edit' (or
865 `read-minibuffer' or `y-or-n-p') after it switched to a
866 locked frame. For example, this is likely to happen
867 when server.el connects to a new terminal while Emacs is in
868 single_kboard mode. It is best to throw an error instead
869 of presenting the user with a frozen screen. */
870 error ("Terminal %d is locked, cannot read from it",
871 FRAME_TERMINAL (f)->id);
872 else
873 /* This call is unnecessary, but helps
874 `restore_kboard_configuration' discover if somebody changed
875 `current_kboard' behind our back. */
876 push_kboard (current_kboard);
877 }
878 else if (f != NULL)
879 current_kboard = FRAME_KBOARD (f);
880 single_kboard = true;
881 record_unwind_protect_int (restore_kboard_configuration, was_locked);
882 }
883
884 #if 0 /* This function is not needed anymore. */
885 void
886 record_single_kboard_state ()
887 {
888 if (single_kboard)
889 push_kboard (current_kboard);
890 record_unwind_protect_int (restore_kboard_configuration, single_kboard);
891 }
892 #endif
893
894 static void
895 restore_kboard_configuration (int was_locked)
896 {
897 single_kboard = was_locked;
898 if (was_locked)
899 {
900 struct kboard *prev = current_kboard;
901 pop_kboard ();
902 /* The pop should not change the kboard. */
903 if (single_kboard && current_kboard != prev)
904 emacs_abort ();
905 }
906 }
907
908 \f
909 /* Handle errors that are not handled at inner levels
910 by printing an error message and returning to the editor command loop. */
911
912 static Lisp_Object
913 cmd_error (Lisp_Object data)
914 {
915 Lisp_Object old_level, old_length;
916 char macroerror[sizeof "After..kbd macro iterations: "
917 + INT_STRLEN_BOUND (EMACS_INT)];
918
919 #ifdef HAVE_WINDOW_SYSTEM
920 if (display_hourglass_p)
921 cancel_hourglass ();
922 #endif
923
924 if (!NILP (executing_kbd_macro))
925 {
926 if (executing_kbd_macro_iterations == 1)
927 sprintf (macroerror, "After 1 kbd macro iteration: ");
928 else
929 sprintf (macroerror, "After %"pI"d kbd macro iterations: ",
930 executing_kbd_macro_iterations);
931 }
932 else
933 *macroerror = 0;
934
935 Vstandard_output = Qt;
936 Vstandard_input = Qt;
937 Vexecuting_kbd_macro = Qnil;
938 executing_kbd_macro = Qnil;
939 kset_prefix_arg (current_kboard, Qnil);
940 kset_last_prefix_arg (current_kboard, Qnil);
941 cancel_echoing ();
942
943 /* Avoid unquittable loop if data contains a circular list. */
944 old_level = Vprint_level;
945 old_length = Vprint_length;
946 XSETFASTINT (Vprint_level, 10);
947 XSETFASTINT (Vprint_length, 10);
948 cmd_error_internal (data, macroerror);
949 Vprint_level = old_level;
950 Vprint_length = old_length;
951
952 Vquit_flag = Qnil;
953 Vinhibit_quit = Qnil;
954
955 return make_number (0);
956 }
957
958 /* Take actions on handling an error. DATA is the data that describes
959 the error.
960
961 CONTEXT is a C-string containing ASCII characters only which
962 describes the context in which the error happened. If we need to
963 generalize CONTEXT to allow multibyte characters, make it a Lisp
964 string. */
965
966 void
967 cmd_error_internal (Lisp_Object data, const char *context)
968 {
969 /* The immediate context is not interesting for Quits,
970 since they are asynchronous. */
971 if (EQ (XCAR (data), Qquit))
972 Vsignaling_function = Qnil;
973
974 Vquit_flag = Qnil;
975 Vinhibit_quit = Qt;
976
977 /* Use user's specified output function if any. */
978 if (!NILP (Vcommand_error_function))
979 call3 (Vcommand_error_function, data,
980 context ? build_string (context) : empty_unibyte_string,
981 Vsignaling_function);
982
983 Vsignaling_function = Qnil;
984 }
985
986 DEFUN ("command-error-default-function", Fcommand_error_default_function,
987 Scommand_error_default_function, 3, 3, 0,
988 doc: /* Produce default output for unhandled error message.
989 Default value of `command-error-function'. */)
990 (Lisp_Object data, Lisp_Object context, Lisp_Object signal)
991 {
992 struct frame *sf = SELECTED_FRAME ();
993
994 CHECK_STRING (context);
995
996 /* If the window system or terminal frame hasn't been initialized
997 yet, or we're not interactive, write the message to stderr and exit. */
998 if (!sf->glyphs_initialized_p
999 /* The initial frame is a special non-displaying frame. It
1000 will be current in daemon mode when there are no frames
1001 to display, and in non-daemon mode before the real frame
1002 has finished initializing. If an error is thrown in the
1003 latter case while creating the frame, then the frame
1004 will never be displayed, so the safest thing to do is
1005 write to stderr and quit. In daemon mode, there are
1006 many other potential errors that do not prevent frames
1007 from being created, so continuing as normal is better in
1008 that case. */
1009 || (!IS_DAEMON && FRAME_INITIAL_P (sf))
1010 || noninteractive)
1011 {
1012 print_error_message (data, Qexternal_debugging_output,
1013 SSDATA (context), signal);
1014 Fterpri (Qexternal_debugging_output, Qnil);
1015 Fkill_emacs (make_number (-1));
1016 }
1017 else
1018 {
1019 clear_message (1, 0);
1020 Fdiscard_input ();
1021 message_log_maybe_newline ();
1022 bitch_at_user ();
1023
1024 print_error_message (data, Qt, SSDATA (context), signal);
1025 }
1026 return Qnil;
1027 }
1028
1029 static Lisp_Object command_loop_2 (Lisp_Object);
1030 static Lisp_Object top_level_1 (Lisp_Object);
1031
1032 /* Entry to editor-command-loop.
1033 This level has the catches for exiting/returning to editor command loop.
1034 It returns nil to exit recursive edit, t to abort it. */
1035
1036 Lisp_Object
1037 command_loop (void)
1038 {
1039 #ifdef HAVE_STACK_OVERFLOW_HANDLING
1040 /* At least on GNU/Linux, saving signal mask is important here. */
1041 if (sigsetjmp (return_to_command_loop, 1) != 0)
1042 {
1043 /* Comes here from handle_sigsegv (see sysdep.c) and
1044 stack_overflow_handler (see w32fns.c). */
1045 #ifdef WINDOWSNT
1046 w32_reset_stack_overflow_guard ();
1047 #endif
1048 init_eval ();
1049 Vinternal__top_level_message = recover_top_level_message;
1050 }
1051 else
1052 Vinternal__top_level_message = regular_top_level_message;
1053 #endif /* HAVE_STACK_OVERFLOW_HANDLING */
1054 if (command_loop_level > 0 || minibuf_level > 0)
1055 {
1056 Lisp_Object val;
1057 val = internal_catch (Qexit, command_loop_2, Qnil);
1058 executing_kbd_macro = Qnil;
1059 return val;
1060 }
1061 else
1062 while (1)
1063 {
1064 internal_catch (Qtop_level, top_level_1, Qnil);
1065 internal_catch (Qtop_level, command_loop_2, Qnil);
1066 executing_kbd_macro = Qnil;
1067
1068 /* End of file in -batch run causes exit here. */
1069 if (noninteractive)
1070 Fkill_emacs (Qt);
1071 }
1072 }
1073
1074 /* Here we catch errors in execution of commands within the
1075 editing loop, and reenter the editing loop.
1076 When there is an error, cmd_error runs and returns a non-nil
1077 value to us. A value of nil means that command_loop_1 itself
1078 returned due to end of file (or end of kbd macro). */
1079
1080 static Lisp_Object
1081 command_loop_2 (Lisp_Object ignore)
1082 {
1083 register Lisp_Object val;
1084
1085 do
1086 val = internal_condition_case (command_loop_1, Qerror, cmd_error);
1087 while (!NILP (val));
1088
1089 return Qnil;
1090 }
1091
1092 static Lisp_Object
1093 top_level_2 (void)
1094 {
1095 return Feval (Vtop_level, Qnil);
1096 }
1097
1098 static Lisp_Object
1099 top_level_1 (Lisp_Object ignore)
1100 {
1101 /* On entry to the outer level, run the startup file. */
1102 if (!NILP (Vtop_level))
1103 internal_condition_case (top_level_2, Qerror, cmd_error);
1104 else if (!NILP (Vpurify_flag))
1105 message1 ("Bare impure Emacs (standard Lisp code not loaded)");
1106 else
1107 message1 ("Bare Emacs (standard Lisp code not loaded)");
1108 return Qnil;
1109 }
1110
1111 DEFUN ("top-level", Ftop_level, Stop_level, 0, 0, "",
1112 doc: /* Exit all recursive editing levels.
1113 This also exits all active minibuffers. */
1114 attributes: noreturn)
1115 (void)
1116 {
1117 #ifdef HAVE_WINDOW_SYSTEM
1118 if (display_hourglass_p)
1119 cancel_hourglass ();
1120 #endif
1121
1122 /* Unblock input if we enter with input blocked. This may happen if
1123 redisplay traps e.g. during tool-bar update with input blocked. */
1124 totally_unblock_input ();
1125
1126 Fthrow (Qtop_level, Qnil);
1127 }
1128
1129 static _Noreturn void
1130 user_error (const char *msg)
1131 {
1132 xsignal1 (Quser_error, build_string (msg));
1133 }
1134
1135 /* _Noreturn will be added to prototype by make-docfile. */
1136 DEFUN ("exit-recursive-edit", Fexit_recursive_edit, Sexit_recursive_edit, 0, 0, "",
1137 doc: /* Exit from the innermost recursive edit or minibuffer. */
1138 attributes: noreturn)
1139 (void)
1140 {
1141 if (command_loop_level > 0 || minibuf_level > 0)
1142 Fthrow (Qexit, Qnil);
1143
1144 user_error ("No recursive edit is in progress");
1145 }
1146
1147 /* _Noreturn will be added to prototype by make-docfile. */
1148 DEFUN ("abort-recursive-edit", Fabort_recursive_edit, Sabort_recursive_edit, 0, 0, "",
1149 doc: /* Abort the command that requested this recursive edit or minibuffer input. */
1150 attributes: noreturn)
1151 (void)
1152 {
1153 if (command_loop_level > 0 || minibuf_level > 0)
1154 Fthrow (Qexit, Qt);
1155
1156 user_error ("No recursive edit is in progress");
1157 }
1158 \f
1159 /* Restore mouse tracking enablement. See Ftrack_mouse for the only use
1160 of this function. */
1161
1162 static void
1163 tracking_off (Lisp_Object old_value)
1164 {
1165 do_mouse_tracking = old_value;
1166 if (NILP (old_value))
1167 {
1168 /* Redisplay may have been preempted because there was input
1169 available, and it assumes it will be called again after the
1170 input has been processed. If the only input available was
1171 the sort that we have just disabled, then we need to call
1172 redisplay. */
1173 if (!readable_events (READABLE_EVENTS_DO_TIMERS_NOW))
1174 {
1175 redisplay_preserve_echo_area (6);
1176 get_input_pending (READABLE_EVENTS_DO_TIMERS_NOW);
1177 }
1178 }
1179 }
1180
1181 DEFUN ("internal--track-mouse", Ftrack_mouse, Strack_mouse, 1, 1, 0,
1182 doc: /* Call BODYFUN with mouse movement events enabled. */)
1183 (Lisp_Object bodyfun)
1184 {
1185 ptrdiff_t count = SPECPDL_INDEX ();
1186 Lisp_Object val;
1187
1188 record_unwind_protect (tracking_off, do_mouse_tracking);
1189
1190 do_mouse_tracking = Qt;
1191
1192 val = call0 (bodyfun);
1193 return unbind_to (count, val);
1194 }
1195
1196 /* If mouse has moved on some frame, return one of those frames.
1197
1198 Return 0 otherwise.
1199
1200 If ignore_mouse_drag_p is non-zero, ignore (implicit) mouse movement
1201 after resizing the tool-bar window. */
1202
1203 bool ignore_mouse_drag_p;
1204
1205 static struct frame *
1206 some_mouse_moved (void)
1207 {
1208 Lisp_Object tail, frame;
1209
1210 if (ignore_mouse_drag_p)
1211 {
1212 /* ignore_mouse_drag_p = 0; */
1213 return 0;
1214 }
1215
1216 FOR_EACH_FRAME (tail, frame)
1217 {
1218 if (XFRAME (frame)->mouse_moved)
1219 return XFRAME (frame);
1220 }
1221
1222 return 0;
1223 }
1224
1225 \f
1226 /* This is the actual command reading loop,
1227 sans error-handling encapsulation. */
1228
1229 static int read_key_sequence (Lisp_Object *, int, Lisp_Object,
1230 bool, bool, bool, bool);
1231 static void adjust_point_for_property (ptrdiff_t, bool);
1232
1233 Lisp_Object
1234 command_loop_1 (void)
1235 {
1236 Lisp_Object cmd;
1237 Lisp_Object keybuf[30];
1238 int i;
1239 EMACS_INT prev_modiff = 0;
1240 struct buffer *prev_buffer = NULL;
1241 bool already_adjusted = 0;
1242
1243 kset_prefix_arg (current_kboard, Qnil);
1244 kset_last_prefix_arg (current_kboard, Qnil);
1245 Vdeactivate_mark = Qnil;
1246 waiting_for_input = false;
1247 cancel_echoing ();
1248
1249 this_command_key_count = 0;
1250 this_single_command_key_start = 0;
1251
1252 if (NILP (Vmemory_full))
1253 {
1254 /* Make sure this hook runs after commands that get errors and
1255 throw to top level. */
1256 /* Note that the value cell will never directly contain nil
1257 if the symbol is a local variable. */
1258 if (!NILP (Vpost_command_hook) && !NILP (Vrun_hooks))
1259 safe_run_hooks (Qpost_command_hook);
1260
1261 /* If displaying a message, resize the echo area window to fit
1262 that message's size exactly. */
1263 if (!NILP (echo_area_buffer[0]))
1264 resize_echo_area_exactly ();
1265
1266 /* If there are warnings waiting, process them. */
1267 if (!NILP (Vdelayed_warnings_list))
1268 safe_run_hooks (Qdelayed_warnings_hook);
1269
1270 if (!NILP (Vdeferred_action_list))
1271 safe_run_hooks (Qdeferred_action_function);
1272 }
1273
1274 /* Do this after running Vpost_command_hook, for consistency. */
1275 kset_last_command (current_kboard, Vthis_command);
1276 kset_real_last_command (current_kboard, Vreal_this_command);
1277 if (!CONSP (last_command_event))
1278 kset_last_repeatable_command (current_kboard, Vreal_this_command);
1279
1280 while (1)
1281 {
1282 if (! FRAME_LIVE_P (XFRAME (selected_frame)))
1283 Fkill_emacs (Qnil);
1284
1285 /* Make sure the current window's buffer is selected. */
1286 set_buffer_internal (XBUFFER (XWINDOW (selected_window)->contents));
1287
1288 /* Display any malloc warning that just came out. Use while because
1289 displaying one warning can cause another. */
1290
1291 while (pending_malloc_warning)
1292 display_malloc_warning ();
1293
1294 Vdeactivate_mark = Qnil;
1295
1296 /* Don't ignore mouse movements for more than a single command
1297 loop. (This flag is set in xdisp.c whenever the tool bar is
1298 resized, because the resize moves text up or down, and would
1299 generate false mouse drag events if we don't ignore them.) */
1300 ignore_mouse_drag_p = 0;
1301
1302 /* If minibuffer on and echo area in use,
1303 wait a short time and redraw minibuffer. */
1304
1305 if (minibuf_level
1306 && !NILP (echo_area_buffer[0])
1307 && EQ (minibuf_window, echo_area_window)
1308 && NUMBERP (Vminibuffer_message_timeout))
1309 {
1310 /* Bind inhibit-quit to t so that C-g gets read in
1311 rather than quitting back to the minibuffer. */
1312 ptrdiff_t count = SPECPDL_INDEX ();
1313 specbind (Qinhibit_quit, Qt);
1314
1315 sit_for (Vminibuffer_message_timeout, 0, 2);
1316
1317 /* Clear the echo area. */
1318 message1 (0);
1319 safe_run_hooks (Qecho_area_clear_hook);
1320
1321 unbind_to (count, Qnil);
1322
1323 /* If a C-g came in before, treat it as input now. */
1324 if (!NILP (Vquit_flag))
1325 {
1326 Vquit_flag = Qnil;
1327 Vunread_command_events = list1 (make_number (quit_char));
1328 }
1329 }
1330
1331 /* If it has changed current-menubar from previous value,
1332 really recompute the menubar from the value. */
1333 if (! NILP (Vlucid_menu_bar_dirty_flag)
1334 && !NILP (Ffboundp (Qrecompute_lucid_menubar)))
1335 call0 (Qrecompute_lucid_menubar);
1336
1337 Vthis_command = Qnil;
1338 Vreal_this_command = Qnil;
1339 Vthis_original_command = Qnil;
1340 Vthis_command_keys_shift_translated = Qnil;
1341
1342 /* Read next key sequence; i gets its length. */
1343 i = read_key_sequence (keybuf, ARRAYELTS (keybuf),
1344 Qnil, 0, 1, 1, 0);
1345
1346 /* A filter may have run while we were reading the input. */
1347 if (! FRAME_LIVE_P (XFRAME (selected_frame)))
1348 Fkill_emacs (Qnil);
1349 set_buffer_internal (XBUFFER (XWINDOW (selected_window)->contents));
1350
1351 ++num_input_keys;
1352
1353 /* Now we have read a key sequence of length I,
1354 or else I is 0 and we found end of file. */
1355
1356 if (i == 0) /* End of file -- happens only in */
1357 return Qnil; /* a kbd macro, at the end. */
1358 /* -1 means read_key_sequence got a menu that was rejected.
1359 Just loop around and read another command. */
1360 if (i == -1)
1361 {
1362 cancel_echoing ();
1363 this_command_key_count = 0;
1364 this_single_command_key_start = 0;
1365 goto finalize;
1366 }
1367
1368 last_command_event = keybuf[i - 1];
1369
1370 /* If the previous command tried to force a specific window-start,
1371 forget about that, in case this command moves point far away
1372 from that position. But also throw away beg_unchanged and
1373 end_unchanged information in that case, so that redisplay will
1374 update the whole window properly. */
1375 if (XWINDOW (selected_window)->force_start)
1376 {
1377 struct buffer *b;
1378 XWINDOW (selected_window)->force_start = 0;
1379 b = XBUFFER (XWINDOW (selected_window)->contents);
1380 BUF_BEG_UNCHANGED (b) = BUF_END_UNCHANGED (b) = 0;
1381 }
1382
1383 cmd = read_key_sequence_cmd;
1384 if (!NILP (Vexecuting_kbd_macro))
1385 {
1386 if (!NILP (Vquit_flag))
1387 {
1388 Vexecuting_kbd_macro = Qt;
1389 QUIT; /* Make some noise. */
1390 /* Will return since macro now empty. */
1391 }
1392 }
1393
1394 /* Do redisplay processing after this command except in special
1395 cases identified below. */
1396 prev_buffer = current_buffer;
1397 prev_modiff = MODIFF;
1398 last_point_position = PT;
1399
1400 /* By default, we adjust point to a boundary of a region that
1401 has such a property that should be treated intangible
1402 (e.g. composition, display). But, some commands will set
1403 this variable differently. */
1404 Vdisable_point_adjustment = Qnil;
1405
1406 /* Process filters and timers may have messed with deactivate-mark.
1407 reset it before we execute the command. */
1408 Vdeactivate_mark = Qnil;
1409
1410 /* Remap command through active keymaps. */
1411 Vthis_original_command = cmd;
1412 if (!NILP (read_key_sequence_remapped))
1413 cmd = read_key_sequence_remapped;
1414
1415 /* Execute the command. */
1416
1417 {
1418 total_keys += total_keys < NUM_RECENT_KEYS;
1419 ASET (recent_keys, recent_keys_index,
1420 Fcons (Qnil, cmd));
1421 if (++recent_keys_index >= NUM_RECENT_KEYS)
1422 recent_keys_index = 0;
1423 }
1424 Vthis_command = cmd;
1425 Vreal_this_command = cmd;
1426 safe_run_hooks (Qpre_command_hook);
1427
1428 already_adjusted = 0;
1429
1430 if (NILP (Vthis_command))
1431 /* nil means key is undefined. */
1432 call0 (Qundefined);
1433 else
1434 {
1435 /* Here for a command that isn't executed directly. */
1436
1437 #ifdef HAVE_WINDOW_SYSTEM
1438 ptrdiff_t scount = SPECPDL_INDEX ();
1439
1440 if (display_hourglass_p
1441 && NILP (Vexecuting_kbd_macro))
1442 {
1443 record_unwind_protect_void (cancel_hourglass);
1444 start_hourglass ();
1445 }
1446 #endif
1447
1448 /* Ensure that we have added appropriate undo-boundaries as a
1449 result of changes from the last command. */
1450 call0 (Qundo_auto__add_boundary);
1451
1452 call1 (Qcommand_execute, Vthis_command);
1453
1454 #ifdef HAVE_WINDOW_SYSTEM
1455 /* Do not check display_hourglass_p here, because
1456 `command-execute' could change it, but we should cancel
1457 hourglass cursor anyway.
1458 But don't cancel the hourglass within a macro
1459 just because a command in the macro finishes. */
1460 if (NILP (Vexecuting_kbd_macro))
1461 unbind_to (scount, Qnil);
1462 #endif
1463 }
1464 kset_last_prefix_arg (current_kboard, Vcurrent_prefix_arg);
1465
1466 safe_run_hooks (Qpost_command_hook);
1467
1468 /* If displaying a message, resize the echo area window to fit
1469 that message's size exactly. */
1470 if (!NILP (echo_area_buffer[0]))
1471 resize_echo_area_exactly ();
1472
1473 /* If there are warnings waiting, process them. */
1474 if (!NILP (Vdelayed_warnings_list))
1475 safe_run_hooks (Qdelayed_warnings_hook);
1476
1477 safe_run_hooks (Qdeferred_action_function);
1478
1479 kset_last_command (current_kboard, Vthis_command);
1480 kset_real_last_command (current_kboard, Vreal_this_command);
1481 if (!CONSP (last_command_event))
1482 kset_last_repeatable_command (current_kboard, Vreal_this_command);
1483
1484 this_command_key_count = 0;
1485 this_single_command_key_start = 0;
1486
1487 if (current_kboard->immediate_echo
1488 && !NILP (call0 (Qinternal_echo_keystrokes_prefix)))
1489 {
1490 current_kboard->immediate_echo = false;
1491 /* Refresh the echo message. */
1492 echo_now ();
1493 }
1494 else
1495 cancel_echoing ();
1496
1497 if (!NILP (BVAR (current_buffer, mark_active))
1498 && !NILP (Vrun_hooks))
1499 {
1500 /* In Emacs 22, setting transient-mark-mode to `only' was a
1501 way of turning it on for just one command. This usage is
1502 obsolete, but support it anyway. */
1503 if (EQ (Vtransient_mark_mode, Qidentity))
1504 Vtransient_mark_mode = Qnil;
1505 else if (EQ (Vtransient_mark_mode, Qonly))
1506 Vtransient_mark_mode = Qidentity;
1507
1508 if (!NILP (Vdeactivate_mark))
1509 /* If `select-active-regions' is non-nil, this call to
1510 `deactivate-mark' also sets the PRIMARY selection. */
1511 call0 (Qdeactivate_mark);
1512 else
1513 {
1514 /* Even if not deactivating the mark, set PRIMARY if
1515 `select-active-regions' is non-nil. */
1516 if (!NILP (Fwindow_system (Qnil))
1517 /* Even if mark_active is non-nil, the actual buffer
1518 marker may not have been set yet (Bug#7044). */
1519 && XMARKER (BVAR (current_buffer, mark))->buffer
1520 && (EQ (Vselect_active_regions, Qonly)
1521 ? EQ (CAR_SAFE (Vtransient_mark_mode), Qonly)
1522 : (!NILP (Vselect_active_regions)
1523 && !NILP (Vtransient_mark_mode)))
1524 && NILP (Fmemq (Vthis_command,
1525 Vselection_inhibit_update_commands)))
1526 {
1527 Lisp_Object txt
1528 = call1 (Fsymbol_value (Qregion_extract_function), Qnil);
1529 if (XINT (Flength (txt)) > 0)
1530 /* Don't set empty selections. */
1531 call2 (Qgui_set_selection, QPRIMARY, txt);
1532 }
1533
1534 if (current_buffer != prev_buffer || MODIFF != prev_modiff)
1535 run_hook (intern ("activate-mark-hook"));
1536 }
1537
1538 Vsaved_region_selection = Qnil;
1539 }
1540
1541 finalize:
1542
1543 if (current_buffer == prev_buffer
1544 && XBUFFER (XWINDOW (selected_window)->contents) == current_buffer
1545 && last_point_position != PT
1546 && NILP (Vdisable_point_adjustment)
1547 && NILP (Vglobal_disable_point_adjustment))
1548 {
1549 if (last_point_position > BEGV
1550 && last_point_position < ZV
1551 && (composition_adjust_point (last_point_position,
1552 last_point_position)
1553 != last_point_position))
1554 /* The last point was temporarily set within a grapheme
1555 cluster to prevent automatic composition. To recover
1556 the automatic composition, we must update the
1557 display. */
1558 windows_or_buffers_changed = 21;
1559 if (!already_adjusted)
1560 adjust_point_for_property (last_point_position,
1561 MODIFF != prev_modiff);
1562 }
1563
1564 /* Install chars successfully executed in kbd macro. */
1565
1566 if (!NILP (KVAR (current_kboard, defining_kbd_macro))
1567 && NILP (KVAR (current_kboard, Vprefix_arg)))
1568 finalize_kbd_macro_chars ();
1569 }
1570 }
1571
1572 Lisp_Object
1573 read_menu_command (void)
1574 {
1575 Lisp_Object keybuf[30];
1576 ptrdiff_t count = SPECPDL_INDEX ();
1577 int i;
1578
1579 /* We don't want to echo the keystrokes while navigating the
1580 menus. */
1581 specbind (Qecho_keystrokes, make_number (0));
1582
1583 i = read_key_sequence (keybuf, ARRAYELTS (keybuf),
1584 Qnil, 0, 1, 1, 1);
1585
1586 unbind_to (count, Qnil);
1587
1588 if (! FRAME_LIVE_P (XFRAME (selected_frame)))
1589 Fkill_emacs (Qnil);
1590 if (i == 0 || i == -1)
1591 return Qt;
1592
1593 return read_key_sequence_cmd;
1594 }
1595
1596 /* Adjust point to a boundary of a region that has such a property
1597 that should be treated intangible. For the moment, we check
1598 `composition', `display' and `invisible' properties.
1599 LAST_PT is the last position of point. */
1600
1601 static void
1602 adjust_point_for_property (ptrdiff_t last_pt, bool modified)
1603 {
1604 ptrdiff_t beg, end;
1605 Lisp_Object val, overlay, tmp;
1606 /* When called after buffer modification, we should temporarily
1607 suppress the point adjustment for automatic composition so that a
1608 user can keep inserting another character at point or keep
1609 deleting characters around point. */
1610 bool check_composition = ! modified;
1611 bool check_display = true, check_invisible = true;
1612 ptrdiff_t orig_pt = PT;
1613
1614 eassert (XBUFFER (XWINDOW (selected_window)->contents) == current_buffer);
1615
1616 /* FIXME: cycling is probably not necessary because these properties
1617 can't be usefully combined anyway. */
1618 while (check_composition || check_display || check_invisible)
1619 {
1620 /* FIXME: check `intangible'. */
1621 if (check_composition
1622 && PT > BEGV && PT < ZV
1623 && (beg = composition_adjust_point (last_pt, PT)) != PT)
1624 {
1625 SET_PT (beg);
1626 check_display = check_invisible = true;
1627 }
1628 check_composition = false;
1629 if (check_display
1630 && PT > BEGV && PT < ZV
1631 && !NILP (val = get_char_property_and_overlay
1632 (make_number (PT), Qdisplay, selected_window,
1633 &overlay))
1634 && display_prop_intangible_p (val, overlay, PT, PT_BYTE)
1635 && (!OVERLAYP (overlay)
1636 ? get_property_and_range (PT, Qdisplay, &val, &beg, &end, Qnil)
1637 : (beg = OVERLAY_POSITION (OVERLAY_START (overlay)),
1638 end = OVERLAY_POSITION (OVERLAY_END (overlay))))
1639 && (beg < PT /* && end > PT <- It's always the case. */
1640 || (beg <= PT && STRINGP (val) && SCHARS (val) == 0)))
1641 {
1642 eassert (end > PT);
1643 SET_PT (PT < last_pt
1644 ? (STRINGP (val) && SCHARS (val) == 0
1645 ? max (beg - 1, BEGV)
1646 : beg)
1647 : end);
1648 check_composition = check_invisible = true;
1649 }
1650 check_display = false;
1651 if (check_invisible && PT > BEGV && PT < ZV)
1652 {
1653 int inv;
1654 bool ellipsis = false;
1655 beg = end = PT;
1656
1657 /* Find boundaries `beg' and `end' of the invisible area, if any. */
1658 while (end < ZV
1659 #if 0
1660 /* FIXME: We should stop if we find a spot between
1661 two runs of `invisible' where inserted text would
1662 be visible. This is important when we have two
1663 invisible boundaries that enclose an area: if the
1664 area is empty, we need this test in order to make
1665 it possible to place point in the middle rather
1666 than skip both boundaries. However, this code
1667 also stops anywhere in a non-sticky text-property,
1668 which breaks (e.g.) Org mode. */
1669 && (val = Fget_pos_property (make_number (end),
1670 Qinvisible, Qnil),
1671 TEXT_PROP_MEANS_INVISIBLE (val))
1672 #endif
1673 && !NILP (val = get_char_property_and_overlay
1674 (make_number (end), Qinvisible, Qnil, &overlay))
1675 && (inv = TEXT_PROP_MEANS_INVISIBLE (val)))
1676 {
1677 ellipsis = ellipsis || inv > 1
1678 || (OVERLAYP (overlay)
1679 && (!NILP (Foverlay_get (overlay, Qafter_string))
1680 || !NILP (Foverlay_get (overlay, Qbefore_string))));
1681 tmp = Fnext_single_char_property_change
1682 (make_number (end), Qinvisible, Qnil, Qnil);
1683 end = NATNUMP (tmp) ? XFASTINT (tmp) : ZV;
1684 }
1685 while (beg > BEGV
1686 #if 0
1687 && (val = Fget_pos_property (make_number (beg),
1688 Qinvisible, Qnil),
1689 TEXT_PROP_MEANS_INVISIBLE (val))
1690 #endif
1691 && !NILP (val = get_char_property_and_overlay
1692 (make_number (beg - 1), Qinvisible, Qnil, &overlay))
1693 && (inv = TEXT_PROP_MEANS_INVISIBLE (val)))
1694 {
1695 ellipsis = ellipsis || inv > 1
1696 || (OVERLAYP (overlay)
1697 && (!NILP (Foverlay_get (overlay, Qafter_string))
1698 || !NILP (Foverlay_get (overlay, Qbefore_string))));
1699 tmp = Fprevious_single_char_property_change
1700 (make_number (beg), Qinvisible, Qnil, Qnil);
1701 beg = NATNUMP (tmp) ? XFASTINT (tmp) : BEGV;
1702 }
1703
1704 /* Move away from the inside area. */
1705 if (beg < PT && end > PT)
1706 {
1707 SET_PT ((orig_pt == PT && (last_pt < beg || last_pt > end))
1708 /* We haven't moved yet (so we don't need to fear
1709 infinite-looping) and we were outside the range
1710 before (so either end of the range still corresponds
1711 to a move in the right direction): pretend we moved
1712 less than we actually did, so that we still have
1713 more freedom below in choosing which end of the range
1714 to go to. */
1715 ? (orig_pt = -1, PT < last_pt ? end : beg)
1716 /* We either have moved already or the last point
1717 was already in the range: we don't get to choose
1718 which end of the range we have to go to. */
1719 : (PT < last_pt ? beg : end));
1720 check_composition = check_display = true;
1721 }
1722 #if 0 /* This assertion isn't correct, because SET_PT may end up setting
1723 the point to something other than its argument, due to
1724 point-motion hooks, intangibility, etc. */
1725 eassert (PT == beg || PT == end);
1726 #endif
1727
1728 /* Pretend the area doesn't exist if the buffer is not
1729 modified. */
1730 if (!modified && !ellipsis && beg < end)
1731 {
1732 if (last_pt == beg && PT == end && end < ZV)
1733 (check_composition = check_display = true, SET_PT (end + 1));
1734 else if (last_pt == end && PT == beg && beg > BEGV)
1735 (check_composition = check_display = true, SET_PT (beg - 1));
1736 else if (PT == ((PT < last_pt) ? beg : end))
1737 /* We've already moved as far as we can. Trying to go
1738 to the other end would mean moving backwards and thus
1739 could lead to an infinite loop. */
1740 ;
1741 else if (val = Fget_pos_property (make_number (PT),
1742 Qinvisible, Qnil),
1743 TEXT_PROP_MEANS_INVISIBLE (val)
1744 && (val = (Fget_pos_property
1745 (make_number (PT == beg ? end : beg),
1746 Qinvisible, Qnil)),
1747 !TEXT_PROP_MEANS_INVISIBLE (val)))
1748 (check_composition = check_display = true,
1749 SET_PT (PT == beg ? end : beg));
1750 }
1751 }
1752 check_invisible = false;
1753 }
1754 }
1755
1756 /* Subroutine for safe_run_hooks: run the hook, which is ARGS[1]. */
1757
1758 static Lisp_Object
1759 safe_run_hooks_1 (ptrdiff_t nargs, Lisp_Object *args)
1760 {
1761 eassert (nargs == 2);
1762 return call0 (args[1]);
1763 }
1764
1765 /* Subroutine for safe_run_hooks: handle an error by clearing out the function
1766 from the hook. */
1767
1768 static Lisp_Object
1769 safe_run_hooks_error (Lisp_Object error, ptrdiff_t nargs, Lisp_Object *args)
1770 {
1771 eassert (nargs == 2);
1772 AUTO_STRING (format, "Error in %s (%S): %S");
1773 Lisp_Object hook = args[0];
1774 Lisp_Object fun = args[1];
1775 CALLN (Fmessage, format, hook, fun, error);
1776
1777 if (SYMBOLP (hook))
1778 {
1779 Lisp_Object val;
1780 bool found = false;
1781 Lisp_Object newval = Qnil;
1782 for (val = find_symbol_value (hook); CONSP (val); val = XCDR (val))
1783 if (EQ (fun, XCAR (val)))
1784 found = true;
1785 else
1786 newval = Fcons (XCAR (val), newval);
1787 if (found)
1788 return Fset (hook, Fnreverse (newval));
1789 /* Not found in the local part of the hook. Let's look at the global
1790 part. */
1791 newval = Qnil;
1792 for (val = (NILP (Fdefault_boundp (hook)) ? Qnil
1793 : Fdefault_value (hook));
1794 CONSP (val); val = XCDR (val))
1795 if (EQ (fun, XCAR (val)))
1796 found = true;
1797 else
1798 newval = Fcons (XCAR (val), newval);
1799 if (found)
1800 return Fset_default (hook, Fnreverse (newval));
1801 }
1802 return Qnil;
1803 }
1804
1805 static Lisp_Object
1806 safe_run_hook_funcall (ptrdiff_t nargs, Lisp_Object *args)
1807 {
1808 eassert (nargs == 2);
1809 /* Yes, run_hook_with_args works with args in the other order. */
1810 internal_condition_case_n (safe_run_hooks_1,
1811 2, ((Lisp_Object []) {args[1], args[0]}),
1812 Qt, safe_run_hooks_error);
1813 return Qnil;
1814 }
1815
1816 /* If we get an error while running the hook, cause the hook variable
1817 to be nil. Also inhibit quits, so that C-g won't cause the hook
1818 to mysteriously evaporate. */
1819
1820 void
1821 safe_run_hooks (Lisp_Object hook)
1822 {
1823 ptrdiff_t count = SPECPDL_INDEX ();
1824
1825 specbind (Qinhibit_quit, Qt);
1826 run_hook_with_args (2, ((Lisp_Object []) {hook, hook}), safe_run_hook_funcall);
1827 unbind_to (count, Qnil);
1828 }
1829
1830 \f
1831 /* Nonzero means polling for input is temporarily suppressed. */
1832
1833 int poll_suppress_count;
1834
1835
1836 #ifdef POLL_FOR_INPUT
1837
1838 /* Asynchronous timer for polling. */
1839
1840 static struct atimer *poll_timer;
1841
1842 /* Poll for input, so that we catch a C-g if it comes in. */
1843 void
1844 poll_for_input_1 (void)
1845 {
1846 if (! input_blocked_p ()
1847 && !waiting_for_input)
1848 gobble_input ();
1849 }
1850
1851 /* Timer callback function for poll_timer. TIMER is equal to
1852 poll_timer. */
1853
1854 static void
1855 poll_for_input (struct atimer *timer)
1856 {
1857 if (poll_suppress_count == 0)
1858 pending_signals = true;
1859 }
1860
1861 #endif /* POLL_FOR_INPUT */
1862
1863 /* Begin signals to poll for input, if they are appropriate.
1864 This function is called unconditionally from various places. */
1865
1866 void
1867 start_polling (void)
1868 {
1869 #ifdef POLL_FOR_INPUT
1870 /* XXX This condition was (read_socket_hook && !interrupt_input),
1871 but read_socket_hook is not global anymore. Let's pretend that
1872 it's always set. */
1873 if (!interrupt_input)
1874 {
1875 /* Turn alarm handling on unconditionally. It might have
1876 been turned off in process.c. */
1877 turn_on_atimers (1);
1878
1879 /* If poll timer doesn't exist, or we need one with
1880 a different interval, start a new one. */
1881 if (poll_timer == NULL
1882 || poll_timer->interval.tv_sec != polling_period)
1883 {
1884 time_t period = max (1, min (polling_period, TYPE_MAXIMUM (time_t)));
1885 struct timespec interval = make_timespec (period, 0);
1886
1887 if (poll_timer)
1888 cancel_atimer (poll_timer);
1889
1890 poll_timer = start_atimer (ATIMER_CONTINUOUS, interval,
1891 poll_for_input, NULL);
1892 }
1893
1894 /* Let the timer's callback function poll for input
1895 if this becomes zero. */
1896 --poll_suppress_count;
1897 }
1898 #endif
1899 }
1900
1901 /* True if we are using polling to handle input asynchronously. */
1902
1903 bool
1904 input_polling_used (void)
1905 {
1906 #ifdef POLL_FOR_INPUT
1907 /* XXX This condition was (read_socket_hook && !interrupt_input),
1908 but read_socket_hook is not global anymore. Let's pretend that
1909 it's always set. */
1910 return !interrupt_input;
1911 #else
1912 return 0;
1913 #endif
1914 }
1915
1916 /* Turn off polling. */
1917
1918 void
1919 stop_polling (void)
1920 {
1921 #ifdef POLL_FOR_INPUT
1922 /* XXX This condition was (read_socket_hook && !interrupt_input),
1923 but read_socket_hook is not global anymore. Let's pretend that
1924 it's always set. */
1925 if (!interrupt_input)
1926 ++poll_suppress_count;
1927 #endif
1928 }
1929
1930 /* Set the value of poll_suppress_count to COUNT
1931 and start or stop polling accordingly. */
1932
1933 void
1934 set_poll_suppress_count (int count)
1935 {
1936 #ifdef POLL_FOR_INPUT
1937 if (count == 0 && poll_suppress_count != 0)
1938 {
1939 poll_suppress_count = 1;
1940 start_polling ();
1941 }
1942 else if (count != 0 && poll_suppress_count == 0)
1943 {
1944 stop_polling ();
1945 }
1946 poll_suppress_count = count;
1947 #endif
1948 }
1949
1950 /* Bind polling_period to a value at least N.
1951 But don't decrease it. */
1952
1953 void
1954 bind_polling_period (int n)
1955 {
1956 #ifdef POLL_FOR_INPUT
1957 EMACS_INT new = polling_period;
1958
1959 if (n > new)
1960 new = n;
1961
1962 stop_other_atimers (poll_timer);
1963 stop_polling ();
1964 specbind (Qpolling_period, make_number (new));
1965 /* Start a new alarm with the new period. */
1966 start_polling ();
1967 #endif
1968 }
1969 \f
1970 /* Apply the control modifier to CHARACTER. */
1971
1972 int
1973 make_ctrl_char (int c)
1974 {
1975 /* Save the upper bits here. */
1976 int upper = c & ~0177;
1977
1978 if (! ASCII_CHAR_P (c))
1979 return c |= ctrl_modifier;
1980
1981 c &= 0177;
1982
1983 /* Everything in the columns containing the upper-case letters
1984 denotes a control character. */
1985 if (c >= 0100 && c < 0140)
1986 {
1987 int oc = c;
1988 c &= ~0140;
1989 /* Set the shift modifier for a control char
1990 made from a shifted letter. But only for letters! */
1991 if (oc >= 'A' && oc <= 'Z')
1992 c |= shift_modifier;
1993 }
1994
1995 /* The lower-case letters denote control characters too. */
1996 else if (c >= 'a' && c <= 'z')
1997 c &= ~0140;
1998
1999 /* Include the bits for control and shift
2000 only if the basic ASCII code can't indicate them. */
2001 else if (c >= ' ')
2002 c |= ctrl_modifier;
2003
2004 /* Replace the high bits. */
2005 c |= (upper & ~ctrl_modifier);
2006
2007 return c;
2008 }
2009
2010 /* Display the help-echo property of the character after the mouse pointer.
2011 Either show it in the echo area, or call show-help-function to display
2012 it by other means (maybe in a tooltip).
2013
2014 If HELP is nil, that means clear the previous help echo.
2015
2016 If HELP is a string, display that string. If HELP is a function,
2017 call it with OBJECT and POS as arguments; the function should
2018 return a help string or nil for none. For all other types of HELP,
2019 evaluate it to obtain a string.
2020
2021 WINDOW is the window in which the help was generated, if any.
2022 It is nil if not in a window.
2023
2024 If OBJECT is a buffer, POS is the position in the buffer where the
2025 `help-echo' text property was found.
2026
2027 If OBJECT is an overlay, that overlay has a `help-echo' property,
2028 and POS is the position in the overlay's buffer under the mouse.
2029
2030 If OBJECT is a string (an overlay string or a string displayed with
2031 the `display' property). POS is the position in that string under
2032 the mouse.
2033
2034 Note: this function may only be called with HELP nil or a string
2035 from X code running asynchronously. */
2036
2037 void
2038 show_help_echo (Lisp_Object help, Lisp_Object window, Lisp_Object object,
2039 Lisp_Object pos)
2040 {
2041 if (!NILP (help) && !STRINGP (help))
2042 {
2043 if (FUNCTIONP (help))
2044 help = safe_call (4, help, window, object, pos);
2045 else
2046 help = safe_eval (help);
2047
2048 if (!STRINGP (help))
2049 return;
2050 }
2051
2052 if (!noninteractive && STRINGP (help))
2053 {
2054 /* The mouse-fixup-help-message Lisp function can call
2055 mouse_position_hook, which resets the mouse_moved flags.
2056 This causes trouble if we are trying to read a mouse motion
2057 event (i.e., if we are inside a `track-mouse' form), so we
2058 restore the mouse_moved flag. */
2059 struct frame *f = NILP (do_mouse_tracking) ? NULL : some_mouse_moved ();
2060 help = call1 (Qmouse_fixup_help_message, help);
2061 if (f)
2062 f->mouse_moved = true;
2063 }
2064
2065 if (STRINGP (help) || NILP (help))
2066 {
2067 if (!NILP (Vshow_help_function))
2068 call1 (Vshow_help_function, Fsubstitute_command_keys (help));
2069 help_echo_showing_p = STRINGP (help);
2070 }
2071 }
2072
2073
2074 \f
2075 /* Input of single characters from keyboard. */
2076
2077 static Lisp_Object kbd_buffer_get_event (KBOARD **kbp, bool *used_mouse_menu,
2078 struct timespec *end_time);
2079 static void record_char (Lisp_Object c);
2080
2081 static Lisp_Object help_form_saved_window_configs;
2082 static void
2083 read_char_help_form_unwind (void)
2084 {
2085 Lisp_Object window_config = XCAR (help_form_saved_window_configs);
2086 help_form_saved_window_configs = XCDR (help_form_saved_window_configs);
2087 if (!NILP (window_config))
2088 Fset_window_configuration (window_config);
2089 }
2090
2091 #define STOP_POLLING \
2092 do { if (! polling_stopped_here) stop_polling (); \
2093 polling_stopped_here = true; } while (0)
2094
2095 #define RESUME_POLLING \
2096 do { if (polling_stopped_here) start_polling (); \
2097 polling_stopped_here = false; } while (0)
2098
2099 static Lisp_Object
2100 read_event_from_main_queue (struct timespec *end_time,
2101 sys_jmp_buf local_getcjmp,
2102 bool *used_mouse_menu)
2103 {
2104 Lisp_Object c = Qnil;
2105 sys_jmp_buf save_jump;
2106 KBOARD *kb IF_LINT (= NULL);
2107
2108 start:
2109
2110 /* Read from the main queue, and if that gives us something we can't use yet,
2111 we put it on the appropriate side queue and try again. */
2112
2113 if (end_time && timespec_cmp (*end_time, current_timespec ()) <= 0)
2114 return c;
2115
2116 /* Actually read a character, waiting if necessary. */
2117 save_getcjmp (save_jump);
2118 restore_getcjmp (local_getcjmp);
2119 if (!end_time)
2120 timer_start_idle ();
2121 c = kbd_buffer_get_event (&kb, used_mouse_menu, end_time);
2122 restore_getcjmp (save_jump);
2123
2124 if (! NILP (c) && (kb != current_kboard))
2125 {
2126 Lisp_Object last = KVAR (kb, kbd_queue);
2127 if (CONSP (last))
2128 {
2129 while (CONSP (XCDR (last)))
2130 last = XCDR (last);
2131 if (!NILP (XCDR (last)))
2132 emacs_abort ();
2133 }
2134 if (!CONSP (last))
2135 kset_kbd_queue (kb, list1 (c));
2136 else
2137 XSETCDR (last, list1 (c));
2138 kb->kbd_queue_has_data = true;
2139 c = Qnil;
2140 if (single_kboard)
2141 goto start;
2142 current_kboard = kb;
2143 return make_number (-2);
2144 }
2145
2146 /* Terminate Emacs in batch mode if at eof. */
2147 if (noninteractive && INTEGERP (c) && XINT (c) < 0)
2148 Fkill_emacs (make_number (1));
2149
2150 if (INTEGERP (c))
2151 {
2152 /* Add in any extra modifiers, where appropriate. */
2153 if ((extra_keyboard_modifiers & CHAR_CTL)
2154 || ((extra_keyboard_modifiers & 0177) < ' '
2155 && (extra_keyboard_modifiers & 0177) != 0))
2156 XSETINT (c, make_ctrl_char (XINT (c)));
2157
2158 /* Transfer any other modifier bits directly from
2159 extra_keyboard_modifiers to c. Ignore the actual character code
2160 in the low 16 bits of extra_keyboard_modifiers. */
2161 XSETINT (c, XINT (c) | (extra_keyboard_modifiers & ~0xff7f & ~CHAR_CTL));
2162 }
2163
2164 return c;
2165 }
2166
2167
2168
2169 /* Like `read_event_from_main_queue' but applies keyboard-coding-system
2170 to tty input. */
2171 static Lisp_Object
2172 read_decoded_event_from_main_queue (struct timespec *end_time,
2173 sys_jmp_buf local_getcjmp,
2174 Lisp_Object prev_event,
2175 bool *used_mouse_menu)
2176 {
2177 #define MAX_ENCODED_BYTES 16
2178 #ifndef WINDOWSNT
2179 Lisp_Object events[MAX_ENCODED_BYTES];
2180 int n = 0;
2181 #endif
2182 while (true)
2183 {
2184 Lisp_Object nextevt
2185 = read_event_from_main_queue (end_time, local_getcjmp,
2186 used_mouse_menu);
2187 #ifdef WINDOWSNT
2188 /* w32_console already returns decoded events. It either reads
2189 Unicode characters from the Windows keyboard input, or
2190 converts characters encoded in the current codepage into
2191 Unicode. See w32inevt.c:key_event, near its end. */
2192 return nextevt;
2193 #else
2194 struct frame *frame = XFRAME (selected_frame);
2195 struct terminal *terminal = frame->terminal;
2196 if (!((FRAME_TERMCAP_P (frame) || FRAME_MSDOS_P (frame))
2197 /* Don't apply decoding if we're just reading a raw event
2198 (e.g. reading bytes sent by the xterm to specify the position
2199 of a mouse click). */
2200 && (!EQ (prev_event, Qt))
2201 && (TERMINAL_KEYBOARD_CODING (terminal)->common_flags
2202 & CODING_REQUIRE_DECODING_MASK)))
2203 return nextevt; /* No decoding needed. */
2204 else
2205 {
2206 int meta_key = terminal->display_info.tty->meta_key;
2207 eassert (n < MAX_ENCODED_BYTES);
2208 events[n++] = nextevt;
2209 if (NATNUMP (nextevt)
2210 && XINT (nextevt) < (meta_key == 1 ? 0x80 : 0x100))
2211 { /* An encoded byte sequence, let's try to decode it. */
2212 struct coding_system *coding
2213 = TERMINAL_KEYBOARD_CODING (terminal);
2214
2215 if (raw_text_coding_system_p (coding))
2216 {
2217 int i;
2218 if (meta_key != 2)
2219 for (i = 0; i < n; i++)
2220 events[i] = make_number (XINT (events[i]) & ~0x80);
2221 }
2222 else
2223 {
2224 unsigned char src[MAX_ENCODED_BYTES];
2225 unsigned char dest[MAX_ENCODED_BYTES * MAX_MULTIBYTE_LENGTH];
2226 int i;
2227 for (i = 0; i < n; i++)
2228 src[i] = XINT (events[i]);
2229 if (meta_key != 2)
2230 for (i = 0; i < n; i++)
2231 src[i] &= ~0x80;
2232 coding->destination = dest;
2233 coding->dst_bytes = sizeof dest;
2234 decode_coding_c_string (coding, src, n, Qnil);
2235 eassert (coding->produced_char <= n);
2236 if (coding->produced_char == 0)
2237 { /* The encoded sequence is incomplete. */
2238 if (n < MAX_ENCODED_BYTES) /* Avoid buffer overflow. */
2239 continue; /* Read on! */
2240 }
2241 else
2242 {
2243 const unsigned char *p = coding->destination;
2244 eassert (coding->carryover_bytes == 0);
2245 n = 0;
2246 while (n < coding->produced_char)
2247 events[n++] = make_number (STRING_CHAR_ADVANCE (p));
2248 }
2249 }
2250 }
2251 /* Now `events' should hold decoded events.
2252 Normally, n should be equal to 1, but better not rely on it.
2253 We can only return one event here, so return the first we
2254 had and keep the others (if any) for later. */
2255 while (n > 1)
2256 Vunread_command_events
2257 = Fcons (events[--n], Vunread_command_events);
2258 return events[0];
2259 }
2260 #endif
2261 }
2262 }
2263
2264 static bool
2265 echo_keystrokes_p (void)
2266 {
2267 return (FLOATP (Vecho_keystrokes) ? XFLOAT_DATA (Vecho_keystrokes) > 0.0
2268 : INTEGERP (Vecho_keystrokes) ? XINT (Vecho_keystrokes) > 0 : false);
2269 }
2270
2271 /* Read a character from the keyboard; call the redisplay if needed. */
2272 /* commandflag 0 means do not autosave, but do redisplay.
2273 -1 means do not redisplay, but do autosave.
2274 -2 means do neither.
2275 1 means do both.
2276
2277 The argument MAP is a keymap for menu prompting.
2278
2279 PREV_EVENT is the previous input event, or nil if we are reading
2280 the first event of a key sequence (or not reading a key sequence).
2281 If PREV_EVENT is t, that is a "magic" value that says
2282 not to run input methods, but in other respects to act as if
2283 not reading a key sequence.
2284
2285 If USED_MOUSE_MENU is non-null, then set *USED_MOUSE_MENU to true
2286 if we used a mouse menu to read the input, or false otherwise. If
2287 USED_MOUSE_MENU is null, don't dereference it.
2288
2289 Value is -2 when we find input on another keyboard. A second call
2290 to read_char will read it.
2291
2292 If END_TIME is non-null, it is a pointer to a struct timespec
2293 specifying the maximum time to wait until. If no input arrives by
2294 that time, stop waiting and return nil.
2295
2296 Value is t if we showed a menu and the user rejected it. */
2297
2298 Lisp_Object
2299 read_char (int commandflag, Lisp_Object map,
2300 Lisp_Object prev_event,
2301 bool *used_mouse_menu, struct timespec *end_time)
2302 {
2303 Lisp_Object c;
2304 ptrdiff_t jmpcount;
2305 sys_jmp_buf local_getcjmp;
2306 sys_jmp_buf save_jump;
2307 Lisp_Object tem, save;
2308 volatile Lisp_Object previous_echo_area_message;
2309 volatile Lisp_Object also_record;
2310 volatile bool reread, recorded;
2311 bool volatile polling_stopped_here = false;
2312 struct kboard *orig_kboard = current_kboard;
2313
2314 also_record = Qnil;
2315
2316 c = Qnil;
2317 previous_echo_area_message = Qnil;
2318
2319 retry:
2320
2321 recorded = false;
2322
2323 if (CONSP (Vunread_post_input_method_events))
2324 {
2325 c = XCAR (Vunread_post_input_method_events);
2326 Vunread_post_input_method_events
2327 = XCDR (Vunread_post_input_method_events);
2328
2329 /* Undo what read_char_x_menu_prompt did when it unread
2330 additional keys returned by Fx_popup_menu. */
2331 if (CONSP (c)
2332 && (SYMBOLP (XCAR (c)) || INTEGERP (XCAR (c)))
2333 && NILP (XCDR (c)))
2334 c = XCAR (c);
2335
2336 reread = true;
2337 goto reread_first;
2338 }
2339 else
2340 reread = false;
2341
2342
2343 if (CONSP (Vunread_command_events))
2344 {
2345 bool was_disabled = false;
2346
2347 c = XCAR (Vunread_command_events);
2348 Vunread_command_events = XCDR (Vunread_command_events);
2349
2350 /* Undo what sit-for did when it unread additional keys
2351 inside universal-argument. */
2352
2353 if (CONSP (c) && EQ (XCAR (c), Qt))
2354 c = XCDR (c);
2355 else
2356 reread = true;
2357
2358 /* Undo what read_char_x_menu_prompt did when it unread
2359 additional keys returned by Fx_popup_menu. */
2360 if (CONSP (c)
2361 && EQ (XCDR (c), Qdisabled)
2362 && (SYMBOLP (XCAR (c)) || INTEGERP (XCAR (c))))
2363 {
2364 was_disabled = true;
2365 c = XCAR (c);
2366 }
2367
2368 /* If the queued event is something that used the mouse,
2369 set used_mouse_menu accordingly. */
2370 if (used_mouse_menu
2371 /* Also check was_disabled so last-nonmenu-event won't return
2372 a bad value when submenus are involved. (Bug#447) */
2373 && (EQ (c, Qtool_bar) || EQ (c, Qmenu_bar) || was_disabled))
2374 *used_mouse_menu = true;
2375
2376 goto reread_for_input_method;
2377 }
2378
2379 if (CONSP (Vunread_input_method_events))
2380 {
2381 c = XCAR (Vunread_input_method_events);
2382 Vunread_input_method_events = XCDR (Vunread_input_method_events);
2383
2384 /* Undo what read_char_x_menu_prompt did when it unread
2385 additional keys returned by Fx_popup_menu. */
2386 if (CONSP (c)
2387 && (SYMBOLP (XCAR (c)) || INTEGERP (XCAR (c)))
2388 && NILP (XCDR (c)))
2389 c = XCAR (c);
2390 reread = true;
2391 goto reread_for_input_method;
2392 }
2393
2394 if (!NILP (Vexecuting_kbd_macro))
2395 {
2396 /* We set this to Qmacro; since that's not a frame, nobody will
2397 try to switch frames on us, and the selected window will
2398 remain unchanged.
2399
2400 Since this event came from a macro, it would be misleading to
2401 leave internal_last_event_frame set to wherever the last
2402 real event came from. Normally, a switch-frame event selects
2403 internal_last_event_frame after each command is read, but
2404 events read from a macro should never cause a new frame to be
2405 selected. */
2406 Vlast_event_frame = internal_last_event_frame = Qmacro;
2407
2408 /* Exit the macro if we are at the end.
2409 Also, some things replace the macro with t
2410 to force an early exit. */
2411 if (EQ (Vexecuting_kbd_macro, Qt)
2412 || executing_kbd_macro_index >= XFASTINT (Flength (Vexecuting_kbd_macro)))
2413 {
2414 XSETINT (c, -1);
2415 goto exit;
2416 }
2417
2418 c = Faref (Vexecuting_kbd_macro, make_number (executing_kbd_macro_index));
2419 if (STRINGP (Vexecuting_kbd_macro)
2420 && (XFASTINT (c) & 0x80) && (XFASTINT (c) <= 0xff))
2421 XSETFASTINT (c, CHAR_META | (XFASTINT (c) & ~0x80));
2422
2423 executing_kbd_macro_index++;
2424
2425 goto from_macro;
2426 }
2427
2428 if (!NILP (unread_switch_frame))
2429 {
2430 c = unread_switch_frame;
2431 unread_switch_frame = Qnil;
2432
2433 /* This event should make it into this_command_keys, and get echoed
2434 again, so we do not set `reread'. */
2435 goto reread_first;
2436 }
2437
2438 /* If redisplay was requested. */
2439 if (commandflag >= 0)
2440 {
2441 bool echo_current = EQ (echo_message_buffer, echo_area_buffer[0]);
2442
2443 /* If there is pending input, process any events which are not
2444 user-visible, such as X selection_request events. */
2445 if (input_pending
2446 || detect_input_pending_run_timers (0))
2447 swallow_events (false); /* May clear input_pending. */
2448
2449 /* Redisplay if no pending input. */
2450 while (!(input_pending
2451 && (input_was_pending || !redisplay_dont_pause)))
2452 {
2453 input_was_pending = input_pending;
2454 if (help_echo_showing_p && !EQ (selected_window, minibuf_window))
2455 redisplay_preserve_echo_area (5);
2456 else
2457 redisplay ();
2458
2459 if (!input_pending)
2460 /* Normal case: no input arrived during redisplay. */
2461 break;
2462
2463 /* Input arrived and pre-empted redisplay.
2464 Process any events which are not user-visible. */
2465 swallow_events (false);
2466 /* If that cleared input_pending, try again to redisplay. */
2467 }
2468
2469 /* Prevent the redisplay we just did
2470 from messing up echoing of the input after the prompt. */
2471 if (commandflag == 0 && echo_current)
2472 echo_message_buffer = echo_area_buffer[0];
2473
2474 }
2475
2476 /* Message turns off echoing unless more keystrokes turn it on again.
2477
2478 The code in 20.x for the condition was
2479
2480 1. echo_area_glyphs && *echo_area_glyphs
2481 2. && echo_area_glyphs != current_kboard->echobuf
2482 3. && ok_to_echo_at_next_pause != echo_area_glyphs
2483
2484 (1) means there's a current message displayed
2485
2486 (2) means it's not the message from echoing from the current
2487 kboard.
2488
2489 (3) There's only one place in 20.x where ok_to_echo_at_next_pause
2490 is set to a non-null value. This is done in read_char and it is
2491 set to echo_area_glyphs. That means
2492 ok_to_echo_at_next_pause is either null or
2493 current_kboard->echobuf with the appropriate current_kboard at
2494 that time.
2495
2496 So, condition (3) means in clear text ok_to_echo_at_next_pause
2497 must be either null, or the current message isn't from echoing at
2498 all, or it's from echoing from a different kboard than the
2499 current one. */
2500
2501 if (/* There currently is something in the echo area. */
2502 !NILP (echo_area_buffer[0])
2503 && (/* It's an echo from a different kboard. */
2504 echo_kboard != current_kboard
2505 /* Or we explicitly allow overwriting whatever there is. */
2506 || ok_to_echo_at_next_pause == NULL))
2507 cancel_echoing ();
2508 else
2509 echo_dash ();
2510
2511 /* Try reading a character via menu prompting in the minibuf.
2512 Try this before the sit-for, because the sit-for
2513 would do the wrong thing if we are supposed to do
2514 menu prompting. If EVENT_HAS_PARAMETERS then we are reading
2515 after a mouse event so don't try a minibuf menu. */
2516 c = Qnil;
2517 if (KEYMAPP (map) && INTERACTIVE
2518 && !NILP (prev_event) && ! EVENT_HAS_PARAMETERS (prev_event)
2519 /* Don't bring up a menu if we already have another event. */
2520 && NILP (Vunread_command_events)
2521 && !detect_input_pending_run_timers (0))
2522 {
2523 c = read_char_minibuf_menu_prompt (commandflag, map);
2524
2525 if (INTEGERP (c) && XINT (c) == -2)
2526 return c; /* wrong_kboard_jmpbuf */
2527
2528 if (! NILP (c))
2529 goto exit;
2530 }
2531
2532 /* Make a longjmp point for quits to use, but don't alter getcjmp just yet.
2533 We will do that below, temporarily for short sections of code,
2534 when appropriate. local_getcjmp must be in effect
2535 around any call to sit_for or kbd_buffer_get_event;
2536 it *must not* be in effect when we call redisplay. */
2537
2538 jmpcount = SPECPDL_INDEX ();
2539 if (sys_setjmp (local_getcjmp))
2540 {
2541 /* Handle quits while reading the keyboard. */
2542 /* We must have saved the outer value of getcjmp here,
2543 so restore it now. */
2544 restore_getcjmp (save_jump);
2545 pthread_sigmask (SIG_SETMASK, &empty_mask, 0);
2546 unbind_to (jmpcount, Qnil);
2547 XSETINT (c, quit_char);
2548 internal_last_event_frame = selected_frame;
2549 Vlast_event_frame = internal_last_event_frame;
2550 /* If we report the quit char as an event,
2551 don't do so more than once. */
2552 if (!NILP (Vinhibit_quit))
2553 Vquit_flag = Qnil;
2554
2555 {
2556 KBOARD *kb = FRAME_KBOARD (XFRAME (selected_frame));
2557 if (kb != current_kboard)
2558 {
2559 Lisp_Object last = KVAR (kb, kbd_queue);
2560 /* We shouldn't get here if we were in single-kboard mode! */
2561 if (single_kboard)
2562 emacs_abort ();
2563 if (CONSP (last))
2564 {
2565 while (CONSP (XCDR (last)))
2566 last = XCDR (last);
2567 if (!NILP (XCDR (last)))
2568 emacs_abort ();
2569 }
2570 if (!CONSP (last))
2571 kset_kbd_queue (kb, list1 (c));
2572 else
2573 XSETCDR (last, list1 (c));
2574 kb->kbd_queue_has_data = true;
2575 current_kboard = kb;
2576 return make_number (-2); /* wrong_kboard_jmpbuf */
2577 }
2578 }
2579 goto non_reread;
2580 }
2581
2582 /* Start idle timers if no time limit is supplied. We don't do it
2583 if a time limit is supplied to avoid an infinite recursion in the
2584 situation where an idle timer calls `sit-for'. */
2585
2586 if (!end_time)
2587 timer_start_idle ();
2588
2589 /* If in middle of key sequence and minibuffer not active,
2590 start echoing if enough time elapses. */
2591
2592 if (minibuf_level == 0
2593 && !end_time
2594 && !current_kboard->immediate_echo
2595 && (this_command_key_count > 0
2596 || !NILP (call0 (Qinternal_echo_keystrokes_prefix)))
2597 && ! noninteractive
2598 && echo_keystrokes_p ()
2599 && (/* No message. */
2600 NILP (echo_area_buffer[0])
2601 /* Or empty message. */
2602 || (BUF_BEG (XBUFFER (echo_area_buffer[0]))
2603 == BUF_Z (XBUFFER (echo_area_buffer[0])))
2604 /* Or already echoing from same kboard. */
2605 || (echo_kboard && ok_to_echo_at_next_pause == echo_kboard)
2606 /* Or not echoing before and echoing allowed. */
2607 || (!echo_kboard && ok_to_echo_at_next_pause)))
2608 {
2609 /* After a mouse event, start echoing right away.
2610 This is because we are probably about to display a menu,
2611 and we don't want to delay before doing so. */
2612 if (EVENT_HAS_PARAMETERS (prev_event))
2613 echo_now ();
2614 else
2615 {
2616 Lisp_Object tem0;
2617
2618 save_getcjmp (save_jump);
2619 restore_getcjmp (local_getcjmp);
2620 tem0 = sit_for (Vecho_keystrokes, 1, 1);
2621 restore_getcjmp (save_jump);
2622 if (EQ (tem0, Qt)
2623 && ! CONSP (Vunread_command_events))
2624 echo_now ();
2625 }
2626 }
2627
2628 /* Maybe auto save due to number of keystrokes. */
2629
2630 if (commandflag != 0 && commandflag != -2
2631 && auto_save_interval > 0
2632 && num_nonmacro_input_events - last_auto_save > max (auto_save_interval, 20)
2633 && !detect_input_pending_run_timers (0))
2634 {
2635 Fdo_auto_save (Qnil, Qnil);
2636 /* Hooks can actually change some buffers in auto save. */
2637 redisplay ();
2638 }
2639
2640 /* Try reading using an X menu.
2641 This is never confused with reading using the minibuf
2642 because the recursive call of read_char in read_char_minibuf_menu_prompt
2643 does not pass on any keymaps. */
2644
2645 if (KEYMAPP (map) && INTERACTIVE
2646 && !NILP (prev_event)
2647 && EVENT_HAS_PARAMETERS (prev_event)
2648 && !EQ (XCAR (prev_event), Qmenu_bar)
2649 && !EQ (XCAR (prev_event), Qtool_bar)
2650 /* Don't bring up a menu if we already have another event. */
2651 && NILP (Vunread_command_events))
2652 {
2653 c = read_char_x_menu_prompt (map, prev_event, used_mouse_menu);
2654
2655 /* Now that we have read an event, Emacs is not idle. */
2656 if (!end_time)
2657 timer_stop_idle ();
2658
2659 goto exit;
2660 }
2661
2662 /* Maybe autosave and/or garbage collect due to idleness. */
2663
2664 if (INTERACTIVE && NILP (c))
2665 {
2666 int delay_level;
2667 ptrdiff_t buffer_size;
2668
2669 /* Slow down auto saves logarithmically in size of current buffer,
2670 and garbage collect while we're at it. */
2671 if (! MINI_WINDOW_P (XWINDOW (selected_window)))
2672 last_non_minibuf_size = Z - BEG;
2673 buffer_size = (last_non_minibuf_size >> 8) + 1;
2674 delay_level = 0;
2675 while (buffer_size > 64)
2676 delay_level++, buffer_size -= buffer_size >> 2;
2677 if (delay_level < 4) delay_level = 4;
2678 /* delay_level is 4 for files under around 50k, 7 at 100k,
2679 9 at 200k, 11 at 300k, and 12 at 500k. It is 15 at 1 meg. */
2680
2681 /* Auto save if enough time goes by without input. */
2682 if (commandflag != 0 && commandflag != -2
2683 && num_nonmacro_input_events > last_auto_save
2684 && INTEGERP (Vauto_save_timeout)
2685 && XINT (Vauto_save_timeout) > 0)
2686 {
2687 Lisp_Object tem0;
2688 EMACS_INT timeout = XFASTINT (Vauto_save_timeout);
2689
2690 timeout = min (timeout, MOST_POSITIVE_FIXNUM / delay_level * 4);
2691 timeout = delay_level * timeout / 4;
2692 save_getcjmp (save_jump);
2693 restore_getcjmp (local_getcjmp);
2694 tem0 = sit_for (make_number (timeout), 1, 1);
2695 restore_getcjmp (save_jump);
2696
2697 if (EQ (tem0, Qt)
2698 && ! CONSP (Vunread_command_events))
2699 {
2700 Fdo_auto_save (Qnil, Qnil);
2701 redisplay ();
2702 }
2703 }
2704
2705 /* If there is still no input available, ask for GC. */
2706 if (!detect_input_pending_run_timers (0))
2707 maybe_gc ();
2708 }
2709
2710 /* Notify the caller if an autosave hook, or a timer, sentinel or
2711 filter in the sit_for calls above have changed the current
2712 kboard. This could happen if they use the minibuffer or start a
2713 recursive edit, like the fancy splash screen in server.el's
2714 filter. If this longjmp wasn't here, read_key_sequence would
2715 interpret the next key sequence using the wrong translation
2716 tables and function keymaps. */
2717 if (NILP (c) && current_kboard != orig_kboard)
2718 return make_number (-2); /* wrong_kboard_jmpbuf */
2719
2720 /* If this has become non-nil here, it has been set by a timer
2721 or sentinel or filter. */
2722 if (CONSP (Vunread_command_events))
2723 {
2724 c = XCAR (Vunread_command_events);
2725 Vunread_command_events = XCDR (Vunread_command_events);
2726
2727 if (CONSP (c) && EQ (XCAR (c), Qt))
2728 c = XCDR (c);
2729 else
2730 reread = true;
2731 }
2732
2733 /* Read something from current KBOARD's side queue, if possible. */
2734
2735 if (NILP (c))
2736 {
2737 if (current_kboard->kbd_queue_has_data)
2738 {
2739 if (!CONSP (KVAR (current_kboard, kbd_queue)))
2740 emacs_abort ();
2741 c = XCAR (KVAR (current_kboard, kbd_queue));
2742 kset_kbd_queue (current_kboard,
2743 XCDR (KVAR (current_kboard, kbd_queue)));
2744 if (NILP (KVAR (current_kboard, kbd_queue)))
2745 current_kboard->kbd_queue_has_data = false;
2746 input_pending = readable_events (0);
2747 if (EVENT_HAS_PARAMETERS (c)
2748 && EQ (EVENT_HEAD_KIND (EVENT_HEAD (c)), Qswitch_frame))
2749 internal_last_event_frame = XCAR (XCDR (c));
2750 Vlast_event_frame = internal_last_event_frame;
2751 }
2752 }
2753
2754 /* If current_kboard's side queue is empty check the other kboards.
2755 If one of them has data that we have not yet seen here,
2756 switch to it and process the data waiting for it.
2757
2758 Note: if the events queued up for another kboard
2759 have already been seen here, and therefore are not a complete command,
2760 the kbd_queue_has_data field is 0, so we skip that kboard here.
2761 That's to avoid an infinite loop switching between kboards here. */
2762 if (NILP (c) && !single_kboard)
2763 {
2764 KBOARD *kb;
2765 for (kb = all_kboards; kb; kb = kb->next_kboard)
2766 if (kb->kbd_queue_has_data)
2767 {
2768 current_kboard = kb;
2769 return make_number (-2); /* wrong_kboard_jmpbuf */
2770 }
2771 }
2772
2773 wrong_kboard:
2774
2775 STOP_POLLING;
2776
2777 if (NILP (c))
2778 {
2779 c = read_decoded_event_from_main_queue (end_time, local_getcjmp,
2780 prev_event, used_mouse_menu);
2781 if (NILP (c) && end_time
2782 && timespec_cmp (*end_time, current_timespec ()) <= 0)
2783 {
2784 goto exit;
2785 }
2786
2787 if (EQ (c, make_number (-2)))
2788 return c;
2789 }
2790
2791 non_reread:
2792
2793 if (!end_time)
2794 timer_stop_idle ();
2795 RESUME_POLLING;
2796
2797 if (NILP (c))
2798 {
2799 if (commandflag >= 0
2800 && !input_pending && !detect_input_pending_run_timers (0))
2801 redisplay ();
2802
2803 goto wrong_kboard;
2804 }
2805
2806 /* Buffer switch events are only for internal wakeups
2807 so don't show them to the user.
2808 Also, don't record a key if we already did. */
2809 if (BUFFERP (c))
2810 goto exit;
2811
2812 /* Process special events within read_char
2813 and loop around to read another event. */
2814 save = Vquit_flag;
2815 Vquit_flag = Qnil;
2816 tem = access_keymap (get_keymap (Vspecial_event_map, 0, 1), c, 0, 0, 1);
2817 Vquit_flag = save;
2818
2819 if (!NILP (tem))
2820 {
2821 struct buffer *prev_buffer = current_buffer;
2822 last_input_event = c;
2823 call4 (Qcommand_execute, tem, Qnil, Fvector (1, &last_input_event), Qt);
2824
2825 if (CONSP (c) && EQ (XCAR (c), Qselect_window) && !end_time)
2826 /* We stopped being idle for this event; undo that. This
2827 prevents automatic window selection (under
2828 mouse_autoselect_window from acting as a real input event, for
2829 example banishing the mouse under mouse-avoidance-mode. */
2830 timer_resume_idle ();
2831
2832 if (current_buffer != prev_buffer)
2833 {
2834 /* The command may have changed the keymaps. Pretend there
2835 is input in another keyboard and return. This will
2836 recalculate keymaps. */
2837 c = make_number (-2);
2838 goto exit;
2839 }
2840 else
2841 goto retry;
2842 }
2843
2844 /* Handle things that only apply to characters. */
2845 if (INTEGERP (c))
2846 {
2847 /* If kbd_buffer_get_event gave us an EOF, return that. */
2848 if (XINT (c) == -1)
2849 goto exit;
2850
2851 if ((STRINGP (KVAR (current_kboard, Vkeyboard_translate_table))
2852 && UNSIGNED_CMP (XFASTINT (c), <,
2853 SCHARS (KVAR (current_kboard,
2854 Vkeyboard_translate_table))))
2855 || (VECTORP (KVAR (current_kboard, Vkeyboard_translate_table))
2856 && UNSIGNED_CMP (XFASTINT (c), <,
2857 ASIZE (KVAR (current_kboard,
2858 Vkeyboard_translate_table))))
2859 || (CHAR_TABLE_P (KVAR (current_kboard, Vkeyboard_translate_table))
2860 && CHARACTERP (c)))
2861 {
2862 Lisp_Object d;
2863 d = Faref (KVAR (current_kboard, Vkeyboard_translate_table), c);
2864 /* nil in keyboard-translate-table means no translation. */
2865 if (!NILP (d))
2866 c = d;
2867 }
2868 }
2869
2870 /* If this event is a mouse click in the menu bar,
2871 return just menu-bar for now. Modify the mouse click event
2872 so we won't do this twice, then queue it up. */
2873 if (EVENT_HAS_PARAMETERS (c)
2874 && CONSP (XCDR (c))
2875 && CONSP (EVENT_START (c))
2876 && CONSP (XCDR (EVENT_START (c))))
2877 {
2878 Lisp_Object posn;
2879
2880 posn = POSN_POSN (EVENT_START (c));
2881 /* Handle menu-bar events:
2882 insert the dummy prefix event `menu-bar'. */
2883 if (EQ (posn, Qmenu_bar) || EQ (posn, Qtool_bar))
2884 {
2885 /* Change menu-bar to (menu-bar) as the event "position". */
2886 POSN_SET_POSN (EVENT_START (c), list1 (posn));
2887
2888 also_record = c;
2889 Vunread_command_events = Fcons (c, Vunread_command_events);
2890 c = posn;
2891 }
2892 }
2893
2894 /* Store these characters into recent_keys, the dribble file if any,
2895 and the keyboard macro being defined, if any. */
2896 record_char (c);
2897 recorded = true;
2898 if (! NILP (also_record))
2899 record_char (also_record);
2900
2901 /* Wipe the echo area.
2902 But first, if we are about to use an input method,
2903 save the echo area contents for it to refer to. */
2904 if (INTEGERP (c)
2905 && ! NILP (Vinput_method_function)
2906 && ' ' <= XINT (c) && XINT (c) < 256 && XINT (c) != 127)
2907 {
2908 previous_echo_area_message = Fcurrent_message ();
2909 Vinput_method_previous_message = previous_echo_area_message;
2910 }
2911
2912 /* Now wipe the echo area, except for help events which do their
2913 own stuff with the echo area. */
2914 if (!CONSP (c)
2915 || (!(EQ (Qhelp_echo, XCAR (c)))
2916 && !(EQ (Qswitch_frame, XCAR (c)))
2917 /* Don't wipe echo area for select window events: These might
2918 get delayed via `mouse-autoselect-window' (Bug#11304). */
2919 && !(EQ (Qselect_window, XCAR (c)))))
2920 {
2921 if (!NILP (echo_area_buffer[0]))
2922 {
2923 safe_run_hooks (Qecho_area_clear_hook);
2924 clear_message (1, 0);
2925 }
2926 }
2927
2928 reread_for_input_method:
2929 from_macro:
2930 /* Pass this to the input method, if appropriate. */
2931 if (INTEGERP (c)
2932 && ! NILP (Vinput_method_function)
2933 /* Don't run the input method within a key sequence,
2934 after the first event of the key sequence. */
2935 && NILP (prev_event)
2936 && ' ' <= XINT (c) && XINT (c) < 256 && XINT (c) != 127)
2937 {
2938 Lisp_Object keys;
2939 ptrdiff_t key_count;
2940 ptrdiff_t command_key_start;
2941 ptrdiff_t count = SPECPDL_INDEX ();
2942
2943 /* Save the echo status. */
2944 bool saved_immediate_echo = current_kboard->immediate_echo;
2945 struct kboard *saved_ok_to_echo = ok_to_echo_at_next_pause;
2946 Lisp_Object saved_echo_string = KVAR (current_kboard, echo_string);
2947 Lisp_Object saved_echo_prompt = KVAR (current_kboard, echo_prompt);
2948
2949 /* Save the this_command_keys status. */
2950 key_count = this_command_key_count;
2951 command_key_start = this_single_command_key_start;
2952
2953 if (key_count > 0)
2954 keys = Fcopy_sequence (this_command_keys);
2955 else
2956 keys = Qnil;
2957
2958 /* Clear out this_command_keys. */
2959 this_command_key_count = 0;
2960 this_single_command_key_start = 0;
2961
2962 /* Now wipe the echo area. */
2963 if (!NILP (echo_area_buffer[0]))
2964 safe_run_hooks (Qecho_area_clear_hook);
2965 clear_message (1, 0);
2966 echo_truncate (0);
2967
2968 /* If we are not reading a key sequence,
2969 never use the echo area. */
2970 if (!KEYMAPP (map))
2971 {
2972 specbind (Qinput_method_use_echo_area, Qt);
2973 }
2974
2975 /* Call the input method. */
2976 tem = call1 (Vinput_method_function, c);
2977
2978 tem = unbind_to (count, tem);
2979
2980 /* Restore the saved echoing state
2981 and this_command_keys state. */
2982 this_command_key_count = key_count;
2983 this_single_command_key_start = command_key_start;
2984 if (key_count > 0)
2985 this_command_keys = keys;
2986
2987 cancel_echoing ();
2988 ok_to_echo_at_next_pause = saved_ok_to_echo;
2989 kset_echo_string (current_kboard, saved_echo_string);
2990 kset_echo_prompt (current_kboard, saved_echo_prompt);
2991 if (saved_immediate_echo)
2992 echo_now ();
2993
2994 /* The input method can return no events. */
2995 if (! CONSP (tem))
2996 {
2997 /* Bring back the previous message, if any. */
2998 if (! NILP (previous_echo_area_message))
2999 message_with_string ("%s", previous_echo_area_message, 0);
3000 goto retry;
3001 }
3002 /* It returned one event or more. */
3003 c = XCAR (tem);
3004 Vunread_post_input_method_events
3005 = nconc2 (XCDR (tem), Vunread_post_input_method_events);
3006 }
3007 /* When we consume events from the various unread-*-events lists, we
3008 bypass the code that records input, so record these events now if
3009 they were not recorded already. */
3010 if (!recorded)
3011 {
3012 record_char (c);
3013 recorded = true;
3014 }
3015
3016 reread_first:
3017
3018 /* Display help if not echoing. */
3019 if (CONSP (c) && EQ (XCAR (c), Qhelp_echo))
3020 {
3021 /* (help-echo FRAME HELP WINDOW OBJECT POS). */
3022 Lisp_Object help, object, position, window, htem;
3023
3024 htem = Fcdr (XCDR (c));
3025 help = Fcar (htem);
3026 htem = Fcdr (htem);
3027 window = Fcar (htem);
3028 htem = Fcdr (htem);
3029 object = Fcar (htem);
3030 htem = Fcdr (htem);
3031 position = Fcar (htem);
3032
3033 show_help_echo (help, window, object, position);
3034
3035 /* We stopped being idle for this event; undo that. */
3036 if (!end_time)
3037 timer_resume_idle ();
3038 goto retry;
3039 }
3040
3041 if ((! reread || this_command_key_count == 0)
3042 && !end_time)
3043 {
3044
3045 /* Don't echo mouse motion events. */
3046 if (! (EVENT_HAS_PARAMETERS (c)
3047 && EQ (EVENT_HEAD_KIND (EVENT_HEAD (c)), Qmouse_movement)))
3048 /* Once we reread a character, echoing can happen
3049 the next time we pause to read a new one. */
3050 ok_to_echo_at_next_pause = current_kboard;
3051
3052 /* Record this character as part of the current key. */
3053 add_command_key (c);
3054 if (! NILP (also_record))
3055 add_command_key (also_record);
3056
3057 echo_update ();
3058 }
3059
3060 last_input_event = c;
3061 num_input_events++;
3062
3063 /* Process the help character specially if enabled. */
3064 if (!NILP (Vhelp_form) && help_char_p (c))
3065 {
3066 ptrdiff_t count = SPECPDL_INDEX ();
3067
3068 help_form_saved_window_configs
3069 = Fcons (Fcurrent_window_configuration (Qnil),
3070 help_form_saved_window_configs);
3071 record_unwind_protect_void (read_char_help_form_unwind);
3072 call0 (Qhelp_form_show);
3073
3074 cancel_echoing ();
3075 do
3076 {
3077 c = read_char (0, Qnil, Qnil, 0, NULL);
3078 if (EVENT_HAS_PARAMETERS (c)
3079 && EQ (EVENT_HEAD_KIND (EVENT_HEAD (c)), Qmouse_click))
3080 XSETCAR (help_form_saved_window_configs, Qnil);
3081 }
3082 while (BUFFERP (c));
3083 /* Remove the help from the frame. */
3084 unbind_to (count, Qnil);
3085
3086 redisplay ();
3087 if (EQ (c, make_number (040)))
3088 {
3089 cancel_echoing ();
3090 do
3091 c = read_char (0, Qnil, Qnil, 0, NULL);
3092 while (BUFFERP (c));
3093 }
3094 }
3095
3096 exit:
3097 RESUME_POLLING;
3098 input_was_pending = input_pending;
3099 return c;
3100 }
3101
3102 /* Record a key that came from a mouse menu.
3103 Record it for echoing, for this-command-keys, and so on. */
3104
3105 static void
3106 record_menu_key (Lisp_Object c)
3107 {
3108 /* Wipe the echo area. */
3109 clear_message (1, 0);
3110
3111 record_char (c);
3112
3113 /* Once we reread a character, echoing can happen
3114 the next time we pause to read a new one. */
3115 ok_to_echo_at_next_pause = NULL;
3116
3117 /* Record this character as part of the current key. */
3118 add_command_key (c);
3119 echo_update ();
3120
3121 /* Re-reading in the middle of a command. */
3122 last_input_event = c;
3123 num_input_events++;
3124 }
3125
3126 /* Return true if should recognize C as "the help character". */
3127
3128 static bool
3129 help_char_p (Lisp_Object c)
3130 {
3131 Lisp_Object tail;
3132
3133 if (EQ (c, Vhelp_char))
3134 return 1;
3135 for (tail = Vhelp_event_list; CONSP (tail); tail = XCDR (tail))
3136 if (EQ (c, XCAR (tail)))
3137 return 1;
3138 return 0;
3139 }
3140
3141 /* Record the input event C in various ways. */
3142
3143 static void
3144 record_char (Lisp_Object c)
3145 {
3146 int recorded = 0;
3147
3148 if (CONSP (c) && (EQ (XCAR (c), Qhelp_echo) || EQ (XCAR (c), Qmouse_movement)))
3149 {
3150 /* To avoid filling recent_keys with help-echo and mouse-movement
3151 events, we filter out repeated help-echo events, only store the
3152 first and last in a series of mouse-movement events, and don't
3153 store repeated help-echo events which are only separated by
3154 mouse-movement events. */
3155
3156 Lisp_Object ev1, ev2, ev3;
3157 int ix1, ix2, ix3;
3158
3159 if ((ix1 = recent_keys_index - 1) < 0)
3160 ix1 = NUM_RECENT_KEYS - 1;
3161 ev1 = AREF (recent_keys, ix1);
3162
3163 if ((ix2 = ix1 - 1) < 0)
3164 ix2 = NUM_RECENT_KEYS - 1;
3165 ev2 = AREF (recent_keys, ix2);
3166
3167 if ((ix3 = ix2 - 1) < 0)
3168 ix3 = NUM_RECENT_KEYS - 1;
3169 ev3 = AREF (recent_keys, ix3);
3170
3171 if (EQ (XCAR (c), Qhelp_echo))
3172 {
3173 /* Don't record `help-echo' in recent_keys unless it shows some help
3174 message, and a different help than the previously recorded
3175 event. */
3176 Lisp_Object help, last_help;
3177
3178 help = Fcar_safe (Fcdr_safe (XCDR (c)));
3179 if (!STRINGP (help))
3180 recorded = 1;
3181 else if (CONSP (ev1) && EQ (XCAR (ev1), Qhelp_echo)
3182 && (last_help = Fcar_safe (Fcdr_safe (XCDR (ev1))), EQ (last_help, help)))
3183 recorded = 1;
3184 else if (CONSP (ev1) && EQ (XCAR (ev1), Qmouse_movement)
3185 && CONSP (ev2) && EQ (XCAR (ev2), Qhelp_echo)
3186 && (last_help = Fcar_safe (Fcdr_safe (XCDR (ev2))), EQ (last_help, help)))
3187 recorded = -1;
3188 else if (CONSP (ev1) && EQ (XCAR (ev1), Qmouse_movement)
3189 && CONSP (ev2) && EQ (XCAR (ev2), Qmouse_movement)
3190 && CONSP (ev3) && EQ (XCAR (ev3), Qhelp_echo)
3191 && (last_help = Fcar_safe (Fcdr_safe (XCDR (ev3))), EQ (last_help, help)))
3192 recorded = -2;
3193 }
3194 else if (EQ (XCAR (c), Qmouse_movement))
3195 {
3196 /* Only record one pair of `mouse-movement' on a window in recent_keys.
3197 So additional mouse movement events replace the last element. */
3198 Lisp_Object last_window, window;
3199
3200 window = Fcar_safe (Fcar_safe (XCDR (c)));
3201 if (CONSP (ev1) && EQ (XCAR (ev1), Qmouse_movement)
3202 && (last_window = Fcar_safe (Fcar_safe (XCDR (ev1))), EQ (last_window, window))
3203 && CONSP (ev2) && EQ (XCAR (ev2), Qmouse_movement)
3204 && (last_window = Fcar_safe (Fcar_safe (XCDR (ev2))), EQ (last_window, window)))
3205 {
3206 ASET (recent_keys, ix1, c);
3207 recorded = 1;
3208 }
3209 }
3210 }
3211 else
3212 store_kbd_macro_char (c);
3213
3214 if (!recorded)
3215 {
3216 total_keys += total_keys < NUM_RECENT_KEYS;
3217 ASET (recent_keys, recent_keys_index, c);
3218 if (++recent_keys_index >= NUM_RECENT_KEYS)
3219 recent_keys_index = 0;
3220 }
3221 else if (recorded < 0)
3222 {
3223 /* We need to remove one or two events from recent_keys.
3224 To do this, we simply put nil at those events and move the
3225 recent_keys_index backwards over those events. Usually,
3226 users will never see those nil events, as they will be
3227 overwritten by the command keys entered to see recent_keys
3228 (e.g. C-h l). */
3229
3230 while (recorded++ < 0 && total_keys > 0)
3231 {
3232 if (total_keys < NUM_RECENT_KEYS)
3233 total_keys--;
3234 if (--recent_keys_index < 0)
3235 recent_keys_index = NUM_RECENT_KEYS - 1;
3236 ASET (recent_keys, recent_keys_index, Qnil);
3237 }
3238 }
3239
3240 num_nonmacro_input_events++;
3241
3242 /* Write c to the dribble file. If c is a lispy event, write
3243 the event's symbol to the dribble file, in <brackets>. Bleaugh.
3244 If you, dear reader, have a better idea, you've got the source. :-) */
3245 if (dribble)
3246 {
3247 block_input ();
3248 if (INTEGERP (c))
3249 {
3250 if (XUINT (c) < 0x100)
3251 putc (XUINT (c), dribble);
3252 else
3253 fprintf (dribble, " 0x%"pI"x", XUINT (c));
3254 }
3255 else
3256 {
3257 Lisp_Object dribblee;
3258
3259 /* If it's a structured event, take the event header. */
3260 dribblee = EVENT_HEAD (c);
3261
3262 if (SYMBOLP (dribblee))
3263 {
3264 putc ('<', dribble);
3265 fwrite (SDATA (SYMBOL_NAME (dribblee)), sizeof (char),
3266 SBYTES (SYMBOL_NAME (dribblee)),
3267 dribble);
3268 putc ('>', dribble);
3269 }
3270 }
3271
3272 fflush (dribble);
3273 unblock_input ();
3274 }
3275 }
3276
3277 /* Copy out or in the info on where C-g should throw to.
3278 This is used when running Lisp code from within get_char,
3279 in case get_char is called recursively.
3280 See read_process_output. */
3281
3282 static void
3283 save_getcjmp (sys_jmp_buf temp)
3284 {
3285 memcpy (temp, getcjmp, sizeof getcjmp);
3286 }
3287
3288 static void
3289 restore_getcjmp (sys_jmp_buf temp)
3290 {
3291 memcpy (getcjmp, temp, sizeof getcjmp);
3292 }
3293 \f
3294 /* Low level keyboard/mouse input.
3295 kbd_buffer_store_event places events in kbd_buffer, and
3296 kbd_buffer_get_event retrieves them. */
3297
3298 /* Return true if there are any events in the queue that read-char
3299 would return. If this returns false, a read-char would block. */
3300 static bool
3301 readable_events (int flags)
3302 {
3303 if (flags & READABLE_EVENTS_DO_TIMERS_NOW)
3304 timer_check ();
3305
3306 /* If the buffer contains only FOCUS_IN_EVENT events, and
3307 READABLE_EVENTS_FILTER_EVENTS is set, report it as empty. */
3308 if (kbd_fetch_ptr != kbd_store_ptr)
3309 {
3310 if (flags & (READABLE_EVENTS_FILTER_EVENTS
3311 #ifdef USE_TOOLKIT_SCROLL_BARS
3312 | READABLE_EVENTS_IGNORE_SQUEEZABLES
3313 #endif
3314 ))
3315 {
3316 union buffered_input_event *event;
3317
3318 event = ((kbd_fetch_ptr < kbd_buffer + KBD_BUFFER_SIZE)
3319 ? kbd_fetch_ptr
3320 : kbd_buffer);
3321
3322 do
3323 {
3324 if (!(
3325 #ifdef USE_TOOLKIT_SCROLL_BARS
3326 (flags & READABLE_EVENTS_FILTER_EVENTS) &&
3327 #endif
3328 event->kind == FOCUS_IN_EVENT)
3329 #ifdef USE_TOOLKIT_SCROLL_BARS
3330 && !((flags & READABLE_EVENTS_IGNORE_SQUEEZABLES)
3331 && (event->kind == SCROLL_BAR_CLICK_EVENT
3332 || event->kind == HORIZONTAL_SCROLL_BAR_CLICK_EVENT)
3333 && event->ie.part == scroll_bar_handle
3334 && event->ie.modifiers == 0)
3335 #endif
3336 && !((flags & READABLE_EVENTS_FILTER_EVENTS)
3337 && event->kind == BUFFER_SWITCH_EVENT))
3338 return 1;
3339 event++;
3340 if (event == kbd_buffer + KBD_BUFFER_SIZE)
3341 event = kbd_buffer;
3342 }
3343 while (event != kbd_store_ptr);
3344 }
3345 else
3346 return 1;
3347 }
3348
3349 if (!(flags & READABLE_EVENTS_IGNORE_SQUEEZABLES)
3350 && !NILP (do_mouse_tracking) && some_mouse_moved ())
3351 return 1;
3352 if (single_kboard)
3353 {
3354 if (current_kboard->kbd_queue_has_data)
3355 return 1;
3356 }
3357 else
3358 {
3359 KBOARD *kb;
3360 for (kb = all_kboards; kb; kb = kb->next_kboard)
3361 if (kb->kbd_queue_has_data)
3362 return 1;
3363 }
3364 return 0;
3365 }
3366
3367 /* Set this for debugging, to have a way to get out */
3368 int stop_character EXTERNALLY_VISIBLE;
3369
3370 static KBOARD *
3371 event_to_kboard (struct input_event *event)
3372 {
3373 /* Not applicable for these special events. */
3374 if (event->kind == SELECTION_REQUEST_EVENT
3375 || event->kind == SELECTION_CLEAR_EVENT)
3376 return NULL;
3377 else
3378 {
3379 Lisp_Object obj = event->frame_or_window;
3380 /* There are some events that set this field to nil or string. */
3381 if (WINDOWP (obj))
3382 obj = WINDOW_FRAME (XWINDOW (obj));
3383 /* Also ignore dead frames here. */
3384 return ((FRAMEP (obj) && FRAME_LIVE_P (XFRAME (obj)))
3385 ? FRAME_KBOARD (XFRAME (obj)) : NULL);
3386 }
3387 }
3388
3389 #ifdef subprocesses
3390 /* Return the number of slots occupied in kbd_buffer. */
3391
3392 static int
3393 kbd_buffer_nr_stored (void)
3394 {
3395 return kbd_fetch_ptr == kbd_store_ptr
3396 ? 0
3397 : (kbd_fetch_ptr < kbd_store_ptr
3398 ? kbd_store_ptr - kbd_fetch_ptr
3399 : ((kbd_buffer + KBD_BUFFER_SIZE) - kbd_fetch_ptr
3400 + (kbd_store_ptr - kbd_buffer)));
3401 }
3402 #endif /* Store an event obtained at interrupt level into kbd_buffer, fifo */
3403
3404 void
3405 kbd_buffer_store_event (register struct input_event *event)
3406 {
3407 kbd_buffer_store_event_hold (event, 0);
3408 }
3409
3410 /* Store EVENT obtained at interrupt level into kbd_buffer, fifo.
3411
3412 If HOLD_QUIT is 0, just stuff EVENT into the fifo.
3413 Else, if HOLD_QUIT.kind != NO_EVENT, discard EVENT.
3414 Else, if EVENT is a quit event, store the quit event
3415 in HOLD_QUIT, and return (thus ignoring further events).
3416
3417 This is used to postpone the processing of the quit event until all
3418 subsequent input events have been parsed (and discarded). */
3419
3420 void
3421 kbd_buffer_store_buffered_event (union buffered_input_event *event,
3422 struct input_event *hold_quit)
3423 {
3424 if (event->kind == NO_EVENT)
3425 emacs_abort ();
3426
3427 if (hold_quit && hold_quit->kind != NO_EVENT)
3428 return;
3429
3430 if (event->kind == ASCII_KEYSTROKE_EVENT)
3431 {
3432 int c = event->ie.code & 0377;
3433
3434 if (event->ie.modifiers & ctrl_modifier)
3435 c = make_ctrl_char (c);
3436
3437 c |= (event->ie.modifiers
3438 & (meta_modifier | alt_modifier
3439 | hyper_modifier | super_modifier));
3440
3441 if (c == quit_char)
3442 {
3443 KBOARD *kb = FRAME_KBOARD (XFRAME (event->ie.frame_or_window));
3444
3445 if (single_kboard && kb != current_kboard)
3446 {
3447 kset_kbd_queue
3448 (kb, list2 (make_lispy_switch_frame (event->ie.frame_or_window),
3449 make_number (c)));
3450 kb->kbd_queue_has_data = true;
3451 union buffered_input_event *sp;
3452 for (sp = kbd_fetch_ptr; sp != kbd_store_ptr; sp++)
3453 {
3454 if (sp == kbd_buffer + KBD_BUFFER_SIZE)
3455 sp = kbd_buffer;
3456
3457 if (event_to_kboard (&sp->ie) == kb)
3458 {
3459 sp->ie.kind = NO_EVENT;
3460 sp->ie.frame_or_window = Qnil;
3461 sp->ie.arg = Qnil;
3462 }
3463 }
3464 return;
3465 }
3466
3467 if (hold_quit)
3468 {
3469 *hold_quit = event->ie;
3470 return;
3471 }
3472
3473 /* If this results in a quit_char being returned to Emacs as
3474 input, set Vlast_event_frame properly. If this doesn't
3475 get returned to Emacs as an event, the next event read
3476 will set Vlast_event_frame again, so this is safe to do. */
3477 {
3478 Lisp_Object focus;
3479
3480 focus = FRAME_FOCUS_FRAME (XFRAME (event->ie.frame_or_window));
3481 if (NILP (focus))
3482 focus = event->ie.frame_or_window;
3483 internal_last_event_frame = focus;
3484 Vlast_event_frame = focus;
3485 }
3486
3487 handle_interrupt (0);
3488 return;
3489 }
3490
3491 if (c && c == stop_character)
3492 {
3493 sys_suspend ();
3494 return;
3495 }
3496 }
3497 /* Don't insert two BUFFER_SWITCH_EVENT's in a row.
3498 Just ignore the second one. */
3499 else if (event->kind == BUFFER_SWITCH_EVENT
3500 && kbd_fetch_ptr != kbd_store_ptr
3501 && ((kbd_store_ptr == kbd_buffer
3502 ? kbd_buffer + KBD_BUFFER_SIZE - 1
3503 : kbd_store_ptr - 1)->kind) == BUFFER_SWITCH_EVENT)
3504 return;
3505
3506 if (kbd_store_ptr - kbd_buffer == KBD_BUFFER_SIZE)
3507 kbd_store_ptr = kbd_buffer;
3508
3509 /* Don't let the very last slot in the buffer become full,
3510 since that would make the two pointers equal,
3511 and that is indistinguishable from an empty buffer.
3512 Discard the event if it would fill the last slot. */
3513 if (kbd_fetch_ptr - 1 != kbd_store_ptr)
3514 {
3515 *kbd_store_ptr = *event;
3516 ++kbd_store_ptr;
3517 #ifdef subprocesses
3518 if (kbd_buffer_nr_stored () > KBD_BUFFER_SIZE / 2
3519 && ! kbd_on_hold_p ())
3520 {
3521 /* Don't read keyboard input until we have processed kbd_buffer.
3522 This happens when pasting text longer than KBD_BUFFER_SIZE/2. */
3523 hold_keyboard_input ();
3524 unrequest_sigio ();
3525 stop_polling ();
3526 }
3527 #endif /* subprocesses */
3528 }
3529
3530 /* If we're inside while-no-input, and this event qualifies
3531 as input, set quit-flag to cause an interrupt. */
3532 if (!NILP (Vthrow_on_input)
3533 && event->kind != FOCUS_IN_EVENT
3534 && event->kind != FOCUS_OUT_EVENT
3535 && event->kind != HELP_EVENT
3536 && event->kind != ICONIFY_EVENT
3537 && event->kind != DEICONIFY_EVENT)
3538 {
3539 Vquit_flag = Vthrow_on_input;
3540 /* If we're inside a function that wants immediate quits,
3541 do it now. */
3542 if (immediate_quit && NILP (Vinhibit_quit))
3543 {
3544 immediate_quit = false;
3545 QUIT;
3546 }
3547 }
3548 }
3549
3550
3551 #ifdef HAVE_X11
3552
3553 /* Put a selection input event back in the head of the event queue. */
3554
3555 void
3556 kbd_buffer_unget_event (struct selection_input_event *event)
3557 {
3558 if (kbd_fetch_ptr == kbd_buffer)
3559 kbd_fetch_ptr = kbd_buffer + KBD_BUFFER_SIZE;
3560
3561 /* Don't let the very last slot in the buffer become full, */
3562 union buffered_input_event *kp = kbd_fetch_ptr - 1;
3563 if (kp != kbd_store_ptr)
3564 {
3565 kp->sie = *event;
3566 kbd_fetch_ptr = kp;
3567 }
3568 }
3569
3570 #endif
3571
3572 /* Limit help event positions to this range, to avoid overflow problems. */
3573 #define INPUT_EVENT_POS_MAX \
3574 ((ptrdiff_t) min (PTRDIFF_MAX, min (TYPE_MAXIMUM (Time) / 2, \
3575 MOST_POSITIVE_FIXNUM)))
3576 #define INPUT_EVENT_POS_MIN (-1 - INPUT_EVENT_POS_MAX)
3577
3578 /* Return a Time that encodes position POS. POS must be in range. */
3579
3580 static Time
3581 position_to_Time (ptrdiff_t pos)
3582 {
3583 eassert (INPUT_EVENT_POS_MIN <= pos && pos <= INPUT_EVENT_POS_MAX);
3584 return pos;
3585 }
3586
3587 /* Return the position that ENCODED_POS encodes.
3588 Avoid signed integer overflow. */
3589
3590 static ptrdiff_t
3591 Time_to_position (Time encoded_pos)
3592 {
3593 if (encoded_pos <= INPUT_EVENT_POS_MAX)
3594 return encoded_pos;
3595 Time encoded_pos_min = INPUT_EVENT_POS_MIN;
3596 eassert (encoded_pos_min <= encoded_pos);
3597 ptrdiff_t notpos = -1 - encoded_pos;
3598 return -1 - notpos;
3599 }
3600
3601 /* Generate a HELP_EVENT input_event and store it in the keyboard
3602 buffer.
3603
3604 HELP is the help form.
3605
3606 FRAME and WINDOW are the frame and window where the help is
3607 generated. OBJECT is the Lisp object where the help was found (a
3608 buffer, a string, an overlay, or nil if neither from a string nor
3609 from a buffer). POS is the position within OBJECT where the help
3610 was found. */
3611
3612 void
3613 gen_help_event (Lisp_Object help, Lisp_Object frame, Lisp_Object window,
3614 Lisp_Object object, ptrdiff_t pos)
3615 {
3616 struct input_event event;
3617
3618 event.kind = HELP_EVENT;
3619 event.frame_or_window = frame;
3620 event.arg = object;
3621 event.x = WINDOWP (window) ? window : frame;
3622 event.y = help;
3623 event.timestamp = position_to_Time (pos);
3624 kbd_buffer_store_event (&event);
3625 }
3626
3627
3628 /* Store HELP_EVENTs for HELP on FRAME in the input queue. */
3629
3630 void
3631 kbd_buffer_store_help_event (Lisp_Object frame, Lisp_Object help)
3632 {
3633 struct input_event event;
3634
3635 event.kind = HELP_EVENT;
3636 event.frame_or_window = frame;
3637 event.arg = Qnil;
3638 event.x = Qnil;
3639 event.y = help;
3640 event.timestamp = 0;
3641 kbd_buffer_store_event (&event);
3642 }
3643
3644 \f
3645 /* Discard any mouse events in the event buffer by setting them to
3646 NO_EVENT. */
3647 void
3648 discard_mouse_events (void)
3649 {
3650 union buffered_input_event *sp;
3651 for (sp = kbd_fetch_ptr; sp != kbd_store_ptr; sp++)
3652 {
3653 if (sp == kbd_buffer + KBD_BUFFER_SIZE)
3654 sp = kbd_buffer;
3655
3656 if (sp->kind == MOUSE_CLICK_EVENT
3657 || sp->kind == WHEEL_EVENT
3658 || sp->kind == HORIZ_WHEEL_EVENT
3659 #ifdef HAVE_GPM
3660 || sp->kind == GPM_CLICK_EVENT
3661 #endif
3662 || sp->kind == SCROLL_BAR_CLICK_EVENT
3663 || sp->kind == HORIZONTAL_SCROLL_BAR_CLICK_EVENT)
3664 {
3665 sp->kind = NO_EVENT;
3666 }
3667 }
3668 }
3669
3670
3671 /* Return true if there are any real events waiting in the event
3672 buffer, not counting `NO_EVENT's.
3673
3674 Discard NO_EVENT events at the front of the input queue, possibly
3675 leaving the input queue empty if there are no real input events. */
3676
3677 bool
3678 kbd_buffer_events_waiting (void)
3679 {
3680 union buffered_input_event *sp;
3681
3682 for (sp = kbd_fetch_ptr;
3683 sp != kbd_store_ptr && sp->kind == NO_EVENT;
3684 ++sp)
3685 {
3686 if (sp == kbd_buffer + KBD_BUFFER_SIZE)
3687 sp = kbd_buffer;
3688 }
3689
3690 kbd_fetch_ptr = sp;
3691 return sp != kbd_store_ptr && sp->kind != NO_EVENT;
3692 }
3693
3694 \f
3695 /* Clear input event EVENT. */
3696
3697 static void
3698 clear_event (union buffered_input_event *event)
3699 {
3700 event->kind = NO_EVENT;
3701 }
3702
3703
3704 /* Read one event from the event buffer, waiting if necessary.
3705 The value is a Lisp object representing the event.
3706 The value is nil for an event that should be ignored,
3707 or that was handled here.
3708 We always read and discard one event. */
3709
3710 static Lisp_Object
3711 kbd_buffer_get_event (KBOARD **kbp,
3712 bool *used_mouse_menu,
3713 struct timespec *end_time)
3714 {
3715 Lisp_Object obj;
3716
3717 #ifdef subprocesses
3718 if (kbd_on_hold_p () && kbd_buffer_nr_stored () < KBD_BUFFER_SIZE / 4)
3719 {
3720 /* Start reading input again because we have processed enough to
3721 be able to accept new events again. */
3722 unhold_keyboard_input ();
3723 request_sigio ();
3724 start_polling ();
3725 }
3726 #endif /* subprocesses */
3727
3728 #if !defined HAVE_DBUS && !defined USE_FILE_NOTIFY
3729 if (noninteractive
3730 /* In case we are running as a daemon, only do this before
3731 detaching from the terminal. */
3732 || (IS_DAEMON && DAEMON_RUNNING))
3733 {
3734 int c = getchar ();
3735 XSETINT (obj, c);
3736 *kbp = current_kboard;
3737 return obj;
3738 }
3739 #endif /* !defined HAVE_DBUS && !defined USE_FILE_NOTIFY */
3740
3741 /* Wait until there is input available. */
3742 for (;;)
3743 {
3744 /* Break loop if there's an unread command event. Needed in
3745 moused window autoselection which uses a timer to insert such
3746 events. */
3747 if (CONSP (Vunread_command_events))
3748 break;
3749
3750 if (kbd_fetch_ptr != kbd_store_ptr)
3751 break;
3752 if (!NILP (do_mouse_tracking) && some_mouse_moved ())
3753 break;
3754
3755 /* If the quit flag is set, then read_char will return
3756 quit_char, so that counts as "available input." */
3757 if (!NILP (Vquit_flag))
3758 quit_throw_to_read_char (0);
3759
3760 /* One way or another, wait until input is available; then, if
3761 interrupt handlers have not read it, read it now. */
3762
3763 #ifdef USABLE_SIGIO
3764 gobble_input ();
3765 #endif
3766 if (kbd_fetch_ptr != kbd_store_ptr)
3767 break;
3768 if (!NILP (do_mouse_tracking) && some_mouse_moved ())
3769 break;
3770 if (end_time)
3771 {
3772 struct timespec now = current_timespec ();
3773 if (timespec_cmp (*end_time, now) <= 0)
3774 return Qnil; /* Finished waiting. */
3775 else
3776 {
3777 struct timespec duration = timespec_sub (*end_time, now);
3778 wait_reading_process_output (min (duration.tv_sec,
3779 WAIT_READING_MAX),
3780 duration.tv_nsec,
3781 -1, 1, Qnil, NULL, 0);
3782 }
3783 }
3784 else
3785 {
3786 bool do_display = true;
3787
3788 if (FRAME_TERMCAP_P (SELECTED_FRAME ()))
3789 {
3790 struct tty_display_info *tty = CURTTY ();
3791
3792 /* When this TTY is displaying a menu, we must prevent
3793 any redisplay, because we modify the frame's glyph
3794 matrix behind the back of the display engine. */
3795 if (tty->showing_menu)
3796 do_display = false;
3797 }
3798
3799 wait_reading_process_output (0, 0, -1, do_display, Qnil, NULL, 0);
3800 }
3801
3802 if (!interrupt_input && kbd_fetch_ptr == kbd_store_ptr)
3803 gobble_input ();
3804 }
3805
3806 if (CONSP (Vunread_command_events))
3807 {
3808 Lisp_Object first;
3809 first = XCAR (Vunread_command_events);
3810 Vunread_command_events = XCDR (Vunread_command_events);
3811 *kbp = current_kboard;
3812 return first;
3813 }
3814
3815 /* At this point, we know that there is a readable event available
3816 somewhere. If the event queue is empty, then there must be a
3817 mouse movement enabled and available. */
3818 if (kbd_fetch_ptr != kbd_store_ptr)
3819 {
3820 union buffered_input_event *event;
3821
3822 event = ((kbd_fetch_ptr < kbd_buffer + KBD_BUFFER_SIZE)
3823 ? kbd_fetch_ptr
3824 : kbd_buffer);
3825
3826 *kbp = event_to_kboard (&event->ie);
3827 if (*kbp == 0)
3828 *kbp = current_kboard; /* Better than returning null ptr? */
3829
3830 obj = Qnil;
3831
3832 /* These two kinds of events get special handling
3833 and don't actually appear to the command loop.
3834 We return nil for them. */
3835 if (event->kind == SELECTION_REQUEST_EVENT
3836 || event->kind == SELECTION_CLEAR_EVENT)
3837 {
3838 #ifdef HAVE_X11
3839 /* Remove it from the buffer before processing it,
3840 since otherwise swallow_events will see it
3841 and process it again. */
3842 struct selection_input_event copy = event->sie;
3843 kbd_fetch_ptr = event + 1;
3844 input_pending = readable_events (0);
3845 x_handle_selection_event (&copy);
3846 #else
3847 /* We're getting selection request events, but we don't have
3848 a window system. */
3849 emacs_abort ();
3850 #endif
3851 }
3852
3853 #if defined (HAVE_NS)
3854 else if (event->kind == NS_TEXT_EVENT)
3855 {
3856 if (event->ie.code == KEY_NS_PUT_WORKING_TEXT)
3857 obj = list1 (intern ("ns-put-working-text"));
3858 else
3859 obj = list1 (intern ("ns-unput-working-text"));
3860 kbd_fetch_ptr = event + 1;
3861 if (used_mouse_menu)
3862 *used_mouse_menu = true;
3863 }
3864 #endif
3865
3866 #if defined (HAVE_X11) || defined (HAVE_NTGUI) \
3867 || defined (HAVE_NS)
3868 else if (event->kind == DELETE_WINDOW_EVENT)
3869 {
3870 /* Make an event (delete-frame (FRAME)). */
3871 obj = list2 (Qdelete_frame, list1 (event->ie.frame_or_window));
3872 kbd_fetch_ptr = event + 1;
3873 }
3874 #endif
3875 #if defined (HAVE_X11) || defined (HAVE_NTGUI) \
3876 || defined (HAVE_NS)
3877 else if (event->kind == ICONIFY_EVENT)
3878 {
3879 /* Make an event (iconify-frame (FRAME)). */
3880 obj = list2 (Qiconify_frame, list1 (event->ie.frame_or_window));
3881 kbd_fetch_ptr = event + 1;
3882 }
3883 else if (event->kind == DEICONIFY_EVENT)
3884 {
3885 /* Make an event (make-frame-visible (FRAME)). */
3886 obj = list2 (Qmake_frame_visible, list1 (event->ie.frame_or_window));
3887 kbd_fetch_ptr = event + 1;
3888 }
3889 #endif
3890 else if (event->kind == BUFFER_SWITCH_EVENT)
3891 {
3892 /* The value doesn't matter here; only the type is tested. */
3893 XSETBUFFER (obj, current_buffer);
3894 kbd_fetch_ptr = event + 1;
3895 }
3896 #if defined (USE_X_TOOLKIT) || defined (HAVE_NTGUI) \
3897 || defined (HAVE_NS) || defined (USE_GTK)
3898 else if (event->kind == MENU_BAR_ACTIVATE_EVENT)
3899 {
3900 kbd_fetch_ptr = event + 1;
3901 input_pending = readable_events (0);
3902 if (FRAME_LIVE_P (XFRAME (event->ie.frame_or_window)))
3903 x_activate_menubar (XFRAME (event->ie.frame_or_window));
3904 }
3905 #endif
3906 #ifdef HAVE_NTGUI
3907 else if (event->kind == LANGUAGE_CHANGE_EVENT)
3908 {
3909 /* Make an event (language-change FRAME CODEPAGE LANGUAGE-ID). */
3910 obj = list4 (Qlanguage_change,
3911 event->ie.frame_or_window,
3912 make_number (event->ie.code),
3913 make_number (event->ie.modifiers));
3914 kbd_fetch_ptr = event + 1;
3915 }
3916 #endif
3917 #ifdef USE_FILE_NOTIFY
3918 else if (event->kind == FILE_NOTIFY_EVENT)
3919 {
3920 #ifdef HAVE_W32NOTIFY
3921 /* Make an event (file-notify (DESCRIPTOR ACTION FILE) CALLBACK). */
3922 obj = list3 (Qfile_notify, event->ie.arg, event->ie.frame_or_window);
3923 #else
3924 obj = make_lispy_event (&event->ie);
3925 #endif
3926 kbd_fetch_ptr = event + 1;
3927 }
3928 #endif /* USE_FILE_NOTIFY */
3929 else if (event->kind == SAVE_SESSION_EVENT)
3930 {
3931 obj = list2 (Qsave_session, event->ie.arg);
3932 kbd_fetch_ptr = event + 1;
3933 }
3934 /* Just discard these, by returning nil.
3935 With MULTI_KBOARD, these events are used as placeholders
3936 when we need to randomly delete events from the queue.
3937 (They shouldn't otherwise be found in the buffer,
3938 but on some machines it appears they do show up
3939 even without MULTI_KBOARD.) */
3940 /* On Windows NT/9X, NO_EVENT is used to delete extraneous
3941 mouse events during a popup-menu call. */
3942 else if (event->kind == NO_EVENT)
3943 kbd_fetch_ptr = event + 1;
3944 else if (event->kind == HELP_EVENT)
3945 {
3946 Lisp_Object object, position, help, frame, window;
3947
3948 frame = event->ie.frame_or_window;
3949 object = event->ie.arg;
3950 position = make_number (Time_to_position (event->ie.timestamp));
3951 window = event->ie.x;
3952 help = event->ie.y;
3953 clear_event (event);
3954
3955 kbd_fetch_ptr = event + 1;
3956 if (!WINDOWP (window))
3957 window = Qnil;
3958 obj = Fcons (Qhelp_echo,
3959 list5 (frame, help, window, object, position));
3960 }
3961 else if (event->kind == FOCUS_IN_EVENT)
3962 {
3963 /* Notification of a FocusIn event. The frame receiving the
3964 focus is in event->frame_or_window. Generate a
3965 switch-frame event if necessary. */
3966 Lisp_Object frame, focus;
3967
3968 frame = event->ie.frame_or_window;
3969 focus = FRAME_FOCUS_FRAME (XFRAME (frame));
3970 if (FRAMEP (focus))
3971 frame = focus;
3972
3973 if (
3974 #ifdef HAVE_X11
3975 ! NILP (event->ie.arg)
3976 &&
3977 #endif
3978 !EQ (frame, internal_last_event_frame)
3979 && !EQ (frame, selected_frame))
3980 obj = make_lispy_switch_frame (frame);
3981 else
3982 obj = make_lispy_focus_in (frame);
3983
3984 internal_last_event_frame = frame;
3985 kbd_fetch_ptr = event + 1;
3986 }
3987 else if (event->kind == FOCUS_OUT_EVENT)
3988 {
3989 #ifdef HAVE_WINDOW_SYSTEM
3990
3991 Display_Info *di;
3992 Lisp_Object frame = event->ie.frame_or_window;
3993 bool focused = false;
3994
3995 for (di = x_display_list; di && ! focused; di = di->next)
3996 focused = di->x_highlight_frame != 0;
3997
3998 if (!focused)
3999 obj = make_lispy_focus_out (frame);
4000
4001 #endif /* HAVE_WINDOW_SYSTEM */
4002
4003 kbd_fetch_ptr = event + 1;
4004 }
4005 #ifdef HAVE_DBUS
4006 else if (event->kind == DBUS_EVENT)
4007 {
4008 obj = make_lispy_event (&event->ie);
4009 kbd_fetch_ptr = event + 1;
4010 }
4011 #endif
4012 else if (event->kind == CONFIG_CHANGED_EVENT)
4013 {
4014 obj = make_lispy_event (&event->ie);
4015 kbd_fetch_ptr = event + 1;
4016 }
4017 else
4018 {
4019 /* If this event is on a different frame, return a switch-frame this
4020 time, and leave the event in the queue for next time. */
4021 Lisp_Object frame;
4022 Lisp_Object focus;
4023
4024 frame = event->ie.frame_or_window;
4025 if (CONSP (frame))
4026 frame = XCAR (frame);
4027 else if (WINDOWP (frame))
4028 frame = WINDOW_FRAME (XWINDOW (frame));
4029
4030 focus = FRAME_FOCUS_FRAME (XFRAME (frame));
4031 if (! NILP (focus))
4032 frame = focus;
4033
4034 if (! EQ (frame, internal_last_event_frame)
4035 && !EQ (frame, selected_frame))
4036 obj = make_lispy_switch_frame (frame);
4037 internal_last_event_frame = frame;
4038
4039 /* If we didn't decide to make a switch-frame event, go ahead
4040 and build a real event from the queue entry. */
4041
4042 if (NILP (obj))
4043 {
4044 obj = make_lispy_event (&event->ie);
4045
4046 #if defined (USE_X_TOOLKIT) || defined (HAVE_NTGUI) \
4047 || defined (HAVE_NS) || defined (USE_GTK)
4048 /* If this was a menu selection, then set the flag to inhibit
4049 writing to last_nonmenu_event. Don't do this if the event
4050 we're returning is (menu-bar), though; that indicates the
4051 beginning of the menu sequence, and we might as well leave
4052 that as the `event with parameters' for this selection. */
4053 if (used_mouse_menu
4054 && !EQ (event->ie.frame_or_window, event->ie.arg)
4055 && (event->kind == MENU_BAR_EVENT
4056 || event->kind == TOOL_BAR_EVENT))
4057 *used_mouse_menu = true;
4058 #endif
4059 #ifdef HAVE_NS
4060 /* Certain system events are non-key events. */
4061 if (used_mouse_menu
4062 && event->kind == NS_NONKEY_EVENT)
4063 *used_mouse_menu = true;
4064 #endif
4065
4066 /* Wipe out this event, to catch bugs. */
4067 clear_event (event);
4068 kbd_fetch_ptr = event + 1;
4069 }
4070 }
4071 }
4072 /* Try generating a mouse motion event. */
4073 else if (!NILP (do_mouse_tracking) && some_mouse_moved ())
4074 {
4075 struct frame *f = some_mouse_moved ();
4076 Lisp_Object bar_window;
4077 enum scroll_bar_part part;
4078 Lisp_Object x, y;
4079 Time t;
4080
4081 *kbp = current_kboard;
4082 /* Note that this uses F to determine which terminal to look at.
4083 If there is no valid info, it does not store anything
4084 so x remains nil. */
4085 x = Qnil;
4086
4087 /* XXX Can f or mouse_position_hook be NULL here? */
4088 if (f && FRAME_TERMINAL (f)->mouse_position_hook)
4089 (*FRAME_TERMINAL (f)->mouse_position_hook) (&f, 0, &bar_window,
4090 &part, &x, &y, &t);
4091
4092 obj = Qnil;
4093
4094 /* Decide if we should generate a switch-frame event. Don't
4095 generate switch-frame events for motion outside of all Emacs
4096 frames. */
4097 if (!NILP (x) && f)
4098 {
4099 Lisp_Object frame;
4100
4101 frame = FRAME_FOCUS_FRAME (f);
4102 if (NILP (frame))
4103 XSETFRAME (frame, f);
4104
4105 if (! EQ (frame, internal_last_event_frame)
4106 && !EQ (frame, selected_frame))
4107 obj = make_lispy_switch_frame (frame);
4108 internal_last_event_frame = frame;
4109 }
4110
4111 /* If we didn't decide to make a switch-frame event, go ahead and
4112 return a mouse-motion event. */
4113 if (!NILP (x) && NILP (obj))
4114 obj = make_lispy_movement (f, bar_window, part, x, y, t);
4115 }
4116 else
4117 /* We were promised by the above while loop that there was
4118 something for us to read! */
4119 emacs_abort ();
4120
4121 input_pending = readable_events (0);
4122
4123 Vlast_event_frame = internal_last_event_frame;
4124
4125 return (obj);
4126 }
4127 \f
4128 /* Process any non-user-visible events (currently X selection events),
4129 without reading any user-visible events. */
4130
4131 static void
4132 process_special_events (void)
4133 {
4134 union buffered_input_event *event;
4135
4136 for (event = kbd_fetch_ptr; event != kbd_store_ptr; ++event)
4137 {
4138 if (event == kbd_buffer + KBD_BUFFER_SIZE)
4139 {
4140 event = kbd_buffer;
4141 if (event == kbd_store_ptr)
4142 break;
4143 }
4144
4145 /* If we find a stored X selection request, handle it now. */
4146 if (event->kind == SELECTION_REQUEST_EVENT
4147 || event->kind == SELECTION_CLEAR_EVENT)
4148 {
4149 #ifdef HAVE_X11
4150
4151 /* Remove the event from the fifo buffer before processing;
4152 otherwise swallow_events called recursively could see it
4153 and process it again. To do this, we move the events
4154 between kbd_fetch_ptr and EVENT one slot to the right,
4155 cyclically. */
4156
4157 struct selection_input_event copy = event->sie;
4158 union buffered_input_event *beg
4159 = (kbd_fetch_ptr == kbd_buffer + KBD_BUFFER_SIZE)
4160 ? kbd_buffer : kbd_fetch_ptr;
4161
4162 if (event > beg)
4163 memmove (beg + 1, beg, (event - beg) * sizeof *beg);
4164 else if (event < beg)
4165 {
4166 if (event > kbd_buffer)
4167 memmove (kbd_buffer + 1, kbd_buffer,
4168 (event - kbd_buffer) * sizeof *kbd_buffer);
4169 *kbd_buffer = *(kbd_buffer + KBD_BUFFER_SIZE - 1);
4170 if (beg < kbd_buffer + KBD_BUFFER_SIZE - 1)
4171 memmove (beg + 1, beg,
4172 (kbd_buffer + KBD_BUFFER_SIZE - 1 - beg) * sizeof *beg);
4173 }
4174
4175 if (kbd_fetch_ptr == kbd_buffer + KBD_BUFFER_SIZE)
4176 kbd_fetch_ptr = kbd_buffer + 1;
4177 else
4178 kbd_fetch_ptr++;
4179
4180 input_pending = readable_events (0);
4181 x_handle_selection_event (&copy);
4182 #else
4183 /* We're getting selection request events, but we don't have
4184 a window system. */
4185 emacs_abort ();
4186 #endif
4187 }
4188 }
4189 }
4190
4191 /* Process any events that are not user-visible, run timer events that
4192 are ripe, and return, without reading any user-visible events. */
4193
4194 void
4195 swallow_events (bool do_display)
4196 {
4197 unsigned old_timers_run;
4198
4199 process_special_events ();
4200
4201 old_timers_run = timers_run;
4202 get_input_pending (READABLE_EVENTS_DO_TIMERS_NOW);
4203
4204 if (!input_pending && timers_run != old_timers_run && do_display)
4205 redisplay_preserve_echo_area (7);
4206 }
4207 \f
4208 /* Record the start of when Emacs is idle,
4209 for the sake of running idle-time timers. */
4210
4211 static void
4212 timer_start_idle (void)
4213 {
4214 /* If we are already in the idle state, do nothing. */
4215 if (timespec_valid_p (timer_idleness_start_time))
4216 return;
4217
4218 timer_idleness_start_time = current_timespec ();
4219 timer_last_idleness_start_time = timer_idleness_start_time;
4220
4221 /* Mark all idle-time timers as once again candidates for running. */
4222 call0 (intern ("internal-timer-start-idle"));
4223 }
4224
4225 /* Record that Emacs is no longer idle, so stop running idle-time timers. */
4226
4227 static void
4228 timer_stop_idle (void)
4229 {
4230 timer_idleness_start_time = invalid_timespec ();
4231 }
4232
4233 /* Resume idle timer from last idle start time. */
4234
4235 static void
4236 timer_resume_idle (void)
4237 {
4238 if (timespec_valid_p (timer_idleness_start_time))
4239 return;
4240
4241 timer_idleness_start_time = timer_last_idleness_start_time;
4242 }
4243
4244 /* List of elisp functions to call, delayed because they were generated in
4245 a context where Elisp could not be safely run (e.g. redisplay, signal,
4246 ...). Each element has the form (FUN . ARGS). */
4247 Lisp_Object pending_funcalls;
4248
4249 /* Return true if TIMER is a valid timer, placing its value into *RESULT. */
4250 static bool
4251 decode_timer (Lisp_Object timer, struct timespec *result)
4252 {
4253 Lisp_Object *vec;
4254
4255 if (! (VECTORP (timer) && ASIZE (timer) == 9))
4256 return 0;
4257 vec = XVECTOR (timer)->contents;
4258 if (! NILP (vec[0]))
4259 return 0;
4260 if (! INTEGERP (vec[2]))
4261 return false;
4262
4263 struct lisp_time t;
4264 if (decode_time_components (vec[1], vec[2], vec[3], vec[8], &t, 0) <= 0)
4265 return false;
4266 *result = lisp_to_timespec (t);
4267 return timespec_valid_p (*result);
4268 }
4269
4270
4271 /* Check whether a timer has fired. To prevent larger problems we simply
4272 disregard elements that are not proper timers. Do not make a circular
4273 timer list for the time being.
4274
4275 Returns the time to wait until the next timer fires. If a
4276 timer is triggering now, return zero.
4277 If no timer is active, return -1.
4278
4279 If a timer is ripe, we run it, with quitting turned off.
4280 In that case we return 0 to indicate that a new timer_check_2 call
4281 should be done. */
4282
4283 static struct timespec
4284 timer_check_2 (Lisp_Object timers, Lisp_Object idle_timers)
4285 {
4286 struct timespec nexttime;
4287 struct timespec now;
4288 struct timespec idleness_now;
4289 Lisp_Object chosen_timer;
4290
4291 nexttime = invalid_timespec ();
4292
4293 chosen_timer = Qnil;
4294
4295 /* First run the code that was delayed. */
4296 while (CONSP (pending_funcalls))
4297 {
4298 Lisp_Object funcall = XCAR (pending_funcalls);
4299 pending_funcalls = XCDR (pending_funcalls);
4300 safe_call2 (Qapply, XCAR (funcall), XCDR (funcall));
4301 }
4302
4303 if (CONSP (timers) || CONSP (idle_timers))
4304 {
4305 now = current_timespec ();
4306 idleness_now = (timespec_valid_p (timer_idleness_start_time)
4307 ? timespec_sub (now, timer_idleness_start_time)
4308 : make_timespec (0, 0));
4309 }
4310
4311 while (CONSP (timers) || CONSP (idle_timers))
4312 {
4313 Lisp_Object timer = Qnil, idle_timer = Qnil;
4314 struct timespec timer_time, idle_timer_time;
4315 struct timespec difference;
4316 struct timespec timer_difference = invalid_timespec ();
4317 struct timespec idle_timer_difference = invalid_timespec ();
4318 bool ripe, timer_ripe = 0, idle_timer_ripe = 0;
4319
4320 /* Set TIMER and TIMER_DIFFERENCE
4321 based on the next ordinary timer.
4322 TIMER_DIFFERENCE is the distance in time from NOW to when
4323 this timer becomes ripe.
4324 Skip past invalid timers and timers already handled. */
4325 if (CONSP (timers))
4326 {
4327 timer = XCAR (timers);
4328 if (! decode_timer (timer, &timer_time))
4329 {
4330 timers = XCDR (timers);
4331 continue;
4332 }
4333
4334 timer_ripe = timespec_cmp (timer_time, now) <= 0;
4335 timer_difference = (timer_ripe
4336 ? timespec_sub (now, timer_time)
4337 : timespec_sub (timer_time, now));
4338 }
4339
4340 /* Likewise for IDLE_TIMER and IDLE_TIMER_DIFFERENCE
4341 based on the next idle timer. */
4342 if (CONSP (idle_timers))
4343 {
4344 idle_timer = XCAR (idle_timers);
4345 if (! decode_timer (idle_timer, &idle_timer_time))
4346 {
4347 idle_timers = XCDR (idle_timers);
4348 continue;
4349 }
4350
4351 idle_timer_ripe = timespec_cmp (idle_timer_time, idleness_now) <= 0;
4352 idle_timer_difference
4353 = (idle_timer_ripe
4354 ? timespec_sub (idleness_now, idle_timer_time)
4355 : timespec_sub (idle_timer_time, idleness_now));
4356 }
4357
4358 /* Decide which timer is the next timer,
4359 and set CHOSEN_TIMER, DIFFERENCE, and RIPE accordingly.
4360 Also step down the list where we found that timer. */
4361
4362 if (timespec_valid_p (timer_difference)
4363 && (! timespec_valid_p (idle_timer_difference)
4364 || idle_timer_ripe < timer_ripe
4365 || (idle_timer_ripe == timer_ripe
4366 && ((timer_ripe
4367 ? timespec_cmp (idle_timer_difference,
4368 timer_difference)
4369 : timespec_cmp (timer_difference,
4370 idle_timer_difference))
4371 < 0))))
4372 {
4373 chosen_timer = timer;
4374 timers = XCDR (timers);
4375 difference = timer_difference;
4376 ripe = timer_ripe;
4377 }
4378 else
4379 {
4380 chosen_timer = idle_timer;
4381 idle_timers = XCDR (idle_timers);
4382 difference = idle_timer_difference;
4383 ripe = idle_timer_ripe;
4384 }
4385
4386 /* If timer is ripe, run it if it hasn't been run. */
4387 if (ripe)
4388 {
4389 if (NILP (AREF (chosen_timer, 0)))
4390 {
4391 ptrdiff_t count = SPECPDL_INDEX ();
4392 Lisp_Object old_deactivate_mark = Vdeactivate_mark;
4393
4394 /* Mark the timer as triggered to prevent problems if the lisp
4395 code fails to reschedule it right. */
4396 ASET (chosen_timer, 0, Qt);
4397
4398 specbind (Qinhibit_quit, Qt);
4399
4400 call1 (Qtimer_event_handler, chosen_timer);
4401 Vdeactivate_mark = old_deactivate_mark;
4402 timers_run++;
4403 unbind_to (count, Qnil);
4404
4405 /* Since we have handled the event,
4406 we don't need to tell the caller to wake up and do it. */
4407 /* But the caller must still wait for the next timer, so
4408 return 0 to indicate that. */
4409 }
4410
4411 nexttime = make_timespec (0, 0);
4412 break;
4413 }
4414 else
4415 /* When we encounter a timer that is still waiting,
4416 return the amount of time to wait before it is ripe. */
4417 {
4418 return difference;
4419 }
4420 }
4421
4422 /* No timers are pending in the future. */
4423 /* Return 0 if we generated an event, and -1 if not. */
4424 return nexttime;
4425 }
4426
4427
4428 /* Check whether a timer has fired. To prevent larger problems we simply
4429 disregard elements that are not proper timers. Do not make a circular
4430 timer list for the time being.
4431
4432 Returns the time to wait until the next timer fires.
4433 If no timer is active, return an invalid value.
4434
4435 As long as any timer is ripe, we run it. */
4436
4437 struct timespec
4438 timer_check (void)
4439 {
4440 struct timespec nexttime;
4441 Lisp_Object timers, idle_timers;
4442
4443 Lisp_Object tem = Vinhibit_quit;
4444 Vinhibit_quit = Qt;
4445
4446 /* We use copies of the timers' lists to allow a timer to add itself
4447 again, without locking up Emacs if the newly added timer is
4448 already ripe when added. */
4449
4450 /* Always consider the ordinary timers. */
4451 timers = Fcopy_sequence (Vtimer_list);
4452 /* Consider the idle timers only if Emacs is idle. */
4453 if (timespec_valid_p (timer_idleness_start_time))
4454 idle_timers = Fcopy_sequence (Vtimer_idle_list);
4455 else
4456 idle_timers = Qnil;
4457
4458 Vinhibit_quit = tem;
4459
4460 do
4461 {
4462 nexttime = timer_check_2 (timers, idle_timers);
4463 }
4464 while (nexttime.tv_sec == 0 && nexttime.tv_nsec == 0);
4465
4466 return nexttime;
4467 }
4468
4469 DEFUN ("current-idle-time", Fcurrent_idle_time, Scurrent_idle_time, 0, 0, 0,
4470 doc: /* Return the current length of Emacs idleness, or nil.
4471 The value when Emacs is idle is a list of four integers (HIGH LOW USEC PSEC)
4472 in the same style as (current-time).
4473
4474 The value when Emacs is not idle is nil.
4475
4476 PSEC is a multiple of the system clock resolution. */)
4477 (void)
4478 {
4479 if (timespec_valid_p (timer_idleness_start_time))
4480 return make_lisp_time (timespec_sub (current_timespec (),
4481 timer_idleness_start_time));
4482
4483 return Qnil;
4484 }
4485 \f
4486 /* Caches for modify_event_symbol. */
4487 static Lisp_Object accent_key_syms;
4488 static Lisp_Object func_key_syms;
4489 static Lisp_Object mouse_syms;
4490 static Lisp_Object wheel_syms;
4491 static Lisp_Object drag_n_drop_syms;
4492
4493 /* This is a list of keysym codes for special "accent" characters.
4494 It parallels lispy_accent_keys. */
4495
4496 static const int lispy_accent_codes[] =
4497 {
4498 #ifdef XK_dead_circumflex
4499 XK_dead_circumflex,
4500 #else
4501 0,
4502 #endif
4503 #ifdef XK_dead_grave
4504 XK_dead_grave,
4505 #else
4506 0,
4507 #endif
4508 #ifdef XK_dead_tilde
4509 XK_dead_tilde,
4510 #else
4511 0,
4512 #endif
4513 #ifdef XK_dead_diaeresis
4514 XK_dead_diaeresis,
4515 #else
4516 0,
4517 #endif
4518 #ifdef XK_dead_macron
4519 XK_dead_macron,
4520 #else
4521 0,
4522 #endif
4523 #ifdef XK_dead_degree
4524 XK_dead_degree,
4525 #else
4526 0,
4527 #endif
4528 #ifdef XK_dead_acute
4529 XK_dead_acute,
4530 #else
4531 0,
4532 #endif
4533 #ifdef XK_dead_cedilla
4534 XK_dead_cedilla,
4535 #else
4536 0,
4537 #endif
4538 #ifdef XK_dead_breve
4539 XK_dead_breve,
4540 #else
4541 0,
4542 #endif
4543 #ifdef XK_dead_ogonek
4544 XK_dead_ogonek,
4545 #else
4546 0,
4547 #endif
4548 #ifdef XK_dead_caron
4549 XK_dead_caron,
4550 #else
4551 0,
4552 #endif
4553 #ifdef XK_dead_doubleacute
4554 XK_dead_doubleacute,
4555 #else
4556 0,
4557 #endif
4558 #ifdef XK_dead_abovedot
4559 XK_dead_abovedot,
4560 #else
4561 0,
4562 #endif
4563 #ifdef XK_dead_abovering
4564 XK_dead_abovering,
4565 #else
4566 0,
4567 #endif
4568 #ifdef XK_dead_iota
4569 XK_dead_iota,
4570 #else
4571 0,
4572 #endif
4573 #ifdef XK_dead_belowdot
4574 XK_dead_belowdot,
4575 #else
4576 0,
4577 #endif
4578 #ifdef XK_dead_voiced_sound
4579 XK_dead_voiced_sound,
4580 #else
4581 0,
4582 #endif
4583 #ifdef XK_dead_semivoiced_sound
4584 XK_dead_semivoiced_sound,
4585 #else
4586 0,
4587 #endif
4588 #ifdef XK_dead_hook
4589 XK_dead_hook,
4590 #else
4591 0,
4592 #endif
4593 #ifdef XK_dead_horn
4594 XK_dead_horn,
4595 #else
4596 0,
4597 #endif
4598 };
4599
4600 /* This is a list of Lisp names for special "accent" characters.
4601 It parallels lispy_accent_codes. */
4602
4603 static const char *const lispy_accent_keys[] =
4604 {
4605 "dead-circumflex",
4606 "dead-grave",
4607 "dead-tilde",
4608 "dead-diaeresis",
4609 "dead-macron",
4610 "dead-degree",
4611 "dead-acute",
4612 "dead-cedilla",
4613 "dead-breve",
4614 "dead-ogonek",
4615 "dead-caron",
4616 "dead-doubleacute",
4617 "dead-abovedot",
4618 "dead-abovering",
4619 "dead-iota",
4620 "dead-belowdot",
4621 "dead-voiced-sound",
4622 "dead-semivoiced-sound",
4623 "dead-hook",
4624 "dead-horn",
4625 };
4626
4627 #ifdef HAVE_NTGUI
4628 #define FUNCTION_KEY_OFFSET 0x0
4629
4630 const char *const lispy_function_keys[] =
4631 {
4632 0, /* 0 */
4633
4634 0, /* VK_LBUTTON 0x01 */
4635 0, /* VK_RBUTTON 0x02 */
4636 "cancel", /* VK_CANCEL 0x03 */
4637 0, /* VK_MBUTTON 0x04 */
4638
4639 0, 0, 0, /* 0x05 .. 0x07 */
4640
4641 "backspace", /* VK_BACK 0x08 */
4642 "tab", /* VK_TAB 0x09 */
4643
4644 0, 0, /* 0x0A .. 0x0B */
4645
4646 "clear", /* VK_CLEAR 0x0C */
4647 "return", /* VK_RETURN 0x0D */
4648
4649 0, 0, /* 0x0E .. 0x0F */
4650
4651 0, /* VK_SHIFT 0x10 */
4652 0, /* VK_CONTROL 0x11 */
4653 0, /* VK_MENU 0x12 */
4654 "pause", /* VK_PAUSE 0x13 */
4655 "capslock", /* VK_CAPITAL 0x14 */
4656 "kana", /* VK_KANA/VK_HANGUL 0x15 */
4657 0, /* 0x16 */
4658 "junja", /* VK_JUNJA 0x17 */
4659 "final", /* VK_FINAL 0x18 */
4660 "kanji", /* VK_KANJI/VK_HANJA 0x19 */
4661 0, /* 0x1A */
4662 "escape", /* VK_ESCAPE 0x1B */
4663 "convert", /* VK_CONVERT 0x1C */
4664 "non-convert", /* VK_NONCONVERT 0x1D */
4665 "accept", /* VK_ACCEPT 0x1E */
4666 "mode-change", /* VK_MODECHANGE 0x1F */
4667 0, /* VK_SPACE 0x20 */
4668 "prior", /* VK_PRIOR 0x21 */
4669 "next", /* VK_NEXT 0x22 */
4670 "end", /* VK_END 0x23 */
4671 "home", /* VK_HOME 0x24 */
4672 "left", /* VK_LEFT 0x25 */
4673 "up", /* VK_UP 0x26 */
4674 "right", /* VK_RIGHT 0x27 */
4675 "down", /* VK_DOWN 0x28 */
4676 "select", /* VK_SELECT 0x29 */
4677 "print", /* VK_PRINT 0x2A */
4678 "execute", /* VK_EXECUTE 0x2B */
4679 "snapshot", /* VK_SNAPSHOT 0x2C */
4680 "insert", /* VK_INSERT 0x2D */
4681 "delete", /* VK_DELETE 0x2E */
4682 "help", /* VK_HELP 0x2F */
4683
4684 /* VK_0 thru VK_9 are the same as ASCII '0' thru '9' (0x30 - 0x39) */
4685
4686 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
4687
4688 0, 0, 0, 0, 0, 0, 0, /* 0x3A .. 0x40 */
4689
4690 /* VK_A thru VK_Z are the same as ASCII 'A' thru 'Z' (0x41 - 0x5A) */
4691
4692 0, 0, 0, 0, 0, 0, 0, 0, 0,
4693 0, 0, 0, 0, 0, 0, 0, 0, 0,
4694 0, 0, 0, 0, 0, 0, 0, 0,
4695
4696 "lwindow", /* VK_LWIN 0x5B */
4697 "rwindow", /* VK_RWIN 0x5C */
4698 "apps", /* VK_APPS 0x5D */
4699 0, /* 0x5E */
4700 "sleep",
4701 "kp-0", /* VK_NUMPAD0 0x60 */
4702 "kp-1", /* VK_NUMPAD1 0x61 */
4703 "kp-2", /* VK_NUMPAD2 0x62 */
4704 "kp-3", /* VK_NUMPAD3 0x63 */
4705 "kp-4", /* VK_NUMPAD4 0x64 */
4706 "kp-5", /* VK_NUMPAD5 0x65 */
4707 "kp-6", /* VK_NUMPAD6 0x66 */
4708 "kp-7", /* VK_NUMPAD7 0x67 */
4709 "kp-8", /* VK_NUMPAD8 0x68 */
4710 "kp-9", /* VK_NUMPAD9 0x69 */
4711 "kp-multiply", /* VK_MULTIPLY 0x6A */
4712 "kp-add", /* VK_ADD 0x6B */
4713 "kp-separator", /* VK_SEPARATOR 0x6C */
4714 "kp-subtract", /* VK_SUBTRACT 0x6D */
4715 "kp-decimal", /* VK_DECIMAL 0x6E */
4716 "kp-divide", /* VK_DIVIDE 0x6F */
4717 "f1", /* VK_F1 0x70 */
4718 "f2", /* VK_F2 0x71 */
4719 "f3", /* VK_F3 0x72 */
4720 "f4", /* VK_F4 0x73 */
4721 "f5", /* VK_F5 0x74 */
4722 "f6", /* VK_F6 0x75 */
4723 "f7", /* VK_F7 0x76 */
4724 "f8", /* VK_F8 0x77 */
4725 "f9", /* VK_F9 0x78 */
4726 "f10", /* VK_F10 0x79 */
4727 "f11", /* VK_F11 0x7A */
4728 "f12", /* VK_F12 0x7B */
4729 "f13", /* VK_F13 0x7C */
4730 "f14", /* VK_F14 0x7D */
4731 "f15", /* VK_F15 0x7E */
4732 "f16", /* VK_F16 0x7F */
4733 "f17", /* VK_F17 0x80 */
4734 "f18", /* VK_F18 0x81 */
4735 "f19", /* VK_F19 0x82 */
4736 "f20", /* VK_F20 0x83 */
4737 "f21", /* VK_F21 0x84 */
4738 "f22", /* VK_F22 0x85 */
4739 "f23", /* VK_F23 0x86 */
4740 "f24", /* VK_F24 0x87 */
4741
4742 0, 0, 0, 0, /* 0x88 .. 0x8B */
4743 0, 0, 0, 0, /* 0x8C .. 0x8F */
4744
4745 "kp-numlock", /* VK_NUMLOCK 0x90 */
4746 "scroll", /* VK_SCROLL 0x91 */
4747 /* Not sure where the following block comes from.
4748 Windows headers have NEC and Fujitsu specific keys in
4749 this block, but nothing generic. */
4750 "kp-space", /* VK_NUMPAD_CLEAR 0x92 */
4751 "kp-enter", /* VK_NUMPAD_ENTER 0x93 */
4752 "kp-prior", /* VK_NUMPAD_PRIOR 0x94 */
4753 "kp-next", /* VK_NUMPAD_NEXT 0x95 */
4754 "kp-end", /* VK_NUMPAD_END 0x96 */
4755 "kp-home", /* VK_NUMPAD_HOME 0x97 */
4756 "kp-left", /* VK_NUMPAD_LEFT 0x98 */
4757 "kp-up", /* VK_NUMPAD_UP 0x99 */
4758 "kp-right", /* VK_NUMPAD_RIGHT 0x9A */
4759 "kp-down", /* VK_NUMPAD_DOWN 0x9B */
4760 "kp-insert", /* VK_NUMPAD_INSERT 0x9C */
4761 "kp-delete", /* VK_NUMPAD_DELETE 0x9D */
4762
4763 0, 0, /* 0x9E .. 0x9F */
4764
4765 /*
4766 * VK_L* & VK_R* - left and right Alt, Ctrl and Shift virtual keys.
4767 * Used only as parameters to GetAsyncKeyState and GetKeyState.
4768 * No other API or message will distinguish left and right keys this way.
4769 * 0xA0 .. 0xA5
4770 */
4771 0, 0, 0, 0, 0, 0,
4772
4773 /* Multimedia keys. These are handled as WM_APPCOMMAND, which allows us
4774 to enable them selectively, and gives access to a few more functions.
4775 See lispy_multimedia_keys below. */
4776 0, 0, 0, 0, 0, 0, 0, /* 0xA6 .. 0xAC Browser */
4777 0, 0, 0, /* 0xAD .. 0xAF Volume */
4778 0, 0, 0, 0, /* 0xB0 .. 0xB3 Media */
4779 0, 0, 0, 0, /* 0xB4 .. 0xB7 Apps */
4780
4781 /* 0xB8 .. 0xC0 "OEM" keys - all seem to be punctuation. */
4782 0, 0, 0, 0, 0, 0, 0, 0, 0,
4783
4784 /* 0xC1 - 0xDA unallocated, 0xDB-0xDF more OEM keys */
4785 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
4786 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
4787
4788 0, /* 0xE0 */
4789 "ax", /* VK_OEM_AX 0xE1 */
4790 0, /* VK_OEM_102 0xE2 */
4791 "ico-help", /* VK_ICO_HELP 0xE3 */
4792 "ico-00", /* VK_ICO_00 0xE4 */
4793 0, /* VK_PROCESSKEY 0xE5 - used by IME */
4794 "ico-clear", /* VK_ICO_CLEAR 0xE6 */
4795 0, /* VK_PACKET 0xE7 - used to pass Unicode chars */
4796 0, /* 0xE8 */
4797 "reset", /* VK_OEM_RESET 0xE9 */
4798 "jump", /* VK_OEM_JUMP 0xEA */
4799 "oem-pa1", /* VK_OEM_PA1 0xEB */
4800 "oem-pa2", /* VK_OEM_PA2 0xEC */
4801 "oem-pa3", /* VK_OEM_PA3 0xED */
4802 "wsctrl", /* VK_OEM_WSCTRL 0xEE */
4803 "cusel", /* VK_OEM_CUSEL 0xEF */
4804 "oem-attn", /* VK_OEM_ATTN 0xF0 */
4805 "finish", /* VK_OEM_FINISH 0xF1 */
4806 "copy", /* VK_OEM_COPY 0xF2 */
4807 "auto", /* VK_OEM_AUTO 0xF3 */
4808 "enlw", /* VK_OEM_ENLW 0xF4 */
4809 "backtab", /* VK_OEM_BACKTAB 0xF5 */
4810 "attn", /* VK_ATTN 0xF6 */
4811 "crsel", /* VK_CRSEL 0xF7 */
4812 "exsel", /* VK_EXSEL 0xF8 */
4813 "ereof", /* VK_EREOF 0xF9 */
4814 "play", /* VK_PLAY 0xFA */
4815 "zoom", /* VK_ZOOM 0xFB */
4816 "noname", /* VK_NONAME 0xFC */
4817 "pa1", /* VK_PA1 0xFD */
4818 "oem_clear", /* VK_OEM_CLEAR 0xFE */
4819 0 /* 0xFF */
4820 };
4821
4822 /* Some of these duplicate the "Media keys" on newer keyboards,
4823 but they are delivered to the application in a different way. */
4824 static const char *const lispy_multimedia_keys[] =
4825 {
4826 0,
4827 "browser-back",
4828 "browser-forward",
4829 "browser-refresh",
4830 "browser-stop",
4831 "browser-search",
4832 "browser-favorites",
4833 "browser-home",
4834 "volume-mute",
4835 "volume-down",
4836 "volume-up",
4837 "media-next",
4838 "media-previous",
4839 "media-stop",
4840 "media-play-pause",
4841 "mail",
4842 "media-select",
4843 "app-1",
4844 "app-2",
4845 "bass-down",
4846 "bass-boost",
4847 "bass-up",
4848 "treble-down",
4849 "treble-up",
4850 "mic-volume-mute",
4851 "mic-volume-down",
4852 "mic-volume-up",
4853 "help",
4854 "find",
4855 "new",
4856 "open",
4857 "close",
4858 "save",
4859 "print",
4860 "undo",
4861 "redo",
4862 "copy",
4863 "cut",
4864 "paste",
4865 "mail-reply",
4866 "mail-forward",
4867 "mail-send",
4868 "spell-check",
4869 "toggle-dictate-command",
4870 "mic-toggle",
4871 "correction-list",
4872 "media-play",
4873 "media-pause",
4874 "media-record",
4875 "media-fast-forward",
4876 "media-rewind",
4877 "media-channel-up",
4878 "media-channel-down"
4879 };
4880
4881 #else /* not HAVE_NTGUI */
4882
4883 /* This should be dealt with in XTread_socket now, and that doesn't
4884 depend on the client system having the Kana syms defined. See also
4885 the XK_kana_A case below. */
4886 #if 0
4887 #ifdef XK_kana_A
4888 static const char *const lispy_kana_keys[] =
4889 {
4890 /* X Keysym value */
4891 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, /* 0x400 .. 0x40f */
4892 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, /* 0x410 .. 0x41f */
4893 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, /* 0x420 .. 0x42f */
4894 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, /* 0x430 .. 0x43f */
4895 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, /* 0x440 .. 0x44f */
4896 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, /* 0x450 .. 0x45f */
4897 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, /* 0x460 .. 0x46f */
4898 0,0,0,0,0,0,0,0,0,0,0,0,0,0,"overline",0,
4899 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, /* 0x480 .. 0x48f */
4900 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, /* 0x490 .. 0x49f */
4901 0, "kana-fullstop", "kana-openingbracket", "kana-closingbracket",
4902 "kana-comma", "kana-conjunctive", "kana-WO", "kana-a",
4903 "kana-i", "kana-u", "kana-e", "kana-o",
4904 "kana-ya", "kana-yu", "kana-yo", "kana-tsu",
4905 "prolongedsound", "kana-A", "kana-I", "kana-U",
4906 "kana-E", "kana-O", "kana-KA", "kana-KI",
4907 "kana-KU", "kana-KE", "kana-KO", "kana-SA",
4908 "kana-SHI", "kana-SU", "kana-SE", "kana-SO",
4909 "kana-TA", "kana-CHI", "kana-TSU", "kana-TE",
4910 "kana-TO", "kana-NA", "kana-NI", "kana-NU",
4911 "kana-NE", "kana-NO", "kana-HA", "kana-HI",
4912 "kana-FU", "kana-HE", "kana-HO", "kana-MA",
4913 "kana-MI", "kana-MU", "kana-ME", "kana-MO",
4914 "kana-YA", "kana-YU", "kana-YO", "kana-RA",
4915 "kana-RI", "kana-RU", "kana-RE", "kana-RO",
4916 "kana-WA", "kana-N", "voicedsound", "semivoicedsound",
4917 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, /* 0x4e0 .. 0x4ef */
4918 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, /* 0x4f0 .. 0x4ff */
4919 };
4920 #endif /* XK_kana_A */
4921 #endif /* 0 */
4922
4923 #define FUNCTION_KEY_OFFSET 0xff00
4924
4925 /* You'll notice that this table is arranged to be conveniently
4926 indexed by X Windows keysym values. */
4927 static const char *const lispy_function_keys[] =
4928 {
4929 /* X Keysym value */
4930
4931 0, 0, 0, 0, 0, 0, 0, 0, /* 0xff00...0f */
4932 "backspace", "tab", "linefeed", "clear",
4933 0, "return", 0, 0,
4934 0, 0, 0, "pause", /* 0xff10...1f */
4935 0, 0, 0, 0, 0, 0, 0, "escape",
4936 0, 0, 0, 0,
4937 0, "kanji", "muhenkan", "henkan", /* 0xff20...2f */
4938 "romaji", "hiragana", "katakana", "hiragana-katakana",
4939 "zenkaku", "hankaku", "zenkaku-hankaku", "touroku",
4940 "massyo", "kana-lock", "kana-shift", "eisu-shift",
4941 "eisu-toggle", /* 0xff30...3f */
4942 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
4943 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* 0xff40...4f */
4944
4945 "home", "left", "up", "right", /* 0xff50 */ /* IsCursorKey */
4946 "down", "prior", "next", "end",
4947 "begin", 0, 0, 0, 0, 0, 0, 0,
4948 "select", /* 0xff60 */ /* IsMiscFunctionKey */
4949 "print",
4950 "execute",
4951 "insert",
4952 0, /* 0xff64 */
4953 "undo",
4954 "redo",
4955 "menu",
4956 "find",
4957 "cancel",
4958 "help",
4959 "break", /* 0xff6b */
4960
4961 0, 0, 0, 0,
4962 0, 0, 0, 0, "backtab", 0, 0, 0, /* 0xff70... */
4963 0, 0, 0, 0, 0, 0, 0, "kp-numlock", /* 0xff78... */
4964 "kp-space", /* 0xff80 */ /* IsKeypadKey */
4965 0, 0, 0, 0, 0, 0, 0, 0,
4966 "kp-tab", /* 0xff89 */
4967 0, 0, 0,
4968 "kp-enter", /* 0xff8d */
4969 0, 0, 0,
4970 "kp-f1", /* 0xff91 */
4971 "kp-f2",
4972 "kp-f3",
4973 "kp-f4",
4974 "kp-home", /* 0xff95 */
4975 "kp-left",
4976 "kp-up",
4977 "kp-right",
4978 "kp-down",
4979 "kp-prior", /* kp-page-up */
4980 "kp-next", /* kp-page-down */
4981 "kp-end",
4982 "kp-begin",
4983 "kp-insert",
4984 "kp-delete",
4985 0, /* 0xffa0 */
4986 0, 0, 0, 0, 0, 0, 0, 0, 0,
4987 "kp-multiply", /* 0xffaa */
4988 "kp-add",
4989 "kp-separator",
4990 "kp-subtract",
4991 "kp-decimal",
4992 "kp-divide", /* 0xffaf */
4993 "kp-0", /* 0xffb0 */
4994 "kp-1", "kp-2", "kp-3", "kp-4", "kp-5", "kp-6", "kp-7", "kp-8", "kp-9",
4995 0, /* 0xffba */
4996 0, 0,
4997 "kp-equal", /* 0xffbd */
4998 "f1", /* 0xffbe */ /* IsFunctionKey */
4999 "f2",
5000 "f3", "f4", "f5", "f6", "f7", "f8", "f9", "f10", /* 0xffc0 */
5001 "f11", "f12", "f13", "f14", "f15", "f16", "f17", "f18",
5002 "f19", "f20", "f21", "f22", "f23", "f24", "f25", "f26", /* 0xffd0 */
5003 "f27", "f28", "f29", "f30", "f31", "f32", "f33", "f34",
5004 "f35", 0, 0, 0, 0, 0, 0, 0, /* 0xffe0 */
5005 0, 0, 0, 0, 0, 0, 0, 0,
5006 0, 0, 0, 0, 0, 0, 0, 0, /* 0xfff0 */
5007 0, 0, 0, 0, 0, 0, 0, "delete"
5008 };
5009
5010 /* ISO 9995 Function and Modifier Keys; the first byte is 0xFE. */
5011 #define ISO_FUNCTION_KEY_OFFSET 0xfe00
5012
5013 static const char *const iso_lispy_function_keys[] =
5014 {
5015 0, 0, 0, 0, 0, 0, 0, 0, /* 0xfe00 */
5016 0, 0, 0, 0, 0, 0, 0, 0, /* 0xfe08 */
5017 0, 0, 0, 0, 0, 0, 0, 0, /* 0xfe10 */
5018 0, 0, 0, 0, 0, 0, 0, 0, /* 0xfe18 */
5019 "iso-lefttab", /* 0xfe20 */
5020 "iso-move-line-up", "iso-move-line-down",
5021 "iso-partial-line-up", "iso-partial-line-down",
5022 "iso-partial-space-left", "iso-partial-space-right",
5023 "iso-set-margin-left", "iso-set-margin-right", /* 0xffe27, 28 */
5024 "iso-release-margin-left", "iso-release-margin-right",
5025 "iso-release-both-margins",
5026 "iso-fast-cursor-left", "iso-fast-cursor-right",
5027 "iso-fast-cursor-up", "iso-fast-cursor-down",
5028 "iso-continuous-underline", "iso-discontinuous-underline", /* 0xfe30, 31 */
5029 "iso-emphasize", "iso-center-object", "iso-enter", /* ... 0xfe34 */
5030 };
5031
5032 #endif /* not HAVE_NTGUI */
5033
5034 static Lisp_Object Vlispy_mouse_stem;
5035
5036 static const char *const lispy_wheel_names[] =
5037 {
5038 "wheel-up", "wheel-down", "wheel-left", "wheel-right"
5039 };
5040
5041 /* drag-n-drop events are generated when a set of selected files are
5042 dragged from another application and dropped onto an Emacs window. */
5043 static const char *const lispy_drag_n_drop_names[] =
5044 {
5045 "drag-n-drop"
5046 };
5047
5048 /* An array of symbol indexes of scroll bar parts, indexed by an enum
5049 scroll_bar_part value. Note that Qnil corresponds to
5050 scroll_bar_nowhere and should not appear in Lisp events. */
5051 static short const scroll_bar_parts[] = {
5052 SYMBOL_INDEX (Qnil), SYMBOL_INDEX (Qabove_handle), SYMBOL_INDEX (Qhandle),
5053 SYMBOL_INDEX (Qbelow_handle), SYMBOL_INDEX (Qup), SYMBOL_INDEX (Qdown),
5054 SYMBOL_INDEX (Qtop), SYMBOL_INDEX (Qbottom), SYMBOL_INDEX (Qend_scroll),
5055 SYMBOL_INDEX (Qratio), SYMBOL_INDEX (Qbefore_handle),
5056 SYMBOL_INDEX (Qhorizontal_handle), SYMBOL_INDEX (Qafter_handle),
5057 SYMBOL_INDEX (Qleft), SYMBOL_INDEX (Qright), SYMBOL_INDEX (Qleftmost),
5058 SYMBOL_INDEX (Qrightmost), SYMBOL_INDEX (Qend_scroll), SYMBOL_INDEX (Qratio)
5059 };
5060
5061 /* A vector, indexed by button number, giving the down-going location
5062 of currently depressed buttons, both scroll bar and non-scroll bar.
5063
5064 The elements have the form
5065 (BUTTON-NUMBER MODIFIER-MASK . REST)
5066 where REST is the cdr of a position as it would be reported in the event.
5067
5068 The make_lispy_event function stores positions here to tell the
5069 difference between click and drag events, and to store the starting
5070 location to be included in drag events. */
5071
5072 static Lisp_Object button_down_location;
5073
5074 /* Information about the most recent up-going button event: Which
5075 button, what location, and what time. */
5076
5077 static int last_mouse_button;
5078 static int last_mouse_x;
5079 static int last_mouse_y;
5080 static Time button_down_time;
5081
5082 /* The number of clicks in this multiple-click. */
5083
5084 static int double_click_count;
5085
5086 /* X and Y are frame-relative coordinates for a click or wheel event.
5087 Return a Lisp-style event list. */
5088
5089 static Lisp_Object
5090 make_lispy_position (struct frame *f, Lisp_Object x, Lisp_Object y,
5091 Time t)
5092 {
5093 enum window_part part;
5094 Lisp_Object posn = Qnil;
5095 Lisp_Object extra_info = Qnil;
5096 /* Coordinate pixel positions to return. */
5097 int xret = 0, yret = 0;
5098 /* The window under frame pixel coordinates (x,y) */
5099 Lisp_Object window = f
5100 ? window_from_coordinates (f, XINT (x), XINT (y), &part, 0)
5101 : Qnil;
5102
5103 if (WINDOWP (window))
5104 {
5105 /* It's a click in window WINDOW at frame coordinates (X,Y) */
5106 struct window *w = XWINDOW (window);
5107 Lisp_Object string_info = Qnil;
5108 ptrdiff_t textpos = 0;
5109 int col = -1, row = -1;
5110 int dx = -1, dy = -1;
5111 int width = -1, height = -1;
5112 Lisp_Object object = Qnil;
5113
5114 /* Pixel coordinates relative to the window corner. */
5115 int wx = XINT (x) - WINDOW_LEFT_EDGE_X (w);
5116 int wy = XINT (y) - WINDOW_TOP_EDGE_Y (w);
5117
5118 /* For text area clicks, return X, Y relative to the corner of
5119 this text area. Note that dX, dY etc are set below, by
5120 buffer_posn_from_coords. */
5121 if (part == ON_TEXT)
5122 {
5123 xret = XINT (x) - window_box_left (w, TEXT_AREA);
5124 yret = wy - WINDOW_HEADER_LINE_HEIGHT (w);
5125 }
5126 /* For mode line and header line clicks, return X, Y relative to
5127 the left window edge. Use mode_line_string to look for a
5128 string on the click position. */
5129 else if (part == ON_MODE_LINE || part == ON_HEADER_LINE)
5130 {
5131 Lisp_Object string;
5132 ptrdiff_t charpos;
5133
5134 posn = (part == ON_MODE_LINE) ? Qmode_line : Qheader_line;
5135 /* Note that mode_line_string takes COL, ROW as pixels and
5136 converts them to characters. */
5137 col = wx;
5138 row = wy;
5139 string = mode_line_string (w, part, &col, &row, &charpos,
5140 &object, &dx, &dy, &width, &height);
5141 if (STRINGP (string))
5142 string_info = Fcons (string, make_number (charpos));
5143 textpos = -1;
5144
5145 xret = wx;
5146 yret = wy;
5147 }
5148 /* For fringes and margins, Y is relative to the area's (and the
5149 window's) top edge, while X is meaningless. */
5150 else if (part == ON_LEFT_MARGIN || part == ON_RIGHT_MARGIN)
5151 {
5152 Lisp_Object string;
5153 ptrdiff_t charpos;
5154
5155 posn = (part == ON_LEFT_MARGIN) ? Qleft_margin : Qright_margin;
5156 col = wx;
5157 row = wy;
5158 string = marginal_area_string (w, part, &col, &row, &charpos,
5159 &object, &dx, &dy, &width, &height);
5160 if (STRINGP (string))
5161 string_info = Fcons (string, make_number (charpos));
5162 xret = wx;
5163 yret = wy - WINDOW_HEADER_LINE_HEIGHT (w);
5164 }
5165 else if (part == ON_LEFT_FRINGE)
5166 {
5167 posn = Qleft_fringe;
5168 col = 0;
5169 xret = wx;
5170 dx = wx
5171 - (WINDOW_HAS_FRINGES_OUTSIDE_MARGINS (w)
5172 ? 0 : window_box_width (w, LEFT_MARGIN_AREA));
5173 dy = yret = wy - WINDOW_HEADER_LINE_HEIGHT (w);
5174 }
5175 else if (part == ON_RIGHT_FRINGE)
5176 {
5177 posn = Qright_fringe;
5178 col = 0;
5179 xret = wx;
5180 dx = wx
5181 - window_box_width (w, LEFT_MARGIN_AREA)
5182 - window_box_width (w, TEXT_AREA)
5183 - (WINDOW_HAS_FRINGES_OUTSIDE_MARGINS (w)
5184 ? window_box_width (w, RIGHT_MARGIN_AREA)
5185 : 0);
5186 dy = yret = wy - WINDOW_HEADER_LINE_HEIGHT (w);
5187 }
5188 else if (part == ON_VERTICAL_BORDER)
5189 {
5190 posn = Qvertical_line;
5191 width = 1;
5192 dx = 0;
5193 xret = wx;
5194 dy = yret = wy;
5195 }
5196 else if (part == ON_VERTICAL_SCROLL_BAR)
5197 {
5198 posn = Qvertical_scroll_bar;
5199 width = WINDOW_SCROLL_BAR_AREA_WIDTH (w);
5200 dx = xret = wx;
5201 dy = yret = wy;
5202 }
5203 else if (part == ON_HORIZONTAL_SCROLL_BAR)
5204 {
5205 posn = Qhorizontal_scroll_bar;
5206 width = WINDOW_SCROLL_BAR_AREA_HEIGHT (w);
5207 dx = xret = wx;
5208 dy = yret = wy;
5209 }
5210 else if (part == ON_RIGHT_DIVIDER)
5211 {
5212 posn = Qright_divider;
5213 width = WINDOW_RIGHT_DIVIDER_WIDTH (w);
5214 dx = xret = wx;
5215 dy = yret = wy;
5216 }
5217 else if (part == ON_BOTTOM_DIVIDER)
5218 {
5219 posn = Qbottom_divider;
5220 width = WINDOW_BOTTOM_DIVIDER_WIDTH (w);
5221 dx = xret = wx;
5222 dy = yret = wy;
5223 }
5224
5225 /* For clicks in the text area, fringes, margins, or vertical
5226 scroll bar, call buffer_posn_from_coords to extract TEXTPOS,
5227 the buffer position nearest to the click. */
5228 if (!textpos)
5229 {
5230 Lisp_Object string2, object2 = Qnil;
5231 struct display_pos p;
5232 int dx2, dy2;
5233 int width2, height2;
5234 /* The pixel X coordinate passed to buffer_posn_from_coords
5235 is the X coordinate relative to the text area for clicks
5236 in text-area, right-margin/fringe and right-side vertical
5237 scroll bar, zero otherwise. */
5238 int x2
5239 = (part == ON_TEXT) ? xret
5240 : (part == ON_RIGHT_FRINGE || part == ON_RIGHT_MARGIN
5241 || (part == ON_VERTICAL_SCROLL_BAR
5242 && WINDOW_HAS_VERTICAL_SCROLL_BAR_ON_RIGHT (w)))
5243 ? (XINT (x) - window_box_left (w, TEXT_AREA))
5244 : 0;
5245 int y2 = wy;
5246
5247 string2 = buffer_posn_from_coords (w, &x2, &y2, &p,
5248 &object2, &dx2, &dy2,
5249 &width2, &height2);
5250 textpos = CHARPOS (p.pos);
5251 if (col < 0) col = x2;
5252 if (row < 0) row = y2;
5253 if (dx < 0) dx = dx2;
5254 if (dy < 0) dy = dy2;
5255 if (width < 0) width = width2;
5256 if (height < 0) height = height2;
5257
5258 if (NILP (posn))
5259 {
5260 posn = make_number (textpos);
5261 if (STRINGP (string2))
5262 string_info = Fcons (string2,
5263 make_number (CHARPOS (p.string_pos)));
5264 }
5265 if (NILP (object))
5266 object = object2;
5267 }
5268
5269 #ifdef HAVE_WINDOW_SYSTEM
5270 if (IMAGEP (object))
5271 {
5272 Lisp_Object image_map, hotspot;
5273 if ((image_map = Fplist_get (XCDR (object), QCmap),
5274 !NILP (image_map))
5275 && (hotspot = find_hot_spot (image_map, dx, dy),
5276 CONSP (hotspot))
5277 && (hotspot = XCDR (hotspot), CONSP (hotspot)))
5278 posn = XCAR (hotspot);
5279 }
5280 #endif
5281
5282 /* Object info. */
5283 extra_info
5284 = list3 (object,
5285 Fcons (make_number (dx), make_number (dy)),
5286 Fcons (make_number (width), make_number (height)));
5287
5288 /* String info. */
5289 extra_info = Fcons (string_info,
5290 Fcons (textpos < 0 ? Qnil : make_number (textpos),
5291 Fcons (Fcons (make_number (col),
5292 make_number (row)),
5293 extra_info)));
5294 }
5295 else if (f != 0)
5296 {
5297 /* Return mouse pixel coordinates here. */
5298 XSETFRAME (window, f);
5299 xret = XINT (x);
5300 yret = XINT (y);
5301 }
5302 else
5303 window = Qnil;
5304
5305 return Fcons (window,
5306 Fcons (posn,
5307 Fcons (Fcons (make_number (xret),
5308 make_number (yret)),
5309 Fcons (make_number (t),
5310 extra_info))));
5311 }
5312
5313 /* Return non-zero if F is a GUI frame that uses some toolkit-managed
5314 menu bar. This really means that Emacs draws and manages the menu
5315 bar as part of its normal display, and therefore can compute its
5316 geometry. */
5317 static bool
5318 toolkit_menubar_in_use (struct frame *f)
5319 {
5320 #if defined (USE_X_TOOLKIT) || defined (USE_GTK) || defined (HAVE_NS) || defined (HAVE_NTGUI)
5321 return !(!FRAME_WINDOW_P (f));
5322 #else
5323 return false;
5324 #endif
5325 }
5326
5327 /* Build the part of Lisp event which represents scroll bar state from
5328 EV. TYPE is one of Qvertical_scroll_bar or Qhorizontal_scroll_bar. */
5329
5330 static Lisp_Object
5331 make_scroll_bar_position (struct input_event *ev, Lisp_Object type)
5332 {
5333 return list5 (ev->frame_or_window, type, Fcons (ev->x, ev->y),
5334 make_number (ev->timestamp),
5335 builtin_lisp_symbol (scroll_bar_parts[ev->part]));
5336 }
5337
5338 /* Given a struct input_event, build the lisp event which represents
5339 it. If EVENT is 0, build a mouse movement event from the mouse
5340 movement buffer, which should have a movement event in it.
5341
5342 Note that events must be passed to this function in the order they
5343 are received; this function stores the location of button presses
5344 in order to build drag events when the button is released. */
5345
5346 static Lisp_Object
5347 make_lispy_event (struct input_event *event)
5348 {
5349 int i;
5350
5351 switch (event->kind)
5352 {
5353 /* A simple keystroke. */
5354 case ASCII_KEYSTROKE_EVENT:
5355 case MULTIBYTE_CHAR_KEYSTROKE_EVENT:
5356 {
5357 Lisp_Object lispy_c;
5358 EMACS_INT c = event->code;
5359 if (event->kind == ASCII_KEYSTROKE_EVENT)
5360 {
5361 c &= 0377;
5362 eassert (c == event->code);
5363 /* Turn ASCII characters into control characters
5364 when proper. */
5365 if (event->modifiers & ctrl_modifier)
5366 {
5367 c = make_ctrl_char (c);
5368 event->modifiers &= ~ctrl_modifier;
5369 }
5370 }
5371
5372 /* Add in the other modifier bits. The shift key was taken care
5373 of by the X code. */
5374 c |= (event->modifiers
5375 & (meta_modifier | alt_modifier
5376 | hyper_modifier | super_modifier | ctrl_modifier));
5377 /* Distinguish Shift-SPC from SPC. */
5378 if ((event->code) == 040
5379 && event->modifiers & shift_modifier)
5380 c |= shift_modifier;
5381 button_down_time = 0;
5382 XSETFASTINT (lispy_c, c);
5383 return lispy_c;
5384 }
5385
5386 #ifdef HAVE_NS
5387 /* NS_NONKEY_EVENTs are just like NON_ASCII_KEYSTROKE_EVENTs,
5388 except that they are non-key events (last-nonmenu-event is nil). */
5389 case NS_NONKEY_EVENT:
5390 #endif
5391
5392 /* A function key. The symbol may need to have modifier prefixes
5393 tacked onto it. */
5394 case NON_ASCII_KEYSTROKE_EVENT:
5395 button_down_time = 0;
5396
5397 for (i = 0; i < ARRAYELTS (lispy_accent_codes); i++)
5398 if (event->code == lispy_accent_codes[i])
5399 return modify_event_symbol (i,
5400 event->modifiers,
5401 Qfunction_key, Qnil,
5402 lispy_accent_keys, &accent_key_syms,
5403 ARRAYELTS (lispy_accent_keys));
5404
5405 #if 0
5406 #ifdef XK_kana_A
5407 if (event->code >= 0x400 && event->code < 0x500)
5408 return modify_event_symbol (event->code - 0x400,
5409 event->modifiers & ~shift_modifier,
5410 Qfunction_key, Qnil,
5411 lispy_kana_keys, &func_key_syms,
5412 ARRAYELTS (lispy_kana_keys));
5413 #endif /* XK_kana_A */
5414 #endif /* 0 */
5415
5416 #ifdef ISO_FUNCTION_KEY_OFFSET
5417 if (event->code < FUNCTION_KEY_OFFSET
5418 && event->code >= ISO_FUNCTION_KEY_OFFSET)
5419 return modify_event_symbol (event->code - ISO_FUNCTION_KEY_OFFSET,
5420 event->modifiers,
5421 Qfunction_key, Qnil,
5422 iso_lispy_function_keys, &func_key_syms,
5423 ARRAYELTS (iso_lispy_function_keys));
5424 #endif
5425
5426 if ((FUNCTION_KEY_OFFSET <= event->code
5427 && (event->code
5428 < FUNCTION_KEY_OFFSET + ARRAYELTS (lispy_function_keys)))
5429 && lispy_function_keys[event->code - FUNCTION_KEY_OFFSET])
5430 return modify_event_symbol (event->code - FUNCTION_KEY_OFFSET,
5431 event->modifiers,
5432 Qfunction_key, Qnil,
5433 lispy_function_keys, &func_key_syms,
5434 ARRAYELTS (lispy_function_keys));
5435
5436 /* Handle system-specific or unknown keysyms.
5437 We need to use an alist rather than a vector as the cache
5438 since we can't make a vector long enough. */
5439 if (NILP (KVAR (current_kboard, system_key_syms)))
5440 kset_system_key_syms (current_kboard, Fcons (Qnil, Qnil));
5441 return modify_event_symbol (event->code,
5442 event->modifiers,
5443 Qfunction_key,
5444 KVAR (current_kboard, Vsystem_key_alist),
5445 0, &KVAR (current_kboard, system_key_syms),
5446 PTRDIFF_MAX);
5447
5448 #ifdef HAVE_NTGUI
5449 case MULTIMEDIA_KEY_EVENT:
5450 if (event->code < ARRAYELTS (lispy_multimedia_keys)
5451 && event->code > 0 && lispy_multimedia_keys[event->code])
5452 {
5453 return modify_event_symbol (event->code, event->modifiers,
5454 Qfunction_key, Qnil,
5455 lispy_multimedia_keys, &func_key_syms,
5456 ARRAYELTS (lispy_multimedia_keys));
5457 }
5458 return Qnil;
5459 #endif
5460
5461 /* A mouse click. Figure out where it is, decide whether it's
5462 a press, click or drag, and build the appropriate structure. */
5463 case MOUSE_CLICK_EVENT:
5464 #ifdef HAVE_GPM
5465 case GPM_CLICK_EVENT:
5466 #endif
5467 #ifndef USE_TOOLKIT_SCROLL_BARS
5468 case SCROLL_BAR_CLICK_EVENT:
5469 case HORIZONTAL_SCROLL_BAR_CLICK_EVENT:
5470 #endif
5471 {
5472 int button = event->code;
5473 bool is_double;
5474 Lisp_Object position;
5475 Lisp_Object *start_pos_ptr;
5476 Lisp_Object start_pos;
5477
5478 position = Qnil;
5479
5480 /* Build the position as appropriate for this mouse click. */
5481 if (event->kind == MOUSE_CLICK_EVENT
5482 #ifdef HAVE_GPM
5483 || event->kind == GPM_CLICK_EVENT
5484 #endif
5485 )
5486 {
5487 struct frame *f = XFRAME (event->frame_or_window);
5488 int row, column;
5489
5490 /* Ignore mouse events that were made on frame that
5491 have been deleted. */
5492 if (! FRAME_LIVE_P (f))
5493 return Qnil;
5494
5495 /* EVENT->x and EVENT->y are frame-relative pixel
5496 coordinates at this place. Under old redisplay, COLUMN
5497 and ROW are set to frame relative glyph coordinates
5498 which are then used to determine whether this click is
5499 in a menu (non-toolkit version). */
5500 if (!toolkit_menubar_in_use (f))
5501 {
5502 pixel_to_glyph_coords (f, XINT (event->x), XINT (event->y),
5503 &column, &row, NULL, 1);
5504
5505 /* In the non-toolkit version, clicks on the menu bar
5506 are ordinary button events in the event buffer.
5507 Distinguish them, and invoke the menu.
5508
5509 (In the toolkit version, the toolkit handles the
5510 menu bar and Emacs doesn't know about it until
5511 after the user makes a selection.) */
5512 if (row >= 0 && row < FRAME_MENU_BAR_LINES (f)
5513 && (event->modifiers & down_modifier))
5514 {
5515 Lisp_Object items, item;
5516
5517 /* Find the menu bar item under `column'. */
5518 item = Qnil;
5519 items = FRAME_MENU_BAR_ITEMS (f);
5520 for (i = 0; i < ASIZE (items); i += 4)
5521 {
5522 Lisp_Object pos, string;
5523 string = AREF (items, i + 1);
5524 pos = AREF (items, i + 3);
5525 if (NILP (string))
5526 break;
5527 if (column >= XINT (pos)
5528 && column < XINT (pos) + SCHARS (string))
5529 {
5530 item = AREF (items, i);
5531 break;
5532 }
5533 }
5534
5535 /* ELisp manual 2.4b says (x y) are window
5536 relative but code says they are
5537 frame-relative. */
5538 position = list4 (event->frame_or_window,
5539 Qmenu_bar,
5540 Fcons (event->x, event->y),
5541 make_number (event->timestamp));
5542
5543 return list2 (item, position);
5544 }
5545 }
5546
5547 position = make_lispy_position (f, event->x, event->y,
5548 event->timestamp);
5549 }
5550 #ifndef USE_TOOLKIT_SCROLL_BARS
5551 else
5552 /* It's a scrollbar click. */
5553 position = make_scroll_bar_position (event, Qvertical_scroll_bar);
5554 #endif /* not USE_TOOLKIT_SCROLL_BARS */
5555
5556 if (button >= ASIZE (button_down_location))
5557 {
5558 ptrdiff_t incr = button - ASIZE (button_down_location) + 1;
5559 button_down_location = larger_vector (button_down_location,
5560 incr, -1);
5561 mouse_syms = larger_vector (mouse_syms, incr, -1);
5562 }
5563
5564 start_pos_ptr = aref_addr (button_down_location, button);
5565 start_pos = *start_pos_ptr;
5566 *start_pos_ptr = Qnil;
5567
5568 {
5569 /* On window-system frames, use the value of
5570 double-click-fuzz as is. On other frames, interpret it
5571 as a multiple of 1/8 characters. */
5572 struct frame *f;
5573 int fuzz;
5574
5575 if (WINDOWP (event->frame_or_window))
5576 f = XFRAME (XWINDOW (event->frame_or_window)->frame);
5577 else if (FRAMEP (event->frame_or_window))
5578 f = XFRAME (event->frame_or_window);
5579 else
5580 emacs_abort ();
5581
5582 if (FRAME_WINDOW_P (f))
5583 fuzz = double_click_fuzz;
5584 else
5585 fuzz = double_click_fuzz / 8;
5586
5587 is_double = (button == last_mouse_button
5588 && (eabs (XINT (event->x) - last_mouse_x) <= fuzz)
5589 && (eabs (XINT (event->y) - last_mouse_y) <= fuzz)
5590 && button_down_time != 0
5591 && (EQ (Vdouble_click_time, Qt)
5592 || (NATNUMP (Vdouble_click_time)
5593 && (event->timestamp - button_down_time
5594 < XFASTINT (Vdouble_click_time)))));
5595 }
5596
5597 last_mouse_button = button;
5598 last_mouse_x = XINT (event->x);
5599 last_mouse_y = XINT (event->y);
5600
5601 /* If this is a button press, squirrel away the location, so
5602 we can decide later whether it was a click or a drag. */
5603 if (event->modifiers & down_modifier)
5604 {
5605 if (is_double)
5606 {
5607 double_click_count++;
5608 event->modifiers |= ((double_click_count > 2)
5609 ? triple_modifier
5610 : double_modifier);
5611 }
5612 else
5613 double_click_count = 1;
5614 button_down_time = event->timestamp;
5615 *start_pos_ptr = Fcopy_alist (position);
5616 ignore_mouse_drag_p = 0;
5617 }
5618
5619 /* Now we're releasing a button - check the co-ordinates to
5620 see if this was a click or a drag. */
5621 else if (event->modifiers & up_modifier)
5622 {
5623 /* If we did not see a down before this up, ignore the up.
5624 Probably this happened because the down event chose a
5625 menu item. It would be an annoyance to treat the
5626 release of the button that chose the menu item as a
5627 separate event. */
5628
5629 if (!CONSP (start_pos))
5630 return Qnil;
5631
5632 event->modifiers &= ~up_modifier;
5633
5634 {
5635 Lisp_Object new_down, down;
5636 EMACS_INT xdiff = double_click_fuzz, ydiff = double_click_fuzz;
5637
5638 /* The third element of every position
5639 should be the (x,y) pair. */
5640 down = Fcar (Fcdr (Fcdr (start_pos)));
5641 new_down = Fcar (Fcdr (Fcdr (position)));
5642
5643 if (CONSP (down)
5644 && INTEGERP (XCAR (down)) && INTEGERP (XCDR (down)))
5645 {
5646 xdiff = XINT (XCAR (new_down)) - XINT (XCAR (down));
5647 ydiff = XINT (XCDR (new_down)) - XINT (XCDR (down));
5648 }
5649
5650 if (ignore_mouse_drag_p)
5651 {
5652 event->modifiers |= click_modifier;
5653 ignore_mouse_drag_p = 0;
5654 }
5655 else if (xdiff < double_click_fuzz && xdiff > - double_click_fuzz
5656 && ydiff < double_click_fuzz && ydiff > - double_click_fuzz
5657 /* Maybe the mouse has moved a lot, caused scrolling, and
5658 eventually ended up at the same screen position (but
5659 not buffer position) in which case it is a drag, not
5660 a click. */
5661 /* FIXME: OTOH if the buffer position has changed
5662 because of a timer or process filter rather than
5663 because of mouse movement, it should be considered as
5664 a click. But mouse-drag-region completely ignores
5665 this case and it hasn't caused any real problem, so
5666 it's probably OK to ignore it as well. */
5667 && EQ (Fcar (Fcdr (start_pos)), Fcar (Fcdr (position))))
5668 /* Mouse hasn't moved (much). */
5669 event->modifiers |= click_modifier;
5670 else
5671 {
5672 button_down_time = 0;
5673 event->modifiers |= drag_modifier;
5674 }
5675
5676 /* Don't check is_double; treat this as multiple
5677 if the down-event was multiple. */
5678 if (double_click_count > 1)
5679 event->modifiers |= ((double_click_count > 2)
5680 ? triple_modifier
5681 : double_modifier);
5682 }
5683 }
5684 else
5685 /* Every mouse event should either have the down_modifier or
5686 the up_modifier set. */
5687 emacs_abort ();
5688
5689 {
5690 /* Get the symbol we should use for the mouse click. */
5691 Lisp_Object head;
5692
5693 head = modify_event_symbol (button,
5694 event->modifiers,
5695 Qmouse_click, Vlispy_mouse_stem,
5696 NULL,
5697 &mouse_syms,
5698 ASIZE (mouse_syms));
5699 if (event->modifiers & drag_modifier)
5700 return list3 (head, start_pos, position);
5701 else if (event->modifiers & (double_modifier | triple_modifier))
5702 return list3 (head, position, make_number (double_click_count));
5703 else
5704 return list2 (head, position);
5705 }
5706 }
5707
5708 case WHEEL_EVENT:
5709 case HORIZ_WHEEL_EVENT:
5710 {
5711 Lisp_Object position;
5712 Lisp_Object head;
5713
5714 /* Build the position as appropriate for this mouse click. */
5715 struct frame *f = XFRAME (event->frame_or_window);
5716
5717 /* Ignore wheel events that were made on frame that have been
5718 deleted. */
5719 if (! FRAME_LIVE_P (f))
5720 return Qnil;
5721
5722 position = make_lispy_position (f, event->x, event->y,
5723 event->timestamp);
5724
5725 /* Set double or triple modifiers to indicate the wheel speed. */
5726 {
5727 /* On window-system frames, use the value of
5728 double-click-fuzz as is. On other frames, interpret it
5729 as a multiple of 1/8 characters. */
5730 struct frame *fr;
5731 int fuzz;
5732 int symbol_num;
5733 bool is_double;
5734
5735 if (WINDOWP (event->frame_or_window))
5736 fr = XFRAME (XWINDOW (event->frame_or_window)->frame);
5737 else if (FRAMEP (event->frame_or_window))
5738 fr = XFRAME (event->frame_or_window);
5739 else
5740 emacs_abort ();
5741
5742 fuzz = FRAME_WINDOW_P (fr)
5743 ? double_click_fuzz : double_click_fuzz / 8;
5744
5745 if (event->modifiers & up_modifier)
5746 {
5747 /* Emit a wheel-up event. */
5748 event->modifiers &= ~up_modifier;
5749 symbol_num = 0;
5750 }
5751 else if (event->modifiers & down_modifier)
5752 {
5753 /* Emit a wheel-down event. */
5754 event->modifiers &= ~down_modifier;
5755 symbol_num = 1;
5756 }
5757 else
5758 /* Every wheel event should either have the down_modifier or
5759 the up_modifier set. */
5760 emacs_abort ();
5761
5762 if (event->kind == HORIZ_WHEEL_EVENT)
5763 symbol_num += 2;
5764
5765 is_double = (last_mouse_button == - (1 + symbol_num)
5766 && (eabs (XINT (event->x) - last_mouse_x) <= fuzz)
5767 && (eabs (XINT (event->y) - last_mouse_y) <= fuzz)
5768 && button_down_time != 0
5769 && (EQ (Vdouble_click_time, Qt)
5770 || (NATNUMP (Vdouble_click_time)
5771 && (event->timestamp - button_down_time
5772 < XFASTINT (Vdouble_click_time)))));
5773 if (is_double)
5774 {
5775 double_click_count++;
5776 event->modifiers |= ((double_click_count > 2)
5777 ? triple_modifier
5778 : double_modifier);
5779 }
5780 else
5781 {
5782 double_click_count = 1;
5783 event->modifiers |= click_modifier;
5784 }
5785
5786 button_down_time = event->timestamp;
5787 /* Use a negative value to distinguish wheel from mouse button. */
5788 last_mouse_button = - (1 + symbol_num);
5789 last_mouse_x = XINT (event->x);
5790 last_mouse_y = XINT (event->y);
5791
5792 /* Get the symbol we should use for the wheel event. */
5793 head = modify_event_symbol (symbol_num,
5794 event->modifiers,
5795 Qmouse_click,
5796 Qnil,
5797 lispy_wheel_names,
5798 &wheel_syms,
5799 ASIZE (wheel_syms));
5800 }
5801
5802 if (event->modifiers & (double_modifier | triple_modifier))
5803 return list3 (head, position, make_number (double_click_count));
5804 else
5805 return list2 (head, position);
5806 }
5807
5808
5809 #ifdef USE_TOOLKIT_SCROLL_BARS
5810
5811 /* We don't have down and up events if using toolkit scroll bars,
5812 so make this always a click event. Store in the `part' of
5813 the Lisp event a symbol which maps to the following actions:
5814
5815 `above_handle' page up
5816 `below_handle' page down
5817 `up' line up
5818 `down' line down
5819 `top' top of buffer
5820 `bottom' bottom of buffer
5821 `handle' thumb has been dragged.
5822 `end-scroll' end of interaction with scroll bar
5823
5824 The incoming input_event contains in its `part' member an
5825 index of type `enum scroll_bar_part' which we can use as an
5826 index in scroll_bar_parts to get the appropriate symbol. */
5827
5828 case SCROLL_BAR_CLICK_EVENT:
5829 {
5830 Lisp_Object position, head;
5831
5832 position = make_scroll_bar_position (event, Qvertical_scroll_bar);
5833
5834 /* Always treat scroll bar events as clicks. */
5835 event->modifiers |= click_modifier;
5836 event->modifiers &= ~up_modifier;
5837
5838 if (event->code >= ASIZE (mouse_syms))
5839 mouse_syms = larger_vector (mouse_syms,
5840 event->code - ASIZE (mouse_syms) + 1,
5841 -1);
5842
5843 /* Get the symbol we should use for the mouse click. */
5844 head = modify_event_symbol (event->code,
5845 event->modifiers,
5846 Qmouse_click,
5847 Vlispy_mouse_stem,
5848 NULL, &mouse_syms,
5849 ASIZE (mouse_syms));
5850 return list2 (head, position);
5851 }
5852
5853 case HORIZONTAL_SCROLL_BAR_CLICK_EVENT:
5854 {
5855 Lisp_Object position, head;
5856
5857 position = make_scroll_bar_position (event, Qhorizontal_scroll_bar);
5858
5859 /* Always treat scroll bar events as clicks. */
5860 event->modifiers |= click_modifier;
5861 event->modifiers &= ~up_modifier;
5862
5863 if (event->code >= ASIZE (mouse_syms))
5864 mouse_syms = larger_vector (mouse_syms,
5865 event->code - ASIZE (mouse_syms) + 1,
5866 -1);
5867
5868 /* Get the symbol we should use for the mouse click. */
5869 head = modify_event_symbol (event->code,
5870 event->modifiers,
5871 Qmouse_click,
5872 Vlispy_mouse_stem,
5873 NULL, &mouse_syms,
5874 ASIZE (mouse_syms));
5875 return list2 (head, position);
5876 }
5877
5878 #endif /* USE_TOOLKIT_SCROLL_BARS */
5879
5880 case DRAG_N_DROP_EVENT:
5881 {
5882 struct frame *f;
5883 Lisp_Object head, position;
5884 Lisp_Object files;
5885
5886 f = XFRAME (event->frame_or_window);
5887 files = event->arg;
5888
5889 /* Ignore mouse events that were made on frames that
5890 have been deleted. */
5891 if (! FRAME_LIVE_P (f))
5892 return Qnil;
5893
5894 position = make_lispy_position (f, event->x, event->y,
5895 event->timestamp);
5896
5897 head = modify_event_symbol (0, event->modifiers,
5898 Qdrag_n_drop, Qnil,
5899 lispy_drag_n_drop_names,
5900 &drag_n_drop_syms, 1);
5901 return list3 (head, position, files);
5902 }
5903
5904 #if defined (USE_X_TOOLKIT) || defined (HAVE_NTGUI) \
5905 || defined (HAVE_NS) || defined (USE_GTK)
5906 case MENU_BAR_EVENT:
5907 if (EQ (event->arg, event->frame_or_window))
5908 /* This is the prefix key. We translate this to
5909 `(menu_bar)' because the code in keyboard.c for menu
5910 events, which we use, relies on this. */
5911 return list1 (Qmenu_bar);
5912 return event->arg;
5913 #endif
5914
5915 case SELECT_WINDOW_EVENT:
5916 /* Make an event (select-window (WINDOW)). */
5917 return list2 (Qselect_window, list1 (event->frame_or_window));
5918
5919 case TOOL_BAR_EVENT:
5920 if (EQ (event->arg, event->frame_or_window))
5921 /* This is the prefix key. We translate this to
5922 `(tool_bar)' because the code in keyboard.c for tool bar
5923 events, which we use, relies on this. */
5924 return list1 (Qtool_bar);
5925 else if (SYMBOLP (event->arg))
5926 return apply_modifiers (event->modifiers, event->arg);
5927 return event->arg;
5928
5929 case USER_SIGNAL_EVENT:
5930 /* A user signal. */
5931 {
5932 char *name = find_user_signal_name (event->code);
5933 if (!name)
5934 emacs_abort ();
5935 return intern (name);
5936 }
5937
5938 case SAVE_SESSION_EVENT:
5939 return Qsave_session;
5940
5941 #ifdef HAVE_DBUS
5942 case DBUS_EVENT:
5943 {
5944 return Fcons (Qdbus_event, event->arg);
5945 }
5946 #endif /* HAVE_DBUS */
5947
5948 #if defined HAVE_INOTIFY || defined HAVE_KQUEUE || defined HAVE_GFILENOTIFY
5949 case FILE_NOTIFY_EVENT:
5950 {
5951 return Fcons (Qfile_notify, event->arg);
5952 }
5953 #endif /* HAVE_INOTIFY || HAVE_KQUEUE || HAVE_GFILENOTIFY */
5954
5955 case CONFIG_CHANGED_EVENT:
5956 return list3 (Qconfig_changed_event,
5957 event->arg, event->frame_or_window);
5958
5959 /* The 'kind' field of the event is something we don't recognize. */
5960 default:
5961 emacs_abort ();
5962 }
5963 }
5964
5965 static Lisp_Object
5966 make_lispy_movement (struct frame *frame, Lisp_Object bar_window, enum scroll_bar_part part,
5967 Lisp_Object x, Lisp_Object y, Time t)
5968 {
5969 /* Is it a scroll bar movement? */
5970 if (frame && ! NILP (bar_window))
5971 {
5972 Lisp_Object part_sym;
5973
5974 part_sym = builtin_lisp_symbol (scroll_bar_parts[part]);
5975 return list2 (Qscroll_bar_movement,
5976 list5 (bar_window,
5977 Qvertical_scroll_bar,
5978 Fcons (x, y),
5979 make_number (t),
5980 part_sym));
5981 }
5982 /* Or is it an ordinary mouse movement? */
5983 else
5984 {
5985 Lisp_Object position;
5986 position = make_lispy_position (frame, x, y, t);
5987 return list2 (Qmouse_movement, position);
5988 }
5989 }
5990
5991 /* Construct a switch frame event. */
5992 static Lisp_Object
5993 make_lispy_switch_frame (Lisp_Object frame)
5994 {
5995 return list2 (Qswitch_frame, frame);
5996 }
5997
5998 static Lisp_Object
5999 make_lispy_focus_in (Lisp_Object frame)
6000 {
6001 return list2 (Qfocus_in, frame);
6002 }
6003
6004 #ifdef HAVE_WINDOW_SYSTEM
6005
6006 static Lisp_Object
6007 make_lispy_focus_out (Lisp_Object frame)
6008 {
6009 return list2 (Qfocus_out, frame);
6010 }
6011
6012 #endif /* HAVE_WINDOW_SYSTEM */
6013
6014 /* Manipulating modifiers. */
6015
6016 /* Parse the name of SYMBOL, and return the set of modifiers it contains.
6017
6018 If MODIFIER_END is non-zero, set *MODIFIER_END to the position in
6019 SYMBOL's name of the end of the modifiers; the string from this
6020 position is the unmodified symbol name.
6021
6022 This doesn't use any caches. */
6023
6024 static int
6025 parse_modifiers_uncached (Lisp_Object symbol, ptrdiff_t *modifier_end)
6026 {
6027 Lisp_Object name;
6028 ptrdiff_t i;
6029 int modifiers;
6030
6031 CHECK_SYMBOL (symbol);
6032
6033 modifiers = 0;
6034 name = SYMBOL_NAME (symbol);
6035
6036 for (i = 0; i < SBYTES (name) - 1; )
6037 {
6038 ptrdiff_t this_mod_end = 0;
6039 int this_mod = 0;
6040
6041 /* See if the name continues with a modifier word.
6042 Check that the word appears, but don't check what follows it.
6043 Set this_mod and this_mod_end to record what we find. */
6044
6045 switch (SREF (name, i))
6046 {
6047 #define SINGLE_LETTER_MOD(BIT) \
6048 (this_mod_end = i + 1, this_mod = BIT)
6049
6050 case 'A':
6051 SINGLE_LETTER_MOD (alt_modifier);
6052 break;
6053
6054 case 'C':
6055 SINGLE_LETTER_MOD (ctrl_modifier);
6056 break;
6057
6058 case 'H':
6059 SINGLE_LETTER_MOD (hyper_modifier);
6060 break;
6061
6062 case 'M':
6063 SINGLE_LETTER_MOD (meta_modifier);
6064 break;
6065
6066 case 'S':
6067 SINGLE_LETTER_MOD (shift_modifier);
6068 break;
6069
6070 case 's':
6071 SINGLE_LETTER_MOD (super_modifier);
6072 break;
6073
6074 #undef SINGLE_LETTER_MOD
6075
6076 #define MULTI_LETTER_MOD(BIT, NAME, LEN) \
6077 if (i + LEN + 1 <= SBYTES (name) \
6078 && ! memcmp (SDATA (name) + i, NAME, LEN)) \
6079 { \
6080 this_mod_end = i + LEN; \
6081 this_mod = BIT; \
6082 }
6083
6084 case 'd':
6085 MULTI_LETTER_MOD (drag_modifier, "drag", 4);
6086 MULTI_LETTER_MOD (down_modifier, "down", 4);
6087 MULTI_LETTER_MOD (double_modifier, "double", 6);
6088 break;
6089
6090 case 't':
6091 MULTI_LETTER_MOD (triple_modifier, "triple", 6);
6092 break;
6093
6094 case 'u':
6095 MULTI_LETTER_MOD (up_modifier, "up", 2);
6096 break;
6097 #undef MULTI_LETTER_MOD
6098
6099 }
6100
6101 /* If we found no modifier, stop looking for them. */
6102 if (this_mod_end == 0)
6103 break;
6104
6105 /* Check there is a dash after the modifier, so that it
6106 really is a modifier. */
6107 if (this_mod_end >= SBYTES (name)
6108 || SREF (name, this_mod_end) != '-')
6109 break;
6110
6111 /* This modifier is real; look for another. */
6112 modifiers |= this_mod;
6113 i = this_mod_end + 1;
6114 }
6115
6116 /* Should we include the `click' modifier? */
6117 if (! (modifiers & (down_modifier | drag_modifier
6118 | double_modifier | triple_modifier))
6119 && i + 7 == SBYTES (name)
6120 && memcmp (SDATA (name) + i, "mouse-", 6) == 0
6121 && ('0' <= SREF (name, i + 6) && SREF (name, i + 6) <= '9'))
6122 modifiers |= click_modifier;
6123
6124 if (! (modifiers & (double_modifier | triple_modifier))
6125 && i + 6 < SBYTES (name)
6126 && memcmp (SDATA (name) + i, "wheel-", 6) == 0)
6127 modifiers |= click_modifier;
6128
6129 if (modifier_end)
6130 *modifier_end = i;
6131
6132 return modifiers;
6133 }
6134
6135 /* Return a symbol whose name is the modifier prefixes for MODIFIERS
6136 prepended to the string BASE[0..BASE_LEN-1].
6137 This doesn't use any caches. */
6138 static Lisp_Object
6139 apply_modifiers_uncached (int modifiers, char *base, int base_len, int base_len_byte)
6140 {
6141 /* Since BASE could contain nulls, we can't use intern here; we have
6142 to use Fintern, which expects a genuine Lisp_String, and keeps a
6143 reference to it. */
6144 char new_mods[sizeof "A-C-H-M-S-s-up-down-drag-double-triple-"];
6145 int mod_len;
6146
6147 {
6148 char *p = new_mods;
6149
6150 /* Mouse events should not exhibit the `up' modifier once they
6151 leave the event queue only accessible to C code; `up' will
6152 always be turned into a click or drag event before being
6153 presented to lisp code. But since lisp events can be
6154 synthesized bypassing the event queue and pushed into
6155 `unread-command-events' or its companions, it's better to just
6156 deal with unexpected modifier combinations. */
6157
6158 if (modifiers & alt_modifier) { *p++ = 'A'; *p++ = '-'; }
6159 if (modifiers & ctrl_modifier) { *p++ = 'C'; *p++ = '-'; }
6160 if (modifiers & hyper_modifier) { *p++ = 'H'; *p++ = '-'; }
6161 if (modifiers & meta_modifier) { *p++ = 'M'; *p++ = '-'; }
6162 if (modifiers & shift_modifier) { *p++ = 'S'; *p++ = '-'; }
6163 if (modifiers & super_modifier) { *p++ = 's'; *p++ = '-'; }
6164 if (modifiers & double_modifier) p = stpcpy (p, "double-");
6165 if (modifiers & triple_modifier) p = stpcpy (p, "triple-");
6166 if (modifiers & up_modifier) p = stpcpy (p, "up-");
6167 if (modifiers & down_modifier) p = stpcpy (p, "down-");
6168 if (modifiers & drag_modifier) p = stpcpy (p, "drag-");
6169 /* The click modifier is denoted by the absence of other modifiers. */
6170
6171 *p = '\0';
6172
6173 mod_len = p - new_mods;
6174 }
6175
6176 {
6177 Lisp_Object new_name;
6178
6179 new_name = make_uninit_multibyte_string (mod_len + base_len,
6180 mod_len + base_len_byte);
6181 memcpy (SDATA (new_name), new_mods, mod_len);
6182 memcpy (SDATA (new_name) + mod_len, base, base_len_byte);
6183
6184 return Fintern (new_name, Qnil);
6185 }
6186 }
6187
6188
6189 static const char *const modifier_names[] =
6190 {
6191 "up", "down", "drag", "click", "double", "triple", 0, 0,
6192 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
6193 0, 0, "alt", "super", "hyper", "shift", "control", "meta"
6194 };
6195 #define NUM_MOD_NAMES ARRAYELTS (modifier_names)
6196
6197 static Lisp_Object modifier_symbols;
6198
6199 /* Return the list of modifier symbols corresponding to the mask MODIFIERS. */
6200 static Lisp_Object
6201 lispy_modifier_list (int modifiers)
6202 {
6203 Lisp_Object modifier_list;
6204 int i;
6205
6206 modifier_list = Qnil;
6207 for (i = 0; (1<<i) <= modifiers && i < NUM_MOD_NAMES; i++)
6208 if (modifiers & (1<<i))
6209 modifier_list = Fcons (AREF (modifier_symbols, i),
6210 modifier_list);
6211
6212 return modifier_list;
6213 }
6214
6215
6216 /* Parse the modifiers on SYMBOL, and return a list like (UNMODIFIED MASK),
6217 where UNMODIFIED is the unmodified form of SYMBOL,
6218 MASK is the set of modifiers present in SYMBOL's name.
6219 This is similar to parse_modifiers_uncached, but uses the cache in
6220 SYMBOL's Qevent_symbol_element_mask property, and maintains the
6221 Qevent_symbol_elements property. */
6222
6223 #define KEY_TO_CHAR(k) (XINT (k) & ((1 << CHARACTERBITS) - 1))
6224
6225 Lisp_Object
6226 parse_modifiers (Lisp_Object symbol)
6227 {
6228 Lisp_Object elements;
6229
6230 if (INTEGERP (symbol))
6231 return list2i (KEY_TO_CHAR (symbol), XINT (symbol) & CHAR_MODIFIER_MASK);
6232 else if (!SYMBOLP (symbol))
6233 return Qnil;
6234
6235 elements = Fget (symbol, Qevent_symbol_element_mask);
6236 if (CONSP (elements))
6237 return elements;
6238 else
6239 {
6240 ptrdiff_t end;
6241 int modifiers = parse_modifiers_uncached (symbol, &end);
6242 Lisp_Object unmodified;
6243 Lisp_Object mask;
6244
6245 unmodified = Fintern (make_string (SSDATA (SYMBOL_NAME (symbol)) + end,
6246 SBYTES (SYMBOL_NAME (symbol)) - end),
6247 Qnil);
6248
6249 if (modifiers & ~INTMASK)
6250 emacs_abort ();
6251 XSETFASTINT (mask, modifiers);
6252 elements = list2 (unmodified, mask);
6253
6254 /* Cache the parsing results on SYMBOL. */
6255 Fput (symbol, Qevent_symbol_element_mask,
6256 elements);
6257 Fput (symbol, Qevent_symbol_elements,
6258 Fcons (unmodified, lispy_modifier_list (modifiers)));
6259
6260 /* Since we know that SYMBOL is modifiers applied to unmodified,
6261 it would be nice to put that in unmodified's cache.
6262 But we can't, since we're not sure that parse_modifiers is
6263 canonical. */
6264
6265 return elements;
6266 }
6267 }
6268
6269 DEFUN ("internal-event-symbol-parse-modifiers", Fevent_symbol_parse_modifiers,
6270 Sevent_symbol_parse_modifiers, 1, 1, 0,
6271 doc: /* Parse the event symbol. For internal use. */)
6272 (Lisp_Object symbol)
6273 {
6274 /* Fill the cache if needed. */
6275 parse_modifiers (symbol);
6276 /* Ignore the result (which is stored on Qevent_symbol_element_mask)
6277 and use the Lispier representation stored on Qevent_symbol_elements
6278 instead. */
6279 return Fget (symbol, Qevent_symbol_elements);
6280 }
6281
6282 /* Apply the modifiers MODIFIERS to the symbol BASE.
6283 BASE must be unmodified.
6284
6285 This is like apply_modifiers_uncached, but uses BASE's
6286 Qmodifier_cache property, if present.
6287
6288 apply_modifiers copies the value of BASE's Qevent_kind property to
6289 the modified symbol. */
6290 static Lisp_Object
6291 apply_modifiers (int modifiers, Lisp_Object base)
6292 {
6293 Lisp_Object cache, idx, entry, new_symbol;
6294
6295 /* Mask out upper bits. We don't know where this value's been. */
6296 modifiers &= INTMASK;
6297
6298 if (INTEGERP (base))
6299 return make_number (XINT (base) | modifiers);
6300
6301 /* The click modifier never figures into cache indices. */
6302 cache = Fget (base, Qmodifier_cache);
6303 XSETFASTINT (idx, (modifiers & ~click_modifier));
6304 entry = assq_no_quit (idx, cache);
6305
6306 if (CONSP (entry))
6307 new_symbol = XCDR (entry);
6308 else
6309 {
6310 /* We have to create the symbol ourselves. */
6311 new_symbol = apply_modifiers_uncached (modifiers,
6312 SSDATA (SYMBOL_NAME (base)),
6313 SCHARS (SYMBOL_NAME (base)),
6314 SBYTES (SYMBOL_NAME (base)));
6315
6316 /* Add the new symbol to the base's cache. */
6317 entry = Fcons (idx, new_symbol);
6318 Fput (base, Qmodifier_cache, Fcons (entry, cache));
6319
6320 /* We have the parsing info now for free, so we could add it to
6321 the caches:
6322 XSETFASTINT (idx, modifiers);
6323 Fput (new_symbol, Qevent_symbol_element_mask,
6324 list2 (base, idx));
6325 Fput (new_symbol, Qevent_symbol_elements,
6326 Fcons (base, lispy_modifier_list (modifiers)));
6327 Sadly, this is only correct if `base' is indeed a base event,
6328 which is not necessarily the case. -stef */
6329 }
6330
6331 /* Make sure this symbol is of the same kind as BASE.
6332
6333 You'd think we could just set this once and for all when we
6334 intern the symbol above, but reorder_modifiers may call us when
6335 BASE's property isn't set right; we can't assume that just
6336 because it has a Qmodifier_cache property it must have its
6337 Qevent_kind set right as well. */
6338 if (NILP (Fget (new_symbol, Qevent_kind)))
6339 {
6340 Lisp_Object kind;
6341
6342 kind = Fget (base, Qevent_kind);
6343 if (! NILP (kind))
6344 Fput (new_symbol, Qevent_kind, kind);
6345 }
6346
6347 return new_symbol;
6348 }
6349
6350
6351 /* Given a symbol whose name begins with modifiers ("C-", "M-", etc),
6352 return a symbol with the modifiers placed in the canonical order.
6353 Canonical order is alphabetical, except for down and drag, which
6354 always come last. The 'click' modifier is never written out.
6355
6356 Fdefine_key calls this to make sure that (for example) C-M-foo
6357 and M-C-foo end up being equivalent in the keymap. */
6358
6359 Lisp_Object
6360 reorder_modifiers (Lisp_Object symbol)
6361 {
6362 /* It's hopefully okay to write the code this way, since everything
6363 will soon be in caches, and no consing will be done at all. */
6364 Lisp_Object parsed;
6365
6366 parsed = parse_modifiers (symbol);
6367 return apply_modifiers (XFASTINT (XCAR (XCDR (parsed))),
6368 XCAR (parsed));
6369 }
6370
6371
6372 /* For handling events, we often want to produce a symbol whose name
6373 is a series of modifier key prefixes ("M-", "C-", etcetera) attached
6374 to some base, like the name of a function key or mouse button.
6375 modify_event_symbol produces symbols of this sort.
6376
6377 NAME_TABLE should point to an array of strings, such that NAME_TABLE[i]
6378 is the name of the i'th symbol. TABLE_SIZE is the number of elements
6379 in the table.
6380
6381 Alternatively, NAME_ALIST_OR_STEM is either an alist mapping codes
6382 into symbol names, or a string specifying a name stem used to
6383 construct a symbol name or the form `STEM-N', where N is the decimal
6384 representation of SYMBOL_NUM. NAME_ALIST_OR_STEM is used if it is
6385 non-nil; otherwise NAME_TABLE is used.
6386
6387 SYMBOL_TABLE should be a pointer to a Lisp_Object whose value will
6388 persist between calls to modify_event_symbol that it can use to
6389 store a cache of the symbols it's generated for this NAME_TABLE
6390 before. The object stored there may be a vector or an alist.
6391
6392 SYMBOL_NUM is the number of the base name we want from NAME_TABLE.
6393
6394 MODIFIERS is a set of modifier bits (as given in struct input_events)
6395 whose prefixes should be applied to the symbol name.
6396
6397 SYMBOL_KIND is the value to be placed in the event_kind property of
6398 the returned symbol.
6399
6400 The symbols we create are supposed to have an
6401 `event-symbol-elements' property, which lists the modifiers present
6402 in the symbol's name. */
6403
6404 static Lisp_Object
6405 modify_event_symbol (ptrdiff_t symbol_num, int modifiers, Lisp_Object symbol_kind,
6406 Lisp_Object name_alist_or_stem, const char *const *name_table,
6407 Lisp_Object *symbol_table, ptrdiff_t table_size)
6408 {
6409 Lisp_Object value;
6410 Lisp_Object symbol_int;
6411
6412 /* Get rid of the "vendor-specific" bit here. */
6413 XSETINT (symbol_int, symbol_num & 0xffffff);
6414
6415 /* Is this a request for a valid symbol? */
6416 if (symbol_num < 0 || symbol_num >= table_size)
6417 return Qnil;
6418
6419 if (CONSP (*symbol_table))
6420 value = Fcdr (assq_no_quit (symbol_int, *symbol_table));
6421
6422 /* If *symbol_table doesn't seem to be initialized properly, fix that.
6423 *symbol_table should be a lisp vector TABLE_SIZE elements long,
6424 where the Nth element is the symbol for NAME_TABLE[N], or nil if
6425 we've never used that symbol before. */
6426 else
6427 {
6428 if (! VECTORP (*symbol_table)
6429 || ASIZE (*symbol_table) != table_size)
6430 {
6431 Lisp_Object size;
6432
6433 XSETFASTINT (size, table_size);
6434 *symbol_table = Fmake_vector (size, Qnil);
6435 }
6436
6437 value = AREF (*symbol_table, symbol_num);
6438 }
6439
6440 /* Have we already used this symbol before? */
6441 if (NILP (value))
6442 {
6443 /* No; let's create it. */
6444 if (CONSP (name_alist_or_stem))
6445 value = Fcdr_safe (Fassq (symbol_int, name_alist_or_stem));
6446 else if (STRINGP (name_alist_or_stem))
6447 {
6448 char *buf;
6449 ptrdiff_t len = (SBYTES (name_alist_or_stem)
6450 + sizeof "-" + INT_STRLEN_BOUND (EMACS_INT));
6451 USE_SAFE_ALLOCA;
6452 buf = SAFE_ALLOCA (len);
6453 esprintf (buf, "%s-%"pI"d", SDATA (name_alist_or_stem),
6454 XINT (symbol_int) + 1);
6455 value = intern (buf);
6456 SAFE_FREE ();
6457 }
6458 else if (name_table != 0 && name_table[symbol_num])
6459 value = intern (name_table[symbol_num]);
6460
6461 #ifdef HAVE_WINDOW_SYSTEM
6462 if (NILP (value))
6463 {
6464 char *name = x_get_keysym_name (symbol_num);
6465 if (name)
6466 value = intern (name);
6467 }
6468 #endif
6469
6470 if (NILP (value))
6471 {
6472 char buf[sizeof "key-" + INT_STRLEN_BOUND (EMACS_INT)];
6473 sprintf (buf, "key-%"pD"d", symbol_num);
6474 value = intern (buf);
6475 }
6476
6477 if (CONSP (*symbol_table))
6478 *symbol_table = Fcons (Fcons (symbol_int, value), *symbol_table);
6479 else
6480 ASET (*symbol_table, symbol_num, value);
6481
6482 /* Fill in the cache entries for this symbol; this also
6483 builds the Qevent_symbol_elements property, which the user
6484 cares about. */
6485 apply_modifiers (modifiers & click_modifier, value);
6486 Fput (value, Qevent_kind, symbol_kind);
6487 }
6488
6489 /* Apply modifiers to that symbol. */
6490 return apply_modifiers (modifiers, value);
6491 }
6492 \f
6493 /* Convert a list that represents an event type,
6494 such as (ctrl meta backspace), into the usual representation of that
6495 event type as a number or a symbol. */
6496
6497 DEFUN ("event-convert-list", Fevent_convert_list, Sevent_convert_list, 1, 1, 0,
6498 doc: /* Convert the event description list EVENT-DESC to an event type.
6499 EVENT-DESC should contain one base event type (a character or symbol)
6500 and zero or more modifier names (control, meta, hyper, super, shift, alt,
6501 drag, down, double or triple). The base must be last.
6502 The return value is an event type (a character or symbol) which
6503 has the same base event type and all the specified modifiers. */)
6504 (Lisp_Object event_desc)
6505 {
6506 Lisp_Object base;
6507 int modifiers = 0;
6508 Lisp_Object rest;
6509
6510 base = Qnil;
6511 rest = event_desc;
6512 while (CONSP (rest))
6513 {
6514 Lisp_Object elt;
6515 int this = 0;
6516
6517 elt = XCAR (rest);
6518 rest = XCDR (rest);
6519
6520 /* Given a symbol, see if it is a modifier name. */
6521 if (SYMBOLP (elt) && CONSP (rest))
6522 this = parse_solitary_modifier (elt);
6523
6524 if (this != 0)
6525 modifiers |= this;
6526 else if (!NILP (base))
6527 error ("Two bases given in one event");
6528 else
6529 base = elt;
6530
6531 }
6532
6533 /* Let the symbol A refer to the character A. */
6534 if (SYMBOLP (base) && SCHARS (SYMBOL_NAME (base)) == 1)
6535 XSETINT (base, SREF (SYMBOL_NAME (base), 0));
6536
6537 if (INTEGERP (base))
6538 {
6539 /* Turn (shift a) into A. */
6540 if ((modifiers & shift_modifier) != 0
6541 && (XINT (base) >= 'a' && XINT (base) <= 'z'))
6542 {
6543 XSETINT (base, XINT (base) - ('a' - 'A'));
6544 modifiers &= ~shift_modifier;
6545 }
6546
6547 /* Turn (control a) into C-a. */
6548 if (modifiers & ctrl_modifier)
6549 return make_number ((modifiers & ~ctrl_modifier)
6550 | make_ctrl_char (XINT (base)));
6551 else
6552 return make_number (modifiers | XINT (base));
6553 }
6554 else if (SYMBOLP (base))
6555 return apply_modifiers (modifiers, base);
6556 else
6557 error ("Invalid base event");
6558 }
6559
6560 /* Try to recognize SYMBOL as a modifier name.
6561 Return the modifier flag bit, or 0 if not recognized. */
6562
6563 int
6564 parse_solitary_modifier (Lisp_Object symbol)
6565 {
6566 Lisp_Object name = SYMBOL_NAME (symbol);
6567
6568 switch (SREF (name, 0))
6569 {
6570 #define SINGLE_LETTER_MOD(BIT) \
6571 if (SBYTES (name) == 1) \
6572 return BIT;
6573
6574 #define MULTI_LETTER_MOD(BIT, NAME, LEN) \
6575 if (LEN == SBYTES (name) \
6576 && ! memcmp (SDATA (name), NAME, LEN)) \
6577 return BIT;
6578
6579 case 'A':
6580 SINGLE_LETTER_MOD (alt_modifier);
6581 break;
6582
6583 case 'a':
6584 MULTI_LETTER_MOD (alt_modifier, "alt", 3);
6585 break;
6586
6587 case 'C':
6588 SINGLE_LETTER_MOD (ctrl_modifier);
6589 break;
6590
6591 case 'c':
6592 MULTI_LETTER_MOD (ctrl_modifier, "ctrl", 4);
6593 MULTI_LETTER_MOD (ctrl_modifier, "control", 7);
6594 break;
6595
6596 case 'H':
6597 SINGLE_LETTER_MOD (hyper_modifier);
6598 break;
6599
6600 case 'h':
6601 MULTI_LETTER_MOD (hyper_modifier, "hyper", 5);
6602 break;
6603
6604 case 'M':
6605 SINGLE_LETTER_MOD (meta_modifier);
6606 break;
6607
6608 case 'm':
6609 MULTI_LETTER_MOD (meta_modifier, "meta", 4);
6610 break;
6611
6612 case 'S':
6613 SINGLE_LETTER_MOD (shift_modifier);
6614 break;
6615
6616 case 's':
6617 MULTI_LETTER_MOD (shift_modifier, "shift", 5);
6618 MULTI_LETTER_MOD (super_modifier, "super", 5);
6619 SINGLE_LETTER_MOD (super_modifier);
6620 break;
6621
6622 case 'd':
6623 MULTI_LETTER_MOD (drag_modifier, "drag", 4);
6624 MULTI_LETTER_MOD (down_modifier, "down", 4);
6625 MULTI_LETTER_MOD (double_modifier, "double", 6);
6626 break;
6627
6628 case 't':
6629 MULTI_LETTER_MOD (triple_modifier, "triple", 6);
6630 break;
6631
6632 case 'u':
6633 MULTI_LETTER_MOD (up_modifier, "up", 2);
6634 break;
6635
6636 #undef SINGLE_LETTER_MOD
6637 #undef MULTI_LETTER_MOD
6638 }
6639
6640 return 0;
6641 }
6642
6643 /* Return true if EVENT is a list whose elements are all integers or symbols.
6644 Such a list is not valid as an event,
6645 but it can be a Lucid-style event type list. */
6646
6647 bool
6648 lucid_event_type_list_p (Lisp_Object object)
6649 {
6650 Lisp_Object tail;
6651
6652 if (! CONSP (object))
6653 return 0;
6654
6655 if (EQ (XCAR (object), Qhelp_echo)
6656 || EQ (XCAR (object), Qvertical_line)
6657 || EQ (XCAR (object), Qmode_line)
6658 || EQ (XCAR (object), Qheader_line))
6659 return 0;
6660
6661 for (tail = object; CONSP (tail); tail = XCDR (tail))
6662 {
6663 Lisp_Object elt;
6664 elt = XCAR (tail);
6665 if (! (INTEGERP (elt) || SYMBOLP (elt)))
6666 return 0;
6667 }
6668
6669 return NILP (tail);
6670 }
6671 \f
6672 /* Return true if terminal input chars are available.
6673 Also, store the return value into INPUT_PENDING.
6674
6675 Serves the purpose of ioctl (0, FIONREAD, ...)
6676 but works even if FIONREAD does not exist.
6677 (In fact, this may actually read some input.)
6678
6679 If READABLE_EVENTS_DO_TIMERS_NOW is set in FLAGS, actually run
6680 timer events that are ripe.
6681 If READABLE_EVENTS_FILTER_EVENTS is set in FLAGS, ignore internal
6682 events (FOCUS_IN_EVENT).
6683 If READABLE_EVENTS_IGNORE_SQUEEZABLES is set in FLAGS, ignore mouse
6684 movements and toolkit scroll bar thumb drags. */
6685
6686 static bool
6687 get_input_pending (int flags)
6688 {
6689 /* First of all, have we already counted some input? */
6690 input_pending = (!NILP (Vquit_flag) || readable_events (flags));
6691
6692 /* If input is being read as it arrives, and we have none, there is none. */
6693 if (!input_pending && (!interrupt_input || interrupts_deferred))
6694 {
6695 /* Try to read some input and see how much we get. */
6696 gobble_input ();
6697 input_pending = (!NILP (Vquit_flag) || readable_events (flags));
6698 }
6699
6700 return input_pending;
6701 }
6702
6703 /* Put a BUFFER_SWITCH_EVENT in the buffer
6704 so that read_key_sequence will notice the new current buffer. */
6705
6706 void
6707 record_asynch_buffer_change (void)
6708 {
6709 /* We don't need a buffer-switch event unless Emacs is waiting for input.
6710 The purpose of the event is to make read_key_sequence look up the
6711 keymaps again. If we aren't in read_key_sequence, we don't need one,
6712 and the event could cause trouble by messing up (input-pending-p).
6713 Note: Fwaiting_for_user_input_p always returns nil when async
6714 subprocesses aren't supported. */
6715 if (!NILP (Fwaiting_for_user_input_p ()))
6716 {
6717 struct input_event event;
6718
6719 EVENT_INIT (event);
6720 event.kind = BUFFER_SWITCH_EVENT;
6721 event.frame_or_window = Qnil;
6722 event.arg = Qnil;
6723
6724 /* Make sure no interrupt happens while storing the event. */
6725 #ifdef USABLE_SIGIO
6726 if (interrupt_input)
6727 kbd_buffer_store_event (&event);
6728 else
6729 #endif
6730 {
6731 stop_polling ();
6732 kbd_buffer_store_event (&event);
6733 start_polling ();
6734 }
6735 }
6736 }
6737
6738 /* Read any terminal input already buffered up by the system
6739 into the kbd_buffer, but do not wait.
6740
6741 Return the number of keyboard chars read, or -1 meaning
6742 this is a bad time to try to read input. */
6743
6744 int
6745 gobble_input (void)
6746 {
6747 int nread = 0;
6748 bool err = false;
6749 struct terminal *t;
6750
6751 /* Store pending user signal events, if any. */
6752 store_user_signal_events ();
6753
6754 /* Loop through the available terminals, and call their input hooks. */
6755 t = terminal_list;
6756 while (t)
6757 {
6758 struct terminal *next = t->next_terminal;
6759
6760 if (t->read_socket_hook)
6761 {
6762 int nr;
6763 struct input_event hold_quit;
6764
6765 if (input_blocked_p ())
6766 {
6767 pending_signals = true;
6768 break;
6769 }
6770
6771 EVENT_INIT (hold_quit);
6772 hold_quit.kind = NO_EVENT;
6773
6774 /* No need for FIONREAD or fcntl; just say don't wait. */
6775 while ((nr = (*t->read_socket_hook) (t, &hold_quit)) > 0)
6776 nread += nr;
6777
6778 if (nr == -1) /* Not OK to read input now. */
6779 {
6780 err = true;
6781 }
6782 else if (nr == -2) /* Non-transient error. */
6783 {
6784 /* The terminal device terminated; it should be closed. */
6785
6786 /* Kill Emacs if this was our last terminal. */
6787 if (!terminal_list->next_terminal)
6788 /* Formerly simply reported no input, but that
6789 sometimes led to a failure of Emacs to terminate.
6790 SIGHUP seems appropriate if we can't reach the
6791 terminal. */
6792 /* ??? Is it really right to send the signal just to
6793 this process rather than to the whole process
6794 group? Perhaps on systems with FIONREAD Emacs is
6795 alone in its group. */
6796 terminate_due_to_signal (SIGHUP, 10);
6797
6798 /* XXX Is calling delete_terminal safe here? It calls delete_frame. */
6799 {
6800 Lisp_Object tmp;
6801 XSETTERMINAL (tmp, t);
6802 Fdelete_terminal (tmp, Qnoelisp);
6803 }
6804 }
6805
6806 /* If there was no error, make sure the pointer
6807 is visible for all frames on this terminal. */
6808 if (nr >= 0)
6809 {
6810 Lisp_Object tail, frame;
6811
6812 FOR_EACH_FRAME (tail, frame)
6813 {
6814 struct frame *f = XFRAME (frame);
6815 if (FRAME_TERMINAL (f) == t)
6816 frame_make_pointer_visible (f);
6817 }
6818 }
6819
6820 if (hold_quit.kind != NO_EVENT)
6821 kbd_buffer_store_event (&hold_quit);
6822 }
6823
6824 t = next;
6825 }
6826
6827 if (err && !nread)
6828 nread = -1;
6829
6830 return nread;
6831 }
6832
6833 /* This is the tty way of reading available input.
6834
6835 Note that each terminal device has its own `struct terminal' object,
6836 and so this function is called once for each individual termcap
6837 terminal. The first parameter indicates which terminal to read from. */
6838
6839 int
6840 tty_read_avail_input (struct terminal *terminal,
6841 struct input_event *hold_quit)
6842 {
6843 /* Using KBD_BUFFER_SIZE - 1 here avoids reading more than
6844 the kbd_buffer can really hold. That may prevent loss
6845 of characters on some systems when input is stuffed at us. */
6846 unsigned char cbuf[KBD_BUFFER_SIZE - 1];
6847 int n_to_read, i;
6848 struct tty_display_info *tty = terminal->display_info.tty;
6849 int nread = 0;
6850 #ifdef subprocesses
6851 int buffer_free = KBD_BUFFER_SIZE - kbd_buffer_nr_stored () - 1;
6852
6853 if (kbd_on_hold_p () || buffer_free <= 0)
6854 return 0;
6855 #endif /* subprocesses */
6856
6857 if (!terminal->name) /* Don't read from a dead terminal. */
6858 return 0;
6859
6860 if (terminal->type != output_termcap
6861 && terminal->type != output_msdos_raw)
6862 emacs_abort ();
6863
6864 /* XXX I think the following code should be moved to separate hook
6865 functions in system-dependent files. */
6866 #ifdef WINDOWSNT
6867 /* FIXME: AFAIK, tty_read_avail_input is not used under w32 since the non-GUI
6868 code sets read_socket_hook to w32_console_read_socket instead! */
6869 return 0;
6870 #else /* not WINDOWSNT */
6871 if (! tty->term_initted) /* In case we get called during bootstrap. */
6872 return 0;
6873
6874 if (! tty->input)
6875 return 0; /* The terminal is suspended. */
6876
6877 #ifdef MSDOS
6878 n_to_read = dos_keysns ();
6879 if (n_to_read == 0)
6880 return 0;
6881
6882 cbuf[0] = dos_keyread ();
6883 nread = 1;
6884
6885 #else /* not MSDOS */
6886 #ifdef HAVE_GPM
6887 if (gpm_tty == tty)
6888 {
6889 Gpm_Event event;
6890 struct input_event gpm_hold_quit;
6891 int gpm, fd = gpm_fd;
6892
6893 EVENT_INIT (gpm_hold_quit);
6894 gpm_hold_quit.kind = NO_EVENT;
6895
6896 /* gpm==1 if event received.
6897 gpm==0 if the GPM daemon has closed the connection, in which case
6898 Gpm_GetEvent closes gpm_fd and clears it to -1, which is why
6899 we save it in `fd' so close_gpm can remove it from the
6900 select masks.
6901 gpm==-1 if a protocol error or EWOULDBLOCK; the latter is normal. */
6902 while (gpm = Gpm_GetEvent (&event), gpm == 1) {
6903 nread += handle_one_term_event (tty, &event, &gpm_hold_quit);
6904 }
6905 if (gpm == 0)
6906 /* Presumably the GPM daemon has closed the connection. */
6907 close_gpm (fd);
6908 if (gpm_hold_quit.kind != NO_EVENT)
6909 kbd_buffer_store_event (&gpm_hold_quit);
6910 if (nread)
6911 return nread;
6912 }
6913 #endif /* HAVE_GPM */
6914
6915 /* Determine how many characters we should *try* to read. */
6916 #ifdef USABLE_FIONREAD
6917 /* Find out how much input is available. */
6918 if (ioctl (fileno (tty->input), FIONREAD, &n_to_read) < 0)
6919 {
6920 if (! noninteractive)
6921 return -2; /* Close this terminal. */
6922 else
6923 n_to_read = 0;
6924 }
6925 if (n_to_read == 0)
6926 return 0;
6927 if (n_to_read > sizeof cbuf)
6928 n_to_read = sizeof cbuf;
6929 #elif defined USG || defined CYGWIN
6930 /* Read some input if available, but don't wait. */
6931 n_to_read = sizeof cbuf;
6932 fcntl (fileno (tty->input), F_SETFL, O_NONBLOCK);
6933 #else
6934 # error "Cannot read without possibly delaying"
6935 #endif
6936
6937 #ifdef subprocesses
6938 /* Don't read more than we can store. */
6939 if (n_to_read > buffer_free)
6940 n_to_read = buffer_free;
6941 #endif /* subprocesses */
6942
6943 /* Now read; for one reason or another, this will not block.
6944 NREAD is set to the number of chars read. */
6945 do
6946 {
6947 nread = emacs_read (fileno (tty->input), (char *) cbuf, n_to_read);
6948 /* POSIX infers that processes which are not in the session leader's
6949 process group won't get SIGHUPs at logout time. BSDI adheres to
6950 this part standard and returns -1 from read (0) with errno==EIO
6951 when the control tty is taken away.
6952 Jeffrey Honig <jch@bsdi.com> says this is generally safe. */
6953 if (nread == -1 && errno == EIO)
6954 return -2; /* Close this terminal. */
6955 #if defined (AIX) && defined (_BSD)
6956 /* The kernel sometimes fails to deliver SIGHUP for ptys.
6957 This looks incorrect, but it isn't, because _BSD causes
6958 O_NDELAY to be defined in fcntl.h as O_NONBLOCK,
6959 and that causes a value other than 0 when there is no input. */
6960 if (nread == 0)
6961 return -2; /* Close this terminal. */
6962 #endif
6963 }
6964 while (
6965 /* We used to retry the read if it was interrupted.
6966 But this does the wrong thing when O_NONBLOCK causes
6967 an EAGAIN error. Does anybody know of a situation
6968 where a retry is actually needed? */
6969 #if 0
6970 nread < 0 && (errno == EAGAIN || errno == EFAULT
6971 #ifdef EBADSLT
6972 || errno == EBADSLT
6973 #endif
6974 )
6975 #else
6976 0
6977 #endif
6978 );
6979
6980 #ifndef USABLE_FIONREAD
6981 #if defined (USG) || defined (CYGWIN)
6982 fcntl (fileno (tty->input), F_SETFL, 0);
6983 #endif /* USG or CYGWIN */
6984 #endif /* no FIONREAD */
6985
6986 if (nread <= 0)
6987 return nread;
6988
6989 #endif /* not MSDOS */
6990 #endif /* not WINDOWSNT */
6991
6992 for (i = 0; i < nread; i++)
6993 {
6994 struct input_event buf;
6995 EVENT_INIT (buf);
6996 buf.kind = ASCII_KEYSTROKE_EVENT;
6997 buf.modifiers = 0;
6998 if (tty->meta_key == 1 && (cbuf[i] & 0x80))
6999 buf.modifiers = meta_modifier;
7000 if (tty->meta_key != 2)
7001 cbuf[i] &= ~0x80;
7002
7003 buf.code = cbuf[i];
7004 /* Set the frame corresponding to the active tty. Note that the
7005 value of selected_frame is not reliable here, redisplay tends
7006 to temporarily change it. */
7007 buf.frame_or_window = tty->top_frame;
7008 buf.arg = Qnil;
7009
7010 kbd_buffer_store_event (&buf);
7011 /* Don't look at input that follows a C-g too closely.
7012 This reduces lossage due to autorepeat on C-g. */
7013 if (buf.kind == ASCII_KEYSTROKE_EVENT
7014 && buf.code == quit_char)
7015 break;
7016 }
7017
7018 return nread;
7019 }
7020 \f
7021 static void
7022 handle_async_input (void)
7023 {
7024 #ifdef USABLE_SIGIO
7025 while (1)
7026 {
7027 int nread = gobble_input ();
7028 /* -1 means it's not ok to read the input now.
7029 UNBLOCK_INPUT will read it later; now, avoid infinite loop.
7030 0 means there was no keyboard input available. */
7031 if (nread <= 0)
7032 break;
7033 }
7034 #endif
7035 }
7036
7037 void
7038 process_pending_signals (void)
7039 {
7040 pending_signals = false;
7041 handle_async_input ();
7042 do_pending_atimers ();
7043 }
7044
7045 /* Undo any number of BLOCK_INPUT calls down to level LEVEL,
7046 and reinvoke any pending signal if the level is now 0 and
7047 a fatal error is not already in progress. */
7048
7049 void
7050 unblock_input_to (int level)
7051 {
7052 interrupt_input_blocked = level;
7053 if (level == 0)
7054 {
7055 if (pending_signals && !fatal_error_in_progress)
7056 process_pending_signals ();
7057 }
7058 else if (level < 0)
7059 emacs_abort ();
7060 }
7061
7062 /* End critical section.
7063
7064 If doing signal-driven input, and a signal came in when input was
7065 blocked, reinvoke the signal handler now to deal with it.
7066
7067 It will also process queued input, if it was not read before.
7068 When a longer code sequence does not use block/unblock input
7069 at all, the whole input gathered up to the next call to
7070 unblock_input will be processed inside that call. */
7071
7072 void
7073 unblock_input (void)
7074 {
7075 unblock_input_to (interrupt_input_blocked - 1);
7076 }
7077
7078 /* Undo any number of BLOCK_INPUT calls,
7079 and also reinvoke any pending signal. */
7080
7081 void
7082 totally_unblock_input (void)
7083 {
7084 unblock_input_to (0);
7085 }
7086
7087 #ifdef USABLE_SIGIO
7088
7089 void
7090 handle_input_available_signal (int sig)
7091 {
7092 pending_signals = true;
7093
7094 if (input_available_clear_time)
7095 *input_available_clear_time = make_timespec (0, 0);
7096 }
7097
7098 static void
7099 deliver_input_available_signal (int sig)
7100 {
7101 deliver_process_signal (sig, handle_input_available_signal);
7102 }
7103 #endif /* USABLE_SIGIO */
7104
7105 \f
7106 /* User signal events. */
7107
7108 struct user_signal_info
7109 {
7110 /* Signal number. */
7111 int sig;
7112
7113 /* Name of the signal. */
7114 char *name;
7115
7116 /* Number of pending signals. */
7117 int npending;
7118
7119 struct user_signal_info *next;
7120 };
7121
7122 /* List of user signals. */
7123 static struct user_signal_info *user_signals = NULL;
7124
7125 void
7126 add_user_signal (int sig, const char *name)
7127 {
7128 struct sigaction action;
7129 struct user_signal_info *p;
7130
7131 for (p = user_signals; p; p = p->next)
7132 if (p->sig == sig)
7133 /* Already added. */
7134 return;
7135
7136 p = xmalloc (sizeof *p);
7137 p->sig = sig;
7138 p->name = xstrdup (name);
7139 p->npending = 0;
7140 p->next = user_signals;
7141 user_signals = p;
7142
7143 emacs_sigaction_init (&action, deliver_user_signal);
7144 sigaction (sig, &action, 0);
7145 }
7146
7147 static void
7148 handle_user_signal (int sig)
7149 {
7150 struct user_signal_info *p;
7151 const char *special_event_name = NULL;
7152
7153 if (SYMBOLP (Vdebug_on_event))
7154 special_event_name = SSDATA (SYMBOL_NAME (Vdebug_on_event));
7155
7156 for (p = user_signals; p; p = p->next)
7157 if (p->sig == sig)
7158 {
7159 if (special_event_name
7160 && strcmp (special_event_name, p->name) == 0)
7161 {
7162 /* Enter the debugger in many ways. */
7163 debug_on_next_call = true;
7164 debug_on_quit = true;
7165 Vquit_flag = Qt;
7166 Vinhibit_quit = Qnil;
7167
7168 /* Eat the event. */
7169 break;
7170 }
7171
7172 p->npending++;
7173 #ifdef USABLE_SIGIO
7174 if (interrupt_input)
7175 handle_input_available_signal (sig);
7176 else
7177 #endif
7178 {
7179 /* Tell wait_reading_process_output that it needs to wake
7180 up and look around. */
7181 if (input_available_clear_time)
7182 *input_available_clear_time = make_timespec (0, 0);
7183 }
7184 break;
7185 }
7186 }
7187
7188 static void
7189 deliver_user_signal (int sig)
7190 {
7191 deliver_process_signal (sig, handle_user_signal);
7192 }
7193
7194 static char *
7195 find_user_signal_name (int sig)
7196 {
7197 struct user_signal_info *p;
7198
7199 for (p = user_signals; p; p = p->next)
7200 if (p->sig == sig)
7201 return p->name;
7202
7203 return NULL;
7204 }
7205
7206 static void
7207 store_user_signal_events (void)
7208 {
7209 struct user_signal_info *p;
7210 struct input_event buf;
7211 bool buf_initialized = false;
7212
7213 for (p = user_signals; p; p = p->next)
7214 if (p->npending > 0)
7215 {
7216 if (! buf_initialized)
7217 {
7218 memset (&buf, 0, sizeof buf);
7219 buf.kind = USER_SIGNAL_EVENT;
7220 buf.frame_or_window = selected_frame;
7221 buf_initialized = true;
7222 }
7223
7224 do
7225 {
7226 buf.code = p->sig;
7227 kbd_buffer_store_event (&buf);
7228 p->npending--;
7229 }
7230 while (p->npending > 0);
7231 }
7232 }
7233
7234 \f
7235 static void menu_bar_item (Lisp_Object, Lisp_Object, Lisp_Object, void *);
7236 static Lisp_Object menu_bar_one_keymap_changed_items;
7237
7238 /* These variables hold the vector under construction within
7239 menu_bar_items and its subroutines, and the current index
7240 for storing into that vector. */
7241 static Lisp_Object menu_bar_items_vector;
7242 static int menu_bar_items_index;
7243
7244
7245 static const char *separator_names[] = {
7246 "space",
7247 "no-line",
7248 "single-line",
7249 "double-line",
7250 "single-dashed-line",
7251 "double-dashed-line",
7252 "shadow-etched-in",
7253 "shadow-etched-out",
7254 "shadow-etched-in-dash",
7255 "shadow-etched-out-dash",
7256 "shadow-double-etched-in",
7257 "shadow-double-etched-out",
7258 "shadow-double-etched-in-dash",
7259 "shadow-double-etched-out-dash",
7260 0,
7261 };
7262
7263 /* Return true if LABEL specifies a separator. */
7264
7265 bool
7266 menu_separator_name_p (const char *label)
7267 {
7268 if (!label)
7269 return 0;
7270 else if (strlen (label) > 3
7271 && memcmp (label, "--", 2) == 0
7272 && label[2] != '-')
7273 {
7274 int i;
7275 label += 2;
7276 for (i = 0; separator_names[i]; ++i)
7277 if (strcmp (label, separator_names[i]) == 0)
7278 return 1;
7279 }
7280 else
7281 {
7282 /* It's a separator if it contains only dashes. */
7283 while (*label == '-')
7284 ++label;
7285 return (*label == 0);
7286 }
7287
7288 return 0;
7289 }
7290
7291
7292 /* Return a vector of menu items for a menu bar, appropriate
7293 to the current buffer. Each item has three elements in the vector:
7294 KEY STRING MAPLIST.
7295
7296 OLD is an old vector we can optionally reuse, or nil. */
7297
7298 Lisp_Object
7299 menu_bar_items (Lisp_Object old)
7300 {
7301 /* The number of keymaps we're scanning right now, and the number of
7302 keymaps we have allocated space for. */
7303 ptrdiff_t nmaps;
7304
7305 /* maps[0..nmaps-1] are the prefix definitions of KEYBUF[0..t-1]
7306 in the current keymaps, or nil where it is not a prefix. */
7307 Lisp_Object *maps;
7308
7309 Lisp_Object mapsbuf[3];
7310 Lisp_Object def, tail;
7311
7312 ptrdiff_t mapno;
7313 Lisp_Object oquit;
7314
7315 USE_SAFE_ALLOCA;
7316
7317 /* In order to build the menus, we need to call the keymap
7318 accessors. They all call QUIT. But this function is called
7319 during redisplay, during which a quit is fatal. So inhibit
7320 quitting while building the menus.
7321 We do this instead of specbind because (1) errors will clear it anyway
7322 and (2) this avoids risk of specpdl overflow. */
7323 oquit = Vinhibit_quit;
7324 Vinhibit_quit = Qt;
7325
7326 if (!NILP (old))
7327 menu_bar_items_vector = old;
7328 else
7329 menu_bar_items_vector = Fmake_vector (make_number (24), Qnil);
7330 menu_bar_items_index = 0;
7331
7332 /* Build our list of keymaps.
7333 If we recognize a function key and replace its escape sequence in
7334 keybuf with its symbol, or if the sequence starts with a mouse
7335 click and we need to switch buffers, we jump back here to rebuild
7336 the initial keymaps from the current buffer. */
7337 {
7338 Lisp_Object *tmaps;
7339
7340 /* Should overriding-terminal-local-map and overriding-local-map apply? */
7341 if (!NILP (Voverriding_local_map_menu_flag)
7342 && !NILP (Voverriding_local_map))
7343 {
7344 /* Yes, use them (if non-nil) as well as the global map. */
7345 maps = mapsbuf;
7346 nmaps = 0;
7347 if (!NILP (KVAR (current_kboard, Voverriding_terminal_local_map)))
7348 maps[nmaps++] = KVAR (current_kboard, Voverriding_terminal_local_map);
7349 if (!NILP (Voverriding_local_map))
7350 maps[nmaps++] = Voverriding_local_map;
7351 }
7352 else
7353 {
7354 /* No, so use major and minor mode keymaps and keymap property.
7355 Note that menu-bar bindings in the local-map and keymap
7356 properties may not work reliable, as they are only
7357 recognized when the menu-bar (or mode-line) is updated,
7358 which does not normally happen after every command. */
7359 ptrdiff_t nminor = current_minor_maps (NULL, &tmaps);
7360 SAFE_NALLOCA (maps, 1, nminor + 4);
7361 nmaps = 0;
7362 Lisp_Object tem = KVAR (current_kboard, Voverriding_terminal_local_map);
7363 if (!NILP (tem) && !NILP (Voverriding_local_map_menu_flag))
7364 maps[nmaps++] = tem;
7365 if (tem = get_local_map (PT, current_buffer, Qkeymap), !NILP (tem))
7366 maps[nmaps++] = tem;
7367 if (nminor != 0)
7368 {
7369 memcpy (maps + nmaps, tmaps, nminor * sizeof (maps[0]));
7370 nmaps += nminor;
7371 }
7372 maps[nmaps++] = get_local_map (PT, current_buffer, Qlocal_map);
7373 }
7374 maps[nmaps++] = current_global_map;
7375 }
7376
7377 /* Look up in each map the dummy prefix key `menu-bar'. */
7378
7379 for (mapno = nmaps - 1; mapno >= 0; mapno--)
7380 if (!NILP (maps[mapno]))
7381 {
7382 def = get_keymap (access_keymap (maps[mapno], Qmenu_bar, 1, 0, 1),
7383 0, 1);
7384 if (CONSP (def))
7385 {
7386 menu_bar_one_keymap_changed_items = Qnil;
7387 map_keymap_canonical (def, menu_bar_item, Qnil, NULL);
7388 }
7389 }
7390
7391 /* Move to the end those items that should be at the end. */
7392
7393 for (tail = Vmenu_bar_final_items; CONSP (tail); tail = XCDR (tail))
7394 {
7395 int i;
7396 int end = menu_bar_items_index;
7397
7398 for (i = 0; i < end; i += 4)
7399 if (EQ (XCAR (tail), AREF (menu_bar_items_vector, i)))
7400 {
7401 Lisp_Object tem0, tem1, tem2, tem3;
7402 /* Move the item at index I to the end,
7403 shifting all the others forward. */
7404 tem0 = AREF (menu_bar_items_vector, i + 0);
7405 tem1 = AREF (menu_bar_items_vector, i + 1);
7406 tem2 = AREF (menu_bar_items_vector, i + 2);
7407 tem3 = AREF (menu_bar_items_vector, i + 3);
7408 if (end > i + 4)
7409 memmove (aref_addr (menu_bar_items_vector, i),
7410 aref_addr (menu_bar_items_vector, i + 4),
7411 (end - i - 4) * word_size);
7412 ASET (menu_bar_items_vector, end - 4, tem0);
7413 ASET (menu_bar_items_vector, end - 3, tem1);
7414 ASET (menu_bar_items_vector, end - 2, tem2);
7415 ASET (menu_bar_items_vector, end - 1, tem3);
7416 break;
7417 }
7418 }
7419
7420 /* Add nil, nil, nil, nil at the end. */
7421 {
7422 int i = menu_bar_items_index;
7423 if (i + 4 > ASIZE (menu_bar_items_vector))
7424 menu_bar_items_vector
7425 = larger_vector (menu_bar_items_vector, 4, -1);
7426 /* Add this item. */
7427 ASET (menu_bar_items_vector, i, Qnil); i++;
7428 ASET (menu_bar_items_vector, i, Qnil); i++;
7429 ASET (menu_bar_items_vector, i, Qnil); i++;
7430 ASET (menu_bar_items_vector, i, Qnil); i++;
7431 menu_bar_items_index = i;
7432 }
7433
7434 Vinhibit_quit = oquit;
7435 SAFE_FREE ();
7436 return menu_bar_items_vector;
7437 }
7438 \f
7439 /* Add one item to menu_bar_items_vector, for KEY, ITEM_STRING and DEF.
7440 If there's already an item for KEY, add this DEF to it. */
7441
7442 Lisp_Object item_properties;
7443
7444 static void
7445 menu_bar_item (Lisp_Object key, Lisp_Object item, Lisp_Object dummy1, void *dummy2)
7446 {
7447 int i;
7448 bool parsed;
7449 Lisp_Object tem;
7450
7451 if (EQ (item, Qundefined))
7452 {
7453 /* If a map has an explicit `undefined' as definition,
7454 discard any previously made menu bar item. */
7455
7456 for (i = 0; i < menu_bar_items_index; i += 4)
7457 if (EQ (key, AREF (menu_bar_items_vector, i)))
7458 {
7459 if (menu_bar_items_index > i + 4)
7460 memmove (aref_addr (menu_bar_items_vector, i),
7461 aref_addr (menu_bar_items_vector, i + 4),
7462 (menu_bar_items_index - i - 4) * word_size);
7463 menu_bar_items_index -= 4;
7464 }
7465 }
7466
7467 /* If this keymap has already contributed to this KEY,
7468 don't contribute to it a second time. */
7469 tem = Fmemq (key, menu_bar_one_keymap_changed_items);
7470 if (!NILP (tem) || NILP (item))
7471 return;
7472
7473 menu_bar_one_keymap_changed_items
7474 = Fcons (key, menu_bar_one_keymap_changed_items);
7475
7476 /* We add to menu_bar_one_keymap_changed_items before doing the
7477 parse_menu_item, so that if it turns out it wasn't a menu item,
7478 it still correctly hides any further menu item. */
7479 parsed = parse_menu_item (item, 1);
7480 if (!parsed)
7481 return;
7482
7483 item = AREF (item_properties, ITEM_PROPERTY_DEF);
7484
7485 /* Find any existing item for this KEY. */
7486 for (i = 0; i < menu_bar_items_index; i += 4)
7487 if (EQ (key, AREF (menu_bar_items_vector, i)))
7488 break;
7489
7490 /* If we did not find this KEY, add it at the end. */
7491 if (i == menu_bar_items_index)
7492 {
7493 /* If vector is too small, get a bigger one. */
7494 if (i + 4 > ASIZE (menu_bar_items_vector))
7495 menu_bar_items_vector = larger_vector (menu_bar_items_vector, 4, -1);
7496 /* Add this item. */
7497 ASET (menu_bar_items_vector, i, key); i++;
7498 ASET (menu_bar_items_vector, i,
7499 AREF (item_properties, ITEM_PROPERTY_NAME)); i++;
7500 ASET (menu_bar_items_vector, i, list1 (item)); i++;
7501 ASET (menu_bar_items_vector, i, make_number (0)); i++;
7502 menu_bar_items_index = i;
7503 }
7504 /* We did find an item for this KEY. Add ITEM to its list of maps. */
7505 else
7506 {
7507 Lisp_Object old;
7508 old = AREF (menu_bar_items_vector, i + 2);
7509 /* If the new and the old items are not both keymaps,
7510 the lookup will only find `item'. */
7511 item = Fcons (item, KEYMAPP (item) && KEYMAPP (XCAR (old)) ? old : Qnil);
7512 ASET (menu_bar_items_vector, i + 2, item);
7513 }
7514 }
7515 \f
7516 /* This is used as the handler when calling menu_item_eval_property. */
7517 static Lisp_Object
7518 menu_item_eval_property_1 (Lisp_Object arg)
7519 {
7520 /* If we got a quit from within the menu computation,
7521 quit all the way out of it. This takes care of C-] in the debugger. */
7522 if (CONSP (arg) && EQ (XCAR (arg), Qquit))
7523 Fsignal (Qquit, Qnil);
7524
7525 return Qnil;
7526 }
7527
7528 static Lisp_Object
7529 eval_dyn (Lisp_Object form)
7530 {
7531 return Feval (form, Qnil);
7532 }
7533
7534 /* Evaluate an expression and return the result (or nil if something
7535 went wrong). Used to evaluate dynamic parts of menu items. */
7536 Lisp_Object
7537 menu_item_eval_property (Lisp_Object sexpr)
7538 {
7539 ptrdiff_t count = SPECPDL_INDEX ();
7540 Lisp_Object val;
7541 specbind (Qinhibit_redisplay, Qt);
7542 val = internal_condition_case_1 (eval_dyn, sexpr, Qerror,
7543 menu_item_eval_property_1);
7544 return unbind_to (count, val);
7545 }
7546
7547 /* This function parses a menu item and leaves the result in the
7548 vector item_properties.
7549 ITEM is a key binding, a possible menu item.
7550 INMENUBAR is > 0 when this is considered for an entry in a menu bar
7551 top level.
7552 INMENUBAR is < 0 when this is considered for an entry in a keyboard menu.
7553 parse_menu_item returns true if the item is a menu item and false
7554 otherwise. */
7555
7556 bool
7557 parse_menu_item (Lisp_Object item, int inmenubar)
7558 {
7559 Lisp_Object def, tem, item_string, start;
7560 Lisp_Object filter;
7561 Lisp_Object keyhint;
7562 int i;
7563
7564 filter = Qnil;
7565 keyhint = Qnil;
7566
7567 if (!CONSP (item))
7568 return 0;
7569
7570 /* Create item_properties vector if necessary. */
7571 if (NILP (item_properties))
7572 item_properties
7573 = Fmake_vector (make_number (ITEM_PROPERTY_ENABLE + 1), Qnil);
7574
7575 /* Initialize optional entries. */
7576 for (i = ITEM_PROPERTY_DEF; i < ITEM_PROPERTY_ENABLE; i++)
7577 ASET (item_properties, i, Qnil);
7578 ASET (item_properties, ITEM_PROPERTY_ENABLE, Qt);
7579
7580 /* Save the item here to protect it from GC. */
7581 ASET (item_properties, ITEM_PROPERTY_ITEM, item);
7582
7583 item_string = XCAR (item);
7584
7585 start = item;
7586 item = XCDR (item);
7587 if (STRINGP (item_string))
7588 {
7589 /* Old format menu item. */
7590 ASET (item_properties, ITEM_PROPERTY_NAME, item_string);
7591
7592 /* Maybe help string. */
7593 if (CONSP (item) && STRINGP (XCAR (item)))
7594 {
7595 ASET (item_properties, ITEM_PROPERTY_HELP,
7596 Fsubstitute_command_keys (XCAR (item)));
7597 start = item;
7598 item = XCDR (item);
7599 }
7600
7601 /* Maybe an obsolete key binding cache. */
7602 if (CONSP (item) && CONSP (XCAR (item))
7603 && (NILP (XCAR (XCAR (item)))
7604 || VECTORP (XCAR (XCAR (item)))))
7605 item = XCDR (item);
7606
7607 /* This is the real definition--the function to run. */
7608 ASET (item_properties, ITEM_PROPERTY_DEF, item);
7609
7610 /* Get enable property, if any. */
7611 if (SYMBOLP (item))
7612 {
7613 tem = Fget (item, Qmenu_enable);
7614 if (!NILP (Venable_disabled_menus_and_buttons))
7615 ASET (item_properties, ITEM_PROPERTY_ENABLE, Qt);
7616 else if (!NILP (tem))
7617 ASET (item_properties, ITEM_PROPERTY_ENABLE, tem);
7618 }
7619 }
7620 else if (EQ (item_string, Qmenu_item) && CONSP (item))
7621 {
7622 /* New format menu item. */
7623 ASET (item_properties, ITEM_PROPERTY_NAME, XCAR (item));
7624 start = XCDR (item);
7625 if (CONSP (start))
7626 {
7627 /* We have a real binding. */
7628 ASET (item_properties, ITEM_PROPERTY_DEF, XCAR (start));
7629
7630 item = XCDR (start);
7631 /* Is there an obsolete cache list with key equivalences. */
7632 if (CONSP (item) && CONSP (XCAR (item)))
7633 item = XCDR (item);
7634
7635 /* Parse properties. */
7636 while (CONSP (item) && CONSP (XCDR (item)))
7637 {
7638 tem = XCAR (item);
7639 item = XCDR (item);
7640
7641 if (EQ (tem, QCenable))
7642 {
7643 if (!NILP (Venable_disabled_menus_and_buttons))
7644 ASET (item_properties, ITEM_PROPERTY_ENABLE, Qt);
7645 else
7646 ASET (item_properties, ITEM_PROPERTY_ENABLE, XCAR (item));
7647 }
7648 else if (EQ (tem, QCvisible))
7649 {
7650 /* If got a visible property and that evaluates to nil
7651 then ignore this item. */
7652 tem = menu_item_eval_property (XCAR (item));
7653 if (NILP (tem))
7654 return 0;
7655 }
7656 else if (EQ (tem, QChelp))
7657 {
7658 Lisp_Object help = XCAR (item);
7659 if (STRINGP (help))
7660 help = Fsubstitute_command_keys (help);
7661 ASET (item_properties, ITEM_PROPERTY_HELP, help);
7662 }
7663 else if (EQ (tem, QCfilter))
7664 filter = item;
7665 else if (EQ (tem, QCkey_sequence))
7666 {
7667 tem = XCAR (item);
7668 if (SYMBOLP (tem) || STRINGP (tem) || VECTORP (tem))
7669 /* Be GC protected. Set keyhint to item instead of tem. */
7670 keyhint = item;
7671 }
7672 else if (EQ (tem, QCkeys))
7673 {
7674 tem = XCAR (item);
7675 if (CONSP (tem) || STRINGP (tem))
7676 ASET (item_properties, ITEM_PROPERTY_KEYEQ, tem);
7677 }
7678 else if (EQ (tem, QCbutton) && CONSP (XCAR (item)))
7679 {
7680 Lisp_Object type;
7681 tem = XCAR (item);
7682 type = XCAR (tem);
7683 if (EQ (type, QCtoggle) || EQ (type, QCradio))
7684 {
7685 ASET (item_properties, ITEM_PROPERTY_SELECTED,
7686 XCDR (tem));
7687 ASET (item_properties, ITEM_PROPERTY_TYPE, type);
7688 }
7689 }
7690 item = XCDR (item);
7691 }
7692 }
7693 else if (inmenubar || !NILP (start))
7694 return 0;
7695 }
7696 else
7697 return 0; /* not a menu item */
7698
7699 /* If item string is not a string, evaluate it to get string.
7700 If we don't get a string, skip this item. */
7701 item_string = AREF (item_properties, ITEM_PROPERTY_NAME);
7702 if (!(STRINGP (item_string)))
7703 {
7704 item_string = menu_item_eval_property (item_string);
7705 if (!STRINGP (item_string))
7706 return 0;
7707 ASET (item_properties, ITEM_PROPERTY_NAME, item_string);
7708 }
7709
7710 /* If got a filter apply it on definition. */
7711 def = AREF (item_properties, ITEM_PROPERTY_DEF);
7712 if (!NILP (filter))
7713 {
7714 def = menu_item_eval_property (list2 (XCAR (filter),
7715 list2 (Qquote, def)));
7716
7717 ASET (item_properties, ITEM_PROPERTY_DEF, def);
7718 }
7719
7720 /* Enable or disable selection of item. */
7721 tem = AREF (item_properties, ITEM_PROPERTY_ENABLE);
7722 if (!EQ (tem, Qt))
7723 {
7724 tem = menu_item_eval_property (tem);
7725 if (inmenubar && NILP (tem))
7726 return 0; /* Ignore disabled items in menu bar. */
7727 ASET (item_properties, ITEM_PROPERTY_ENABLE, tem);
7728 }
7729
7730 /* If we got no definition, this item is just unselectable text which
7731 is OK in a submenu but not in the menubar. */
7732 if (NILP (def))
7733 return (!inmenubar);
7734
7735 /* See if this is a separate pane or a submenu. */
7736 def = AREF (item_properties, ITEM_PROPERTY_DEF);
7737 tem = get_keymap (def, 0, 1);
7738 /* For a subkeymap, just record its details and exit. */
7739 if (CONSP (tem))
7740 {
7741 ASET (item_properties, ITEM_PROPERTY_MAP, tem);
7742 ASET (item_properties, ITEM_PROPERTY_DEF, tem);
7743 return 1;
7744 }
7745
7746 /* At the top level in the menu bar, do likewise for commands also.
7747 The menu bar does not display equivalent key bindings anyway.
7748 ITEM_PROPERTY_DEF is already set up properly. */
7749 if (inmenubar > 0)
7750 return 1;
7751
7752 { /* This is a command. See if there is an equivalent key binding. */
7753 Lisp_Object keyeq = AREF (item_properties, ITEM_PROPERTY_KEYEQ);
7754 AUTO_STRING (space_space, " ");
7755
7756 /* The previous code preferred :key-sequence to :keys, so we
7757 preserve this behavior. */
7758 if (STRINGP (keyeq) && !CONSP (keyhint))
7759 keyeq = concat2 (space_space, Fsubstitute_command_keys (keyeq));
7760 else
7761 {
7762 Lisp_Object prefix = keyeq;
7763 Lisp_Object keys = Qnil;
7764
7765 if (CONSP (prefix))
7766 {
7767 def = XCAR (prefix);
7768 prefix = XCDR (prefix);
7769 }
7770 else
7771 def = AREF (item_properties, ITEM_PROPERTY_DEF);
7772
7773 if (CONSP (keyhint) && !NILP (XCAR (keyhint)))
7774 {
7775 keys = XCAR (keyhint);
7776 tem = Fkey_binding (keys, Qnil, Qnil, Qnil);
7777
7778 /* We have a suggested key. Is it bound to the command? */
7779 if (NILP (tem)
7780 || (!EQ (tem, def)
7781 /* If the command is an alias for another
7782 (such as lmenu.el set it up), check if the
7783 original command matches the cached command. */
7784 && !(SYMBOLP (def)
7785 && EQ (tem, XSYMBOL (def)->function))))
7786 keys = Qnil;
7787 }
7788
7789 if (NILP (keys))
7790 keys = Fwhere_is_internal (def, Qnil, Qt, Qnil, Qnil);
7791
7792 if (!NILP (keys))
7793 {
7794 tem = Fkey_description (keys, Qnil);
7795 if (CONSP (prefix))
7796 {
7797 if (STRINGP (XCAR (prefix)))
7798 tem = concat2 (XCAR (prefix), tem);
7799 if (STRINGP (XCDR (prefix)))
7800 tem = concat2 (tem, XCDR (prefix));
7801 }
7802 keyeq = concat2 (space_space, tem);
7803 }
7804 else
7805 keyeq = Qnil;
7806 }
7807
7808 /* If we have an equivalent key binding, use that. */
7809 ASET (item_properties, ITEM_PROPERTY_KEYEQ, keyeq);
7810 }
7811
7812 /* Include this when menu help is implemented.
7813 tem = XVECTOR (item_properties)->contents[ITEM_PROPERTY_HELP];
7814 if (!(NILP (tem) || STRINGP (tem)))
7815 {
7816 tem = menu_item_eval_property (tem);
7817 if (!STRINGP (tem))
7818 tem = Qnil;
7819 XVECTOR (item_properties)->contents[ITEM_PROPERTY_HELP] = tem;
7820 }
7821 */
7822
7823 /* Handle radio buttons or toggle boxes. */
7824 tem = AREF (item_properties, ITEM_PROPERTY_SELECTED);
7825 if (!NILP (tem))
7826 ASET (item_properties, ITEM_PROPERTY_SELECTED,
7827 menu_item_eval_property (tem));
7828
7829 return 1;
7830 }
7831
7832
7833 \f
7834 /***********************************************************************
7835 Tool-bars
7836 ***********************************************************************/
7837
7838 /* A vector holding tool bar items while they are parsed in function
7839 tool_bar_items. Each item occupies TOOL_BAR_ITEM_NSCLOTS elements
7840 in the vector. */
7841
7842 static Lisp_Object tool_bar_items_vector;
7843
7844 /* A vector holding the result of parse_tool_bar_item. Layout is like
7845 the one for a single item in tool_bar_items_vector. */
7846
7847 static Lisp_Object tool_bar_item_properties;
7848
7849 /* Next free index in tool_bar_items_vector. */
7850
7851 static int ntool_bar_items;
7852
7853 /* Function prototypes. */
7854
7855 static void init_tool_bar_items (Lisp_Object);
7856 static void process_tool_bar_item (Lisp_Object, Lisp_Object, Lisp_Object,
7857 void *);
7858 static bool parse_tool_bar_item (Lisp_Object, Lisp_Object);
7859 static void append_tool_bar_item (void);
7860
7861
7862 /* Return a vector of tool bar items for keymaps currently in effect.
7863 Reuse vector REUSE if non-nil. Return in *NITEMS the number of
7864 tool bar items found. */
7865
7866 Lisp_Object
7867 tool_bar_items (Lisp_Object reuse, int *nitems)
7868 {
7869 Lisp_Object *maps;
7870 Lisp_Object mapsbuf[3];
7871 ptrdiff_t nmaps, i;
7872 Lisp_Object oquit;
7873 Lisp_Object *tmaps;
7874 USE_SAFE_ALLOCA;
7875
7876 *nitems = 0;
7877
7878 /* In order to build the menus, we need to call the keymap
7879 accessors. They all call QUIT. But this function is called
7880 during redisplay, during which a quit is fatal. So inhibit
7881 quitting while building the menus. We do this instead of
7882 specbind because (1) errors will clear it anyway and (2) this
7883 avoids risk of specpdl overflow. */
7884 oquit = Vinhibit_quit;
7885 Vinhibit_quit = Qt;
7886
7887 /* Initialize tool_bar_items_vector and protect it from GC. */
7888 init_tool_bar_items (reuse);
7889
7890 /* Build list of keymaps in maps. Set nmaps to the number of maps
7891 to process. */
7892
7893 /* Should overriding-terminal-local-map and overriding-local-map apply? */
7894 if (!NILP (Voverriding_local_map_menu_flag)
7895 && !NILP (Voverriding_local_map))
7896 {
7897 /* Yes, use them (if non-nil) as well as the global map. */
7898 maps = mapsbuf;
7899 nmaps = 0;
7900 if (!NILP (KVAR (current_kboard, Voverriding_terminal_local_map)))
7901 maps[nmaps++] = KVAR (current_kboard, Voverriding_terminal_local_map);
7902 if (!NILP (Voverriding_local_map))
7903 maps[nmaps++] = Voverriding_local_map;
7904 }
7905 else
7906 {
7907 /* No, so use major and minor mode keymaps and keymap property.
7908 Note that tool-bar bindings in the local-map and keymap
7909 properties may not work reliable, as they are only
7910 recognized when the tool-bar (or mode-line) is updated,
7911 which does not normally happen after every command. */
7912 ptrdiff_t nminor = current_minor_maps (NULL, &tmaps);
7913 SAFE_NALLOCA (maps, 1, nminor + 4);
7914 nmaps = 0;
7915 Lisp_Object tem = KVAR (current_kboard, Voverriding_terminal_local_map);
7916 if (!NILP (tem) && !NILP (Voverriding_local_map_menu_flag))
7917 maps[nmaps++] = tem;
7918 if (tem = get_local_map (PT, current_buffer, Qkeymap), !NILP (tem))
7919 maps[nmaps++] = tem;
7920 if (nminor != 0)
7921 {
7922 memcpy (maps + nmaps, tmaps, nminor * sizeof (maps[0]));
7923 nmaps += nminor;
7924 }
7925 maps[nmaps++] = get_local_map (PT, current_buffer, Qlocal_map);
7926 }
7927
7928 /* Add global keymap at the end. */
7929 maps[nmaps++] = current_global_map;
7930
7931 /* Process maps in reverse order and look up in each map the prefix
7932 key `tool-bar'. */
7933 for (i = nmaps - 1; i >= 0; --i)
7934 if (!NILP (maps[i]))
7935 {
7936 Lisp_Object keymap;
7937
7938 keymap = get_keymap (access_keymap (maps[i], Qtool_bar, 1, 0, 1), 0, 1);
7939 if (CONSP (keymap))
7940 map_keymap (keymap, process_tool_bar_item, Qnil, NULL, 1);
7941 }
7942
7943 Vinhibit_quit = oquit;
7944 *nitems = ntool_bar_items / TOOL_BAR_ITEM_NSLOTS;
7945 SAFE_FREE ();
7946 return tool_bar_items_vector;
7947 }
7948
7949
7950 /* Process the definition of KEY which is DEF. */
7951
7952 static void
7953 process_tool_bar_item (Lisp_Object key, Lisp_Object def, Lisp_Object data, void *args)
7954 {
7955 int i;
7956
7957 if (EQ (def, Qundefined))
7958 {
7959 /* If a map has an explicit `undefined' as definition,
7960 discard any previously made item. */
7961 for (i = 0; i < ntool_bar_items; i += TOOL_BAR_ITEM_NSLOTS)
7962 {
7963 Lisp_Object *v = XVECTOR (tool_bar_items_vector)->contents + i;
7964
7965 if (EQ (key, v[TOOL_BAR_ITEM_KEY]))
7966 {
7967 if (ntool_bar_items > i + TOOL_BAR_ITEM_NSLOTS)
7968 memmove (v, v + TOOL_BAR_ITEM_NSLOTS,
7969 ((ntool_bar_items - i - TOOL_BAR_ITEM_NSLOTS)
7970 * word_size));
7971 ntool_bar_items -= TOOL_BAR_ITEM_NSLOTS;
7972 break;
7973 }
7974 }
7975 }
7976 else if (parse_tool_bar_item (key, def))
7977 /* Append a new tool bar item to tool_bar_items_vector. Accept
7978 more than one definition for the same key. */
7979 append_tool_bar_item ();
7980 }
7981
7982 /* Access slot with index IDX of vector tool_bar_item_properties. */
7983 #define PROP(IDX) AREF (tool_bar_item_properties, (IDX))
7984 static void
7985 set_prop (ptrdiff_t idx, Lisp_Object val)
7986 {
7987 ASET (tool_bar_item_properties, idx, val);
7988 }
7989
7990
7991 /* Parse a tool bar item specification ITEM for key KEY and return the
7992 result in tool_bar_item_properties. Value is false if ITEM is
7993 invalid.
7994
7995 ITEM is a list `(menu-item CAPTION BINDING PROPS...)'.
7996
7997 CAPTION is the caption of the item, If it's not a string, it is
7998 evaluated to get a string.
7999
8000 BINDING is the tool bar item's binding. Tool-bar items with keymaps
8001 as binding are currently ignored.
8002
8003 The following properties are recognized:
8004
8005 - `:enable FORM'.
8006
8007 FORM is evaluated and specifies whether the tool bar item is
8008 enabled or disabled.
8009
8010 - `:visible FORM'
8011
8012 FORM is evaluated and specifies whether the tool bar item is visible.
8013
8014 - `:filter FUNCTION'
8015
8016 FUNCTION is invoked with one parameter `(quote BINDING)'. Its
8017 result is stored as the new binding.
8018
8019 - `:button (TYPE SELECTED)'
8020
8021 TYPE must be one of `:radio' or `:toggle'. SELECTED is evaluated
8022 and specifies whether the button is selected (pressed) or not.
8023
8024 - `:image IMAGES'
8025
8026 IMAGES is either a single image specification or a vector of four
8027 image specifications. See enum tool_bar_item_images.
8028
8029 - `:help HELP-STRING'.
8030
8031 Gives a help string to display for the tool bar item.
8032
8033 - `:label LABEL-STRING'.
8034
8035 A text label to show with the tool bar button if labels are enabled. */
8036
8037 static bool
8038 parse_tool_bar_item (Lisp_Object key, Lisp_Object item)
8039 {
8040 Lisp_Object filter = Qnil;
8041 Lisp_Object caption;
8042 int i;
8043 bool have_label = false;
8044
8045 /* Definition looks like `(menu-item CAPTION BINDING PROPS...)'.
8046 Rule out items that aren't lists, don't start with
8047 `menu-item' or whose rest following `tool-bar-item' is not a
8048 list. */
8049 if (!CONSP (item))
8050 return 0;
8051
8052 /* As an exception, allow old-style menu separators. */
8053 if (STRINGP (XCAR (item)))
8054 item = list1 (XCAR (item));
8055 else if (!EQ (XCAR (item), Qmenu_item)
8056 || (item = XCDR (item), !CONSP (item)))
8057 return 0;
8058
8059 /* Create tool_bar_item_properties vector if necessary. Reset it to
8060 defaults. */
8061 if (VECTORP (tool_bar_item_properties))
8062 {
8063 for (i = 0; i < TOOL_BAR_ITEM_NSLOTS; ++i)
8064 set_prop (i, Qnil);
8065 }
8066 else
8067 tool_bar_item_properties
8068 = Fmake_vector (make_number (TOOL_BAR_ITEM_NSLOTS), Qnil);
8069
8070 /* Set defaults. */
8071 set_prop (TOOL_BAR_ITEM_KEY, key);
8072 set_prop (TOOL_BAR_ITEM_ENABLED_P, Qt);
8073
8074 /* Get the caption of the item. If the caption is not a string,
8075 evaluate it to get a string. If we don't get a string, skip this
8076 item. */
8077 caption = XCAR (item);
8078 if (!STRINGP (caption))
8079 {
8080 caption = menu_item_eval_property (caption);
8081 if (!STRINGP (caption))
8082 return 0;
8083 }
8084 set_prop (TOOL_BAR_ITEM_CAPTION, caption);
8085
8086 /* If the rest following the caption is not a list, the menu item is
8087 either a separator, or invalid. */
8088 item = XCDR (item);
8089 if (!CONSP (item))
8090 {
8091 if (menu_separator_name_p (SSDATA (caption)))
8092 {
8093 set_prop (TOOL_BAR_ITEM_TYPE, Qt);
8094 #if !defined (USE_GTK) && !defined (HAVE_NS)
8095 /* If we use build_desired_tool_bar_string to render the
8096 tool bar, the separator is rendered as an image. */
8097 set_prop (TOOL_BAR_ITEM_IMAGES,
8098 (menu_item_eval_property
8099 (Vtool_bar_separator_image_expression)));
8100 set_prop (TOOL_BAR_ITEM_ENABLED_P, Qnil);
8101 set_prop (TOOL_BAR_ITEM_SELECTED_P, Qnil);
8102 set_prop (TOOL_BAR_ITEM_CAPTION, Qnil);
8103 #endif
8104 return 1;
8105 }
8106 return 0;
8107 }
8108
8109 /* Store the binding. */
8110 set_prop (TOOL_BAR_ITEM_BINDING, XCAR (item));
8111 item = XCDR (item);
8112
8113 /* Ignore cached key binding, if any. */
8114 if (CONSP (item) && CONSP (XCAR (item)))
8115 item = XCDR (item);
8116
8117 /* Process the rest of the properties. */
8118 for (; CONSP (item) && CONSP (XCDR (item)); item = XCDR (XCDR (item)))
8119 {
8120 Lisp_Object ikey, value;
8121
8122 ikey = XCAR (item);
8123 value = XCAR (XCDR (item));
8124
8125 if (EQ (ikey, QCenable))
8126 {
8127 /* `:enable FORM'. */
8128 if (!NILP (Venable_disabled_menus_and_buttons))
8129 set_prop (TOOL_BAR_ITEM_ENABLED_P, Qt);
8130 else
8131 set_prop (TOOL_BAR_ITEM_ENABLED_P, value);
8132 }
8133 else if (EQ (ikey, QCvisible))
8134 {
8135 /* `:visible FORM'. If got a visible property and that
8136 evaluates to nil then ignore this item. */
8137 if (NILP (menu_item_eval_property (value)))
8138 return 0;
8139 }
8140 else if (EQ (ikey, QChelp))
8141 /* `:help HELP-STRING'. */
8142 set_prop (TOOL_BAR_ITEM_HELP, value);
8143 else if (EQ (ikey, QCvert_only))
8144 /* `:vert-only t/nil'. */
8145 set_prop (TOOL_BAR_ITEM_VERT_ONLY, value);
8146 else if (EQ (ikey, QClabel))
8147 {
8148 const char *bad_label = "!!?GARBLED ITEM?!!";
8149 /* `:label LABEL-STRING'. */
8150 set_prop (TOOL_BAR_ITEM_LABEL,
8151 STRINGP (value) ? value : build_string (bad_label));
8152 have_label = true;
8153 }
8154 else if (EQ (ikey, QCfilter))
8155 /* ':filter FORM'. */
8156 filter = value;
8157 else if (EQ (ikey, QCbutton) && CONSP (value))
8158 {
8159 /* `:button (TYPE . SELECTED)'. */
8160 Lisp_Object type, selected;
8161
8162 type = XCAR (value);
8163 selected = XCDR (value);
8164 if (EQ (type, QCtoggle) || EQ (type, QCradio))
8165 {
8166 set_prop (TOOL_BAR_ITEM_SELECTED_P, selected);
8167 set_prop (TOOL_BAR_ITEM_TYPE, type);
8168 }
8169 }
8170 else if (EQ (ikey, QCimage)
8171 && (CONSP (value)
8172 || (VECTORP (value) && ASIZE (value) == 4)))
8173 /* Value is either a single image specification or a vector
8174 of 4 such specifications for the different button states. */
8175 set_prop (TOOL_BAR_ITEM_IMAGES, value);
8176 else if (EQ (ikey, QCrtl))
8177 /* ':rtl STRING' */
8178 set_prop (TOOL_BAR_ITEM_RTL_IMAGE, value);
8179 }
8180
8181
8182 if (!have_label)
8183 {
8184 /* Try to make one from caption and key. */
8185 Lisp_Object tkey = PROP (TOOL_BAR_ITEM_KEY);
8186 Lisp_Object tcapt = PROP (TOOL_BAR_ITEM_CAPTION);
8187 const char *label = SYMBOLP (tkey) ? SSDATA (SYMBOL_NAME (tkey)) : "";
8188 const char *capt = STRINGP (tcapt) ? SSDATA (tcapt) : "";
8189 ptrdiff_t max_lbl =
8190 2 * max (0, min (tool_bar_max_label_size, STRING_BYTES_BOUND / 2));
8191 char *buf = xmalloc (max_lbl + 1);
8192 Lisp_Object new_lbl;
8193 ptrdiff_t caption_len = strlen (capt);
8194
8195 if (caption_len <= max_lbl && capt[0] != '\0')
8196 {
8197 strcpy (buf, capt);
8198 while (caption_len > 0 && buf[caption_len - 1] == '.')
8199 caption_len--;
8200 buf[caption_len] = '\0';
8201 label = capt = buf;
8202 }
8203
8204 if (strlen (label) <= max_lbl && label[0] != '\0')
8205 {
8206 ptrdiff_t j;
8207 if (label != buf)
8208 strcpy (buf, label);
8209
8210 for (j = 0; buf[j] != '\0'; ++j)
8211 if (buf[j] == '-')
8212 buf[j] = ' ';
8213 label = buf;
8214 }
8215 else
8216 label = "";
8217
8218 new_lbl = Fupcase_initials (build_string (label));
8219 if (SCHARS (new_lbl) <= tool_bar_max_label_size)
8220 set_prop (TOOL_BAR_ITEM_LABEL, new_lbl);
8221 else
8222 set_prop (TOOL_BAR_ITEM_LABEL, empty_unibyte_string);
8223 xfree (buf);
8224 }
8225
8226 /* If got a filter apply it on binding. */
8227 if (!NILP (filter))
8228 set_prop (TOOL_BAR_ITEM_BINDING,
8229 (menu_item_eval_property
8230 (list2 (filter,
8231 list2 (Qquote,
8232 PROP (TOOL_BAR_ITEM_BINDING))))));
8233
8234 /* See if the binding is a keymap. Give up if it is. */
8235 if (CONSP (get_keymap (PROP (TOOL_BAR_ITEM_BINDING), 0, 1)))
8236 return 0;
8237
8238 /* Enable or disable selection of item. */
8239 if (!EQ (PROP (TOOL_BAR_ITEM_ENABLED_P), Qt))
8240 set_prop (TOOL_BAR_ITEM_ENABLED_P,
8241 menu_item_eval_property (PROP (TOOL_BAR_ITEM_ENABLED_P)));
8242
8243 /* Handle radio buttons or toggle boxes. */
8244 if (!NILP (PROP (TOOL_BAR_ITEM_SELECTED_P)))
8245 set_prop (TOOL_BAR_ITEM_SELECTED_P,
8246 menu_item_eval_property (PROP (TOOL_BAR_ITEM_SELECTED_P)));
8247
8248 return 1;
8249
8250 #undef PROP
8251 }
8252
8253
8254 /* Initialize tool_bar_items_vector. REUSE, if non-nil, is a vector
8255 that can be reused. */
8256
8257 static void
8258 init_tool_bar_items (Lisp_Object reuse)
8259 {
8260 if (VECTORP (reuse))
8261 tool_bar_items_vector = reuse;
8262 else
8263 tool_bar_items_vector = Fmake_vector (make_number (64), Qnil);
8264 ntool_bar_items = 0;
8265 }
8266
8267
8268 /* Append parsed tool bar item properties from
8269 tool_bar_item_properties */
8270
8271 static void
8272 append_tool_bar_item (void)
8273 {
8274 ptrdiff_t incr
8275 = (ntool_bar_items
8276 - (ASIZE (tool_bar_items_vector) - TOOL_BAR_ITEM_NSLOTS));
8277
8278 /* Enlarge tool_bar_items_vector if necessary. */
8279 if (incr > 0)
8280 tool_bar_items_vector = larger_vector (tool_bar_items_vector, incr, -1);
8281
8282 /* Append entries from tool_bar_item_properties to the end of
8283 tool_bar_items_vector. */
8284 vcopy (tool_bar_items_vector, ntool_bar_items,
8285 XVECTOR (tool_bar_item_properties)->contents, TOOL_BAR_ITEM_NSLOTS);
8286 ntool_bar_items += TOOL_BAR_ITEM_NSLOTS;
8287 }
8288
8289
8290
8291
8292 \f
8293 /* Read a character using menus based on the keymap MAP.
8294 Return nil if there are no menus in the maps.
8295 Return t if we displayed a menu but the user rejected it.
8296
8297 PREV_EVENT is the previous input event, or nil if we are reading
8298 the first event of a key sequence.
8299
8300 If USED_MOUSE_MENU is non-null, set *USED_MOUSE_MENU to true
8301 if we used a mouse menu to read the input, or false otherwise. If
8302 USED_MOUSE_MENU is null, don't dereference it.
8303
8304 The prompting is done based on the prompt-string of the map
8305 and the strings associated with various map elements.
8306
8307 This can be done with X menus or with menus put in the minibuf.
8308 These are done in different ways, depending on how the input will be read.
8309 Menus using X are done after auto-saving in read-char, getting the input
8310 event from Fx_popup_menu; menus using the minibuf use read_char recursively
8311 and do auto-saving in the inner call of read_char. */
8312
8313 static Lisp_Object
8314 read_char_x_menu_prompt (Lisp_Object map,
8315 Lisp_Object prev_event, bool *used_mouse_menu)
8316 {
8317 if (used_mouse_menu)
8318 *used_mouse_menu = false;
8319
8320 /* Use local over global Menu maps. */
8321
8322 if (! menu_prompting)
8323 return Qnil;
8324
8325 /* If we got to this point via a mouse click,
8326 use a real menu for mouse selection. */
8327 if (EVENT_HAS_PARAMETERS (prev_event)
8328 && !EQ (XCAR (prev_event), Qmenu_bar)
8329 && !EQ (XCAR (prev_event), Qtool_bar))
8330 {
8331 /* Display the menu and get the selection. */
8332 Lisp_Object value;
8333
8334 value = Fx_popup_menu (prev_event, get_keymap (map, 0, 1));
8335 if (CONSP (value))
8336 {
8337 Lisp_Object tem;
8338
8339 record_menu_key (XCAR (value));
8340
8341 /* If we got multiple events, unread all but
8342 the first.
8343 There is no way to prevent those unread events
8344 from showing up later in last_nonmenu_event.
8345 So turn symbol and integer events into lists,
8346 to indicate that they came from a mouse menu,
8347 so that when present in last_nonmenu_event
8348 they won't confuse things. */
8349 for (tem = XCDR (value); CONSP (tem); tem = XCDR (tem))
8350 {
8351 record_menu_key (XCAR (tem));
8352 if (SYMBOLP (XCAR (tem))
8353 || INTEGERP (XCAR (tem)))
8354 XSETCAR (tem, Fcons (XCAR (tem), Qdisabled));
8355 }
8356
8357 /* If we got more than one event, put all but the first
8358 onto this list to be read later.
8359 Return just the first event now. */
8360 Vunread_command_events
8361 = nconc2 (XCDR (value), Vunread_command_events);
8362 value = XCAR (value);
8363 }
8364 else if (NILP (value))
8365 value = Qt;
8366 if (used_mouse_menu)
8367 *used_mouse_menu = true;
8368 return value;
8369 }
8370 return Qnil ;
8371 }
8372
8373 static Lisp_Object
8374 read_char_minibuf_menu_prompt (int commandflag,
8375 Lisp_Object map)
8376 {
8377 Lisp_Object name;
8378 ptrdiff_t nlength;
8379 /* FIXME: Use the minibuffer's frame width. */
8380 ptrdiff_t width = FRAME_COLS (SELECTED_FRAME ()) - 4;
8381 ptrdiff_t idx = -1;
8382 bool nobindings = true;
8383 Lisp_Object rest, vector;
8384 Lisp_Object prompt_strings = Qnil;
8385
8386 vector = Qnil;
8387
8388 if (! menu_prompting)
8389 return Qnil;
8390
8391 map = get_keymap (map, 0, 1);
8392 name = Fkeymap_prompt (map);
8393
8394 /* If we don't have any menus, just read a character normally. */
8395 if (!STRINGP (name))
8396 return Qnil;
8397
8398 #define PUSH_C_STR(str, listvar) \
8399 listvar = Fcons (build_unibyte_string (str), listvar)
8400
8401 /* Prompt string always starts with map's prompt, and a space. */
8402 prompt_strings = Fcons (name, prompt_strings);
8403 PUSH_C_STR (": ", prompt_strings);
8404 nlength = SCHARS (name) + 2;
8405
8406 rest = map;
8407
8408 /* Present the documented bindings, a line at a time. */
8409 while (1)
8410 {
8411 bool notfirst = false;
8412 Lisp_Object menu_strings = prompt_strings;
8413 ptrdiff_t i = nlength;
8414 Lisp_Object obj;
8415 Lisp_Object orig_defn_macro;
8416
8417 /* Loop over elements of map. */
8418 while (i < width)
8419 {
8420 Lisp_Object elt;
8421
8422 /* FIXME: Use map_keymap to handle new keymap formats. */
8423
8424 /* At end of map, wrap around if just starting,
8425 or end this line if already have something on it. */
8426 if (NILP (rest))
8427 {
8428 if (notfirst || nobindings)
8429 break;
8430 else
8431 rest = map;
8432 }
8433
8434 /* Look at the next element of the map. */
8435 if (idx >= 0)
8436 elt = AREF (vector, idx);
8437 else
8438 elt = Fcar_safe (rest);
8439
8440 if (idx < 0 && VECTORP (elt))
8441 {
8442 /* If we found a dense table in the keymap,
8443 advanced past it, but start scanning its contents. */
8444 rest = Fcdr_safe (rest);
8445 vector = elt;
8446 idx = 0;
8447 }
8448 else
8449 {
8450 /* An ordinary element. */
8451 Lisp_Object event, tem;
8452
8453 if (idx < 0)
8454 {
8455 event = Fcar_safe (elt); /* alist */
8456 elt = Fcdr_safe (elt);
8457 }
8458 else
8459 {
8460 XSETINT (event, idx); /* vector */
8461 }
8462
8463 /* Ignore the element if it has no prompt string. */
8464 if (INTEGERP (event) && parse_menu_item (elt, -1))
8465 {
8466 /* True if the char to type matches the string. */
8467 bool char_matches;
8468 Lisp_Object upcased_event, downcased_event;
8469 Lisp_Object desc = Qnil;
8470 Lisp_Object s
8471 = AREF (item_properties, ITEM_PROPERTY_NAME);
8472
8473 upcased_event = Fupcase (event);
8474 downcased_event = Fdowncase (event);
8475 char_matches = (XINT (upcased_event) == SREF (s, 0)
8476 || XINT (downcased_event) == SREF (s, 0));
8477 if (! char_matches)
8478 desc = Fsingle_key_description (event, Qnil);
8479
8480 #if 0 /* It is redundant to list the equivalent key bindings because
8481 the prefix is what the user has already typed. */
8482 tem
8483 = XVECTOR (item_properties)->contents[ITEM_PROPERTY_KEYEQ];
8484 if (!NILP (tem))
8485 /* Insert equivalent keybinding. */
8486 s = concat2 (s, tem);
8487 #endif
8488 tem
8489 = AREF (item_properties, ITEM_PROPERTY_TYPE);
8490 if (EQ (tem, QCradio) || EQ (tem, QCtoggle))
8491 {
8492 /* Insert button prefix. */
8493 Lisp_Object selected
8494 = AREF (item_properties, ITEM_PROPERTY_SELECTED);
8495 AUTO_STRING (radio_yes, "(*) ");
8496 AUTO_STRING (radio_no , "( ) ");
8497 AUTO_STRING (check_yes, "[X] ");
8498 AUTO_STRING (check_no , "[ ] ");
8499 if (EQ (tem, QCradio))
8500 tem = NILP (selected) ? radio_yes : radio_no;
8501 else
8502 tem = NILP (selected) ? check_yes : check_no;
8503 s = concat2 (tem, s);
8504 }
8505
8506
8507 /* If we have room for the prompt string, add it to this line.
8508 If this is the first on the line, always add it. */
8509 if ((SCHARS (s) + i + 2
8510 + (char_matches ? 0 : SCHARS (desc) + 3))
8511 < width
8512 || !notfirst)
8513 {
8514 ptrdiff_t thiswidth;
8515
8516 /* Punctuate between strings. */
8517 if (notfirst)
8518 {
8519 PUSH_C_STR (", ", menu_strings);
8520 i += 2;
8521 }
8522 notfirst = true;
8523 nobindings = false;
8524
8525 /* If the char to type doesn't match the string's
8526 first char, explicitly show what char to type. */
8527 if (! char_matches)
8528 {
8529 /* Add as much of string as fits. */
8530 thiswidth = min (SCHARS (desc), width - i);
8531 menu_strings
8532 = Fcons (Fsubstring (desc, make_number (0),
8533 make_number (thiswidth)),
8534 menu_strings);
8535 i += thiswidth;
8536 PUSH_C_STR (" = ", menu_strings);
8537 i += 3;
8538 }
8539
8540 /* Add as much of string as fits. */
8541 thiswidth = min (SCHARS (s), width - i);
8542 menu_strings
8543 = Fcons (Fsubstring (s, make_number (0),
8544 make_number (thiswidth)),
8545 menu_strings);
8546 i += thiswidth;
8547 }
8548 else
8549 {
8550 /* If this element does not fit, end the line now,
8551 and save the element for the next line. */
8552 PUSH_C_STR ("...", menu_strings);
8553 break;
8554 }
8555 }
8556
8557 /* Move past this element. */
8558 if (idx >= 0 && idx + 1 >= ASIZE (vector))
8559 /* Handle reaching end of dense table. */
8560 idx = -1;
8561 if (idx >= 0)
8562 idx++;
8563 else
8564 rest = Fcdr_safe (rest);
8565 }
8566 }
8567
8568 /* Prompt with that and read response. */
8569 message3_nolog (apply1 (intern ("concat"), Fnreverse (menu_strings)));
8570
8571 /* Make believe it's not a keyboard macro in case the help char
8572 is pressed. Help characters are not recorded because menu prompting
8573 is not used on replay. */
8574 orig_defn_macro = KVAR (current_kboard, defining_kbd_macro);
8575 kset_defining_kbd_macro (current_kboard, Qnil);
8576 do
8577 obj = read_char (commandflag, Qnil, Qt, 0, NULL);
8578 while (BUFFERP (obj));
8579 kset_defining_kbd_macro (current_kboard, orig_defn_macro);
8580
8581 if (!INTEGERP (obj) || XINT (obj) == -2
8582 || (! EQ (obj, menu_prompt_more_char)
8583 && (!INTEGERP (menu_prompt_more_char)
8584 || ! EQ (obj, make_number (Ctl (XINT (menu_prompt_more_char)))))))
8585 {
8586 if (!NILP (KVAR (current_kboard, defining_kbd_macro)))
8587 store_kbd_macro_char (obj);
8588 return obj;
8589 }
8590 /* Help char - go round again. */
8591 }
8592 }
8593 \f
8594 /* Reading key sequences. */
8595
8596 static Lisp_Object
8597 follow_key (Lisp_Object keymap, Lisp_Object key)
8598 {
8599 return access_keymap (get_keymap (keymap, 0, 1),
8600 key, 1, 0, 1);
8601 }
8602
8603 static Lisp_Object
8604 active_maps (Lisp_Object first_event)
8605 {
8606 Lisp_Object position
8607 = CONSP (first_event) ? CAR_SAFE (XCDR (first_event)) : Qnil;
8608 return Fcons (Qkeymap, Fcurrent_active_maps (Qt, position));
8609 }
8610
8611 /* Structure used to keep track of partial application of key remapping
8612 such as Vfunction_key_map and Vkey_translation_map. */
8613 typedef struct keyremap
8614 {
8615 /* This is the map originally specified for this use. */
8616 Lisp_Object parent;
8617 /* This is a submap reached by looking up, in PARENT,
8618 the events from START to END. */
8619 Lisp_Object map;
8620 /* Positions [START, END) in the key sequence buffer
8621 are the key that we have scanned so far.
8622 Those events are the ones that we will replace
8623 if PARENT maps them into a key sequence. */
8624 int start, end;
8625 } keyremap;
8626
8627 /* Lookup KEY in MAP.
8628 MAP is a keymap mapping keys to key vectors or functions.
8629 If the mapping is a function and DO_FUNCALL is true,
8630 the function is called with PROMPT as parameter and its return
8631 value is used as the return value of this function (after checking
8632 that it is indeed a vector). */
8633
8634 static Lisp_Object
8635 access_keymap_keyremap (Lisp_Object map, Lisp_Object key, Lisp_Object prompt,
8636 bool do_funcall)
8637 {
8638 Lisp_Object next;
8639
8640 next = access_keymap (map, key, 1, 0, 1);
8641
8642 /* Handle a symbol whose function definition is a keymap
8643 or an array. */
8644 if (SYMBOLP (next) && !NILP (Ffboundp (next))
8645 && (ARRAYP (XSYMBOL (next)->function)
8646 || KEYMAPP (XSYMBOL (next)->function)))
8647 next = Fautoload_do_load (XSYMBOL (next)->function, next, Qnil);
8648
8649 /* If the keymap gives a function, not an
8650 array, then call the function with one arg and use
8651 its value instead. */
8652 if (do_funcall && FUNCTIONP (next))
8653 {
8654 Lisp_Object tem;
8655 tem = next;
8656
8657 next = call1 (next, prompt);
8658 /* If the function returned something invalid,
8659 barf--don't ignore it. */
8660 if (! (NILP (next) || VECTORP (next) || STRINGP (next)))
8661 error ("Function %s returns invalid key sequence",
8662 SSDATA (SYMBOL_NAME (tem)));
8663 }
8664 return next;
8665 }
8666
8667 /* Do one step of the key remapping used for function-key-map and
8668 key-translation-map:
8669 KEYBUF is the buffer holding the input events.
8670 BUFSIZE is its maximum size.
8671 FKEY is a pointer to the keyremap structure to use.
8672 INPUT is the index of the last element in KEYBUF.
8673 DOIT if true says that the remapping can actually take place.
8674 DIFF is used to return the number of keys added/removed by the remapping.
8675 PARENT is the root of the keymap.
8676 PROMPT is the prompt to use if the remapping happens through a function.
8677 Return true if the remapping actually took place. */
8678
8679 static bool
8680 keyremap_step (Lisp_Object *keybuf, int bufsize, volatile keyremap *fkey,
8681 int input, bool doit, int *diff, Lisp_Object prompt)
8682 {
8683 Lisp_Object next, key;
8684
8685 key = keybuf[fkey->end++];
8686
8687 if (KEYMAPP (fkey->parent))
8688 next = access_keymap_keyremap (fkey->map, key, prompt, doit);
8689 else
8690 next = Qnil;
8691
8692 /* If keybuf[fkey->start..fkey->end] is bound in the
8693 map and we're in a position to do the key remapping, replace it with
8694 the binding and restart with fkey->start at the end. */
8695 if ((VECTORP (next) || STRINGP (next)) && doit)
8696 {
8697 int len = XFASTINT (Flength (next));
8698 int i;
8699
8700 *diff = len - (fkey->end - fkey->start);
8701
8702 if (bufsize - input <= *diff)
8703 error ("Key sequence too long");
8704
8705 /* Shift the keys that follow fkey->end. */
8706 if (*diff < 0)
8707 for (i = fkey->end; i < input; i++)
8708 keybuf[i + *diff] = keybuf[i];
8709 else if (*diff > 0)
8710 for (i = input - 1; i >= fkey->end; i--)
8711 keybuf[i + *diff] = keybuf[i];
8712 /* Overwrite the old keys with the new ones. */
8713 for (i = 0; i < len; i++)
8714 keybuf[fkey->start + i]
8715 = Faref (next, make_number (i));
8716
8717 fkey->start = fkey->end += *diff;
8718 fkey->map = fkey->parent;
8719
8720 return 1;
8721 }
8722
8723 fkey->map = get_keymap (next, 0, 1);
8724
8725 /* If we no longer have a bound suffix, try a new position for
8726 fkey->start. */
8727 if (!CONSP (fkey->map))
8728 {
8729 fkey->end = ++fkey->start;
8730 fkey->map = fkey->parent;
8731 }
8732 return 0;
8733 }
8734
8735 static bool
8736 test_undefined (Lisp_Object binding)
8737 {
8738 return (NILP (binding)
8739 || EQ (binding, Qundefined)
8740 || (SYMBOLP (binding)
8741 && EQ (Fcommand_remapping (binding, Qnil, Qnil), Qundefined)));
8742 }
8743
8744 /* Read a sequence of keys that ends with a non prefix character,
8745 storing it in KEYBUF, a buffer of size BUFSIZE.
8746 Prompt with PROMPT.
8747 Return the length of the key sequence stored.
8748 Return -1 if the user rejected a command menu.
8749
8750 Echo starting immediately unless `prompt' is 0.
8751
8752 If PREVENT_REDISPLAY is non-zero, avoid redisplay by calling
8753 read_char with a suitable COMMANDFLAG argument.
8754
8755 Where a key sequence ends depends on the currently active keymaps.
8756 These include any minor mode keymaps active in the current buffer,
8757 the current buffer's local map, and the global map.
8758
8759 If a key sequence has no other bindings, we check Vfunction_key_map
8760 to see if some trailing subsequence might be the beginning of a
8761 function key's sequence. If so, we try to read the whole function
8762 key, and substitute its symbolic name into the key sequence.
8763
8764 We ignore unbound `down-' mouse clicks. We turn unbound `drag-' and
8765 `double-' events into similar click events, if that would make them
8766 bound. We try to turn `triple-' events first into `double-' events,
8767 then into clicks.
8768
8769 If we get a mouse click in a mode line, vertical divider, or other
8770 non-text area, we treat the click as if it were prefixed by the
8771 symbol denoting that area - `mode-line', `vertical-line', or
8772 whatever.
8773
8774 If the sequence starts with a mouse click, we read the key sequence
8775 with respect to the buffer clicked on, not the current buffer.
8776
8777 If the user switches frames in the midst of a key sequence, we put
8778 off the switch-frame event until later; the next call to
8779 read_char will return it.
8780
8781 If FIX_CURRENT_BUFFER, we restore current_buffer
8782 from the selected window's buffer. */
8783
8784 static int
8785 read_key_sequence (Lisp_Object *keybuf, int bufsize, Lisp_Object prompt,
8786 bool dont_downcase_last, bool can_return_switch_frame,
8787 bool fix_current_buffer, bool prevent_redisplay)
8788 {
8789 ptrdiff_t count = SPECPDL_INDEX ();
8790
8791 /* How many keys there are in the current key sequence. */
8792 int t;
8793
8794 /* The length of the echo buffer when we started reading, and
8795 the length of this_command_keys when we started reading. */
8796 ptrdiff_t echo_start IF_LINT (= 0);
8797 ptrdiff_t keys_start;
8798
8799 Lisp_Object current_binding = Qnil;
8800 Lisp_Object first_event = Qnil;
8801
8802 /* Index of the first key that has no binding.
8803 It is useless to try fkey.start larger than that. */
8804 int first_unbound;
8805
8806 /* If t < mock_input, then KEYBUF[t] should be read as the next
8807 input key.
8808
8809 We use this to recover after recognizing a function key. Once we
8810 realize that a suffix of the current key sequence is actually a
8811 function key's escape sequence, we replace the suffix with the
8812 function key's binding from Vfunction_key_map. Now keybuf
8813 contains a new and different key sequence, so the echo area,
8814 this_command_keys, and the submaps and defs arrays are wrong. In
8815 this situation, we set mock_input to t, set t to 0, and jump to
8816 restart_sequence; the loop will read keys from keybuf up until
8817 mock_input, thus rebuilding the state; and then it will resume
8818 reading characters from the keyboard. */
8819 int mock_input = 0;
8820
8821 /* If the sequence is unbound in submaps[], then
8822 keybuf[fkey.start..fkey.end-1] is a prefix in Vfunction_key_map,
8823 and fkey.map is its binding.
8824
8825 These might be > t, indicating that all function key scanning
8826 should hold off until t reaches them. We do this when we've just
8827 recognized a function key, to avoid searching for the function
8828 key's again in Vfunction_key_map. */
8829 keyremap fkey;
8830
8831 /* Likewise, for key_translation_map and input-decode-map. */
8832 keyremap keytran, indec;
8833
8834 /* True if we are trying to map a key by changing an upper-case
8835 letter to lower case, or a shifted function key to an unshifted
8836 one. */
8837 bool shift_translated = false;
8838
8839 /* If we receive a `switch-frame' or `select-window' event in the middle of
8840 a key sequence, we put it off for later.
8841 While we're reading, we keep the event here. */
8842 Lisp_Object delayed_switch_frame;
8843
8844 Lisp_Object original_uppercase IF_LINT (= Qnil);
8845 int original_uppercase_position = -1;
8846
8847 /* Gets around Microsoft compiler limitations. */
8848 bool dummyflag = false;
8849
8850 struct buffer *starting_buffer;
8851
8852 /* List of events for which a fake prefix key has been generated. */
8853 Lisp_Object fake_prefixed_keys = Qnil;
8854
8855 raw_keybuf_count = 0;
8856
8857 last_nonmenu_event = Qnil;
8858
8859 delayed_switch_frame = Qnil;
8860
8861 if (INTERACTIVE)
8862 {
8863 if (!NILP (prompt))
8864 {
8865 /* Install the string PROMPT as the beginning of the string
8866 of echoing, so that it serves as a prompt for the next
8867 character. */
8868 kset_echo_prompt (current_kboard, prompt);
8869 current_kboard->immediate_echo = false;
8870 echo_now ();
8871 }
8872 else if (cursor_in_echo_area
8873 && echo_keystrokes_p ())
8874 /* This doesn't put in a dash if the echo buffer is empty, so
8875 you don't always see a dash hanging out in the minibuffer. */
8876 echo_dash ();
8877 }
8878
8879 /* Record the initial state of the echo area and this_command_keys;
8880 we will need to restore them if we replay a key sequence. */
8881 if (INTERACTIVE)
8882 echo_start = echo_length ();
8883 keys_start = this_command_key_count;
8884 this_single_command_key_start = keys_start;
8885
8886 /* We jump here when we need to reinitialize fkey and keytran; this
8887 happens if we switch keyboards between rescans. */
8888 replay_entire_sequence:
8889
8890 indec.map = indec.parent = KVAR (current_kboard, Vinput_decode_map);
8891 fkey.map = fkey.parent = KVAR (current_kboard, Vlocal_function_key_map);
8892 keytran.map = keytran.parent = Vkey_translation_map;
8893 indec.start = indec.end = 0;
8894 fkey.start = fkey.end = 0;
8895 keytran.start = keytran.end = 0;
8896
8897 /* We jump here when the key sequence has been thoroughly changed, and
8898 we need to rescan it starting from the beginning. When we jump here,
8899 keybuf[0..mock_input] holds the sequence we should reread. */
8900 replay_sequence:
8901
8902 starting_buffer = current_buffer;
8903 first_unbound = bufsize + 1;
8904
8905 /* Build our list of keymaps.
8906 If we recognize a function key and replace its escape sequence in
8907 keybuf with its symbol, or if the sequence starts with a mouse
8908 click and we need to switch buffers, we jump back here to rebuild
8909 the initial keymaps from the current buffer. */
8910 current_binding = active_maps (first_event);
8911
8912 /* Start from the beginning in keybuf. */
8913 t = 0;
8914
8915 /* These are no-ops the first time through, but if we restart, they
8916 revert the echo area and this_command_keys to their original state. */
8917 this_command_key_count = keys_start;
8918 if (INTERACTIVE && t < mock_input)
8919 echo_truncate (echo_start);
8920
8921 /* If the best binding for the current key sequence is a keymap, or
8922 we may be looking at a function key's escape sequence, keep on
8923 reading. */
8924 while (!NILP (current_binding)
8925 /* Keep reading as long as there's a prefix binding. */
8926 ? KEYMAPP (current_binding)
8927 /* Don't return in the middle of a possible function key sequence,
8928 if the only bindings we found were via case conversion.
8929 Thus, if ESC O a has a function-key-map translation
8930 and ESC o has a binding, don't return after ESC O,
8931 so that we can translate ESC O plus the next character. */
8932 : (/* indec.start < t || fkey.start < t || */ keytran.start < t))
8933 {
8934 Lisp_Object key;
8935 bool used_mouse_menu = false;
8936
8937 /* Where the last real key started. If we need to throw away a
8938 key that has expanded into more than one element of keybuf
8939 (say, a mouse click on the mode line which is being treated
8940 as [mode-line (mouse-...)], then we backtrack to this point
8941 of keybuf. */
8942 int last_real_key_start;
8943
8944 /* These variables are analogous to echo_start and keys_start;
8945 while those allow us to restart the entire key sequence,
8946 echo_local_start and keys_local_start allow us to throw away
8947 just one key. */
8948 ptrdiff_t echo_local_start IF_LINT (= 0);
8949 int keys_local_start;
8950 Lisp_Object new_binding;
8951
8952 eassert (indec.end == t || (indec.end > t && indec.end <= mock_input));
8953 eassert (indec.start <= indec.end);
8954 eassert (fkey.start <= fkey.end);
8955 eassert (keytran.start <= keytran.end);
8956 /* key-translation-map is applied *after* function-key-map
8957 which is itself applied *after* input-decode-map. */
8958 eassert (fkey.end <= indec.start);
8959 eassert (keytran.end <= fkey.start);
8960
8961 if (/* first_unbound < indec.start && first_unbound < fkey.start && */
8962 first_unbound < keytran.start)
8963 { /* The prefix upto first_unbound has no binding and has
8964 no translation left to do either, so we know it's unbound.
8965 If we don't stop now, we risk staying here indefinitely
8966 (if the user keeps entering fkey or keytran prefixes
8967 like C-c ESC ESC ESC ESC ...) */
8968 int i;
8969 for (i = first_unbound + 1; i < t; i++)
8970 keybuf[i - first_unbound - 1] = keybuf[i];
8971 mock_input = t - first_unbound - 1;
8972 indec.end = indec.start -= first_unbound + 1;
8973 indec.map = indec.parent;
8974 fkey.end = fkey.start -= first_unbound + 1;
8975 fkey.map = fkey.parent;
8976 keytran.end = keytran.start -= first_unbound + 1;
8977 keytran.map = keytran.parent;
8978 goto replay_sequence;
8979 }
8980
8981 if (t >= bufsize)
8982 error ("Key sequence too long");
8983
8984 if (INTERACTIVE)
8985 echo_local_start = echo_length ();
8986 keys_local_start = this_command_key_count;
8987
8988 replay_key:
8989 /* These are no-ops, unless we throw away a keystroke below and
8990 jumped back up to replay_key; in that case, these restore the
8991 variables to their original state, allowing us to replay the
8992 loop. */
8993 if (INTERACTIVE && t < mock_input)
8994 echo_truncate (echo_local_start);
8995 this_command_key_count = keys_local_start;
8996
8997 /* By default, assume each event is "real". */
8998 last_real_key_start = t;
8999
9000 /* Does mock_input indicate that we are re-reading a key sequence? */
9001 if (t < mock_input)
9002 {
9003 key = keybuf[t];
9004 add_command_key (key);
9005 if (current_kboard->immediate_echo)
9006 {
9007 /* Set immediate_echo to false so as to force echo_now to
9008 redisplay (it will set immediate_echo right back to true). */
9009 current_kboard->immediate_echo = false;
9010 echo_now ();
9011 }
9012 }
9013
9014 /* If not, we should actually read a character. */
9015 else
9016 {
9017 {
9018 KBOARD *interrupted_kboard = current_kboard;
9019 struct frame *interrupted_frame = SELECTED_FRAME ();
9020 /* Calling read_char with COMMANDFLAG = -2 avoids
9021 redisplay in read_char and its subroutines. */
9022 key = read_char (prevent_redisplay ? -2 : NILP (prompt),
9023 current_binding, last_nonmenu_event,
9024 &used_mouse_menu, NULL);
9025 if ((INTEGERP (key) && XINT (key) == -2) /* wrong_kboard_jmpbuf */
9026 /* When switching to a new tty (with a new keyboard),
9027 read_char returns the new buffer, rather than -2
9028 (Bug#5095). This is because `terminal-init-xterm'
9029 calls read-char, which eats the wrong_kboard_jmpbuf
9030 return. Any better way to fix this? -- cyd */
9031 || (interrupted_kboard != current_kboard))
9032 {
9033 bool found = false;
9034 struct kboard *k;
9035
9036 for (k = all_kboards; k; k = k->next_kboard)
9037 if (k == interrupted_kboard)
9038 found = true;
9039
9040 if (!found)
9041 {
9042 /* Don't touch interrupted_kboard when it's been
9043 deleted. */
9044 delayed_switch_frame = Qnil;
9045 goto replay_entire_sequence;
9046 }
9047
9048 if (!NILP (delayed_switch_frame))
9049 {
9050 kset_kbd_queue
9051 (interrupted_kboard,
9052 Fcons (delayed_switch_frame,
9053 KVAR (interrupted_kboard, kbd_queue)));
9054 delayed_switch_frame = Qnil;
9055 }
9056
9057 while (t > 0)
9058 kset_kbd_queue
9059 (interrupted_kboard,
9060 Fcons (keybuf[--t], KVAR (interrupted_kboard, kbd_queue)));
9061
9062 /* If the side queue is non-empty, ensure it begins with a
9063 switch-frame, so we'll replay it in the right context. */
9064 if (CONSP (KVAR (interrupted_kboard, kbd_queue))
9065 && (key = XCAR (KVAR (interrupted_kboard, kbd_queue)),
9066 !(EVENT_HAS_PARAMETERS (key)
9067 && EQ (EVENT_HEAD_KIND (EVENT_HEAD (key)),
9068 Qswitch_frame))))
9069 {
9070 Lisp_Object frame;
9071 XSETFRAME (frame, interrupted_frame);
9072 kset_kbd_queue
9073 (interrupted_kboard,
9074 Fcons (make_lispy_switch_frame (frame),
9075 KVAR (interrupted_kboard, kbd_queue)));
9076 }
9077 mock_input = 0;
9078 goto replay_entire_sequence;
9079 }
9080 }
9081
9082 /* read_char returns t when it shows a menu and the user rejects it.
9083 Just return -1. */
9084 if (EQ (key, Qt))
9085 {
9086 unbind_to (count, Qnil);
9087 return -1;
9088 }
9089
9090 /* read_char returns -1 at the end of a macro.
9091 Emacs 18 handles this by returning immediately with a
9092 zero, so that's what we'll do. */
9093 if (INTEGERP (key) && XINT (key) == -1)
9094 {
9095 t = 0;
9096 /* The Microsoft C compiler can't handle the goto that
9097 would go here. */
9098 dummyflag = true;
9099 break;
9100 }
9101
9102 /* If the current buffer has been changed from under us, the
9103 keymap may have changed, so replay the sequence. */
9104 if (BUFFERP (key))
9105 {
9106 timer_resume_idle ();
9107
9108 mock_input = t;
9109 /* Reset the current buffer from the selected window
9110 in case something changed the former and not the latter.
9111 This is to be more consistent with the behavior
9112 of the command_loop_1. */
9113 if (fix_current_buffer)
9114 {
9115 if (! FRAME_LIVE_P (XFRAME (selected_frame)))
9116 Fkill_emacs (Qnil);
9117 if (XBUFFER (XWINDOW (selected_window)->contents)
9118 != current_buffer)
9119 Fset_buffer (XWINDOW (selected_window)->contents);
9120 }
9121
9122 goto replay_sequence;
9123 }
9124
9125 /* If we have a quit that was typed in another frame, and
9126 quit_throw_to_read_char switched buffers,
9127 replay to get the right keymap. */
9128 if (INTEGERP (key)
9129 && XINT (key) == quit_char
9130 && current_buffer != starting_buffer)
9131 {
9132 GROW_RAW_KEYBUF;
9133 ASET (raw_keybuf, raw_keybuf_count, key);
9134 raw_keybuf_count++;
9135 keybuf[t++] = key;
9136 mock_input = t;
9137 Vquit_flag = Qnil;
9138 goto replay_sequence;
9139 }
9140
9141 Vquit_flag = Qnil;
9142
9143 if (EVENT_HAS_PARAMETERS (key)
9144 /* Either a `switch-frame' or a `select-window' event. */
9145 && EQ (EVENT_HEAD_KIND (EVENT_HEAD (key)), Qswitch_frame))
9146 {
9147 /* If we're at the beginning of a key sequence, and the caller
9148 says it's okay, go ahead and return this event. If we're
9149 in the midst of a key sequence, delay it until the end. */
9150 if (t > 0 || !can_return_switch_frame)
9151 {
9152 delayed_switch_frame = key;
9153 goto replay_key;
9154 }
9155 }
9156
9157 if (NILP (first_event))
9158 {
9159 first_event = key;
9160 /* Even if first_event does not specify a particular
9161 window/position, it's important to recompute the maps here
9162 since a long time might have passed since we entered
9163 read_key_sequence, and a timer (or process-filter or
9164 special-event-map, ...) might have switched the current buffer
9165 or the selected window from under us in the mean time. */
9166 if (fix_current_buffer
9167 && (XBUFFER (XWINDOW (selected_window)->contents)
9168 != current_buffer))
9169 Fset_buffer (XWINDOW (selected_window)->contents);
9170 current_binding = active_maps (first_event);
9171 }
9172
9173 GROW_RAW_KEYBUF;
9174 ASET (raw_keybuf, raw_keybuf_count, key);
9175 raw_keybuf_count++;
9176 }
9177
9178 /* Clicks in non-text areas get prefixed by the symbol
9179 in their CHAR-ADDRESS field. For example, a click on
9180 the mode line is prefixed by the symbol `mode-line'.
9181
9182 Furthermore, key sequences beginning with mouse clicks
9183 are read using the keymaps of the buffer clicked on, not
9184 the current buffer. So we may have to switch the buffer
9185 here.
9186
9187 When we turn one event into two events, we must make sure
9188 that neither of the two looks like the original--so that,
9189 if we replay the events, they won't be expanded again.
9190 If not for this, such reexpansion could happen either here
9191 or when user programs play with this-command-keys. */
9192 if (EVENT_HAS_PARAMETERS (key))
9193 {
9194 Lisp_Object kind = EVENT_HEAD_KIND (EVENT_HEAD (key));
9195 if (EQ (kind, Qmouse_click))
9196 {
9197 Lisp_Object window = POSN_WINDOW (EVENT_START (key));
9198 Lisp_Object posn = POSN_POSN (EVENT_START (key));
9199
9200 if (CONSP (posn)
9201 || (!NILP (fake_prefixed_keys)
9202 && !NILP (Fmemq (key, fake_prefixed_keys))))
9203 {
9204 /* We're looking a second time at an event for which
9205 we generated a fake prefix key. Set
9206 last_real_key_start appropriately. */
9207 if (t > 0)
9208 last_real_key_start = t - 1;
9209 }
9210
9211 if (last_real_key_start == 0)
9212 {
9213 /* Key sequences beginning with mouse clicks are
9214 read using the keymaps in the buffer clicked on,
9215 not the current buffer. If we're at the
9216 beginning of a key sequence, switch buffers. */
9217 if (WINDOWP (window)
9218 && BUFFERP (XWINDOW (window)->contents)
9219 && XBUFFER (XWINDOW (window)->contents) != current_buffer)
9220 {
9221 ASET (raw_keybuf, raw_keybuf_count, key);
9222 raw_keybuf_count++;
9223 keybuf[t] = key;
9224 mock_input = t + 1;
9225
9226 /* Arrange to go back to the original buffer once we're
9227 done reading the key sequence. Note that we can't
9228 use save_excursion_{save,restore} here, because they
9229 save point as well as the current buffer; we don't
9230 want to save point, because redisplay may change it,
9231 to accommodate a Fset_window_start or something. We
9232 don't want to do this at the top of the function,
9233 because we may get input from a subprocess which
9234 wants to change the selected window and stuff (say,
9235 emacsclient). */
9236 record_unwind_current_buffer ();
9237
9238 if (! FRAME_LIVE_P (XFRAME (selected_frame)))
9239 Fkill_emacs (Qnil);
9240 set_buffer_internal (XBUFFER (XWINDOW (window)->contents));
9241 goto replay_sequence;
9242 }
9243 }
9244
9245 /* Expand mode-line and scroll-bar events into two events:
9246 use posn as a fake prefix key. */
9247 if (SYMBOLP (posn)
9248 && (NILP (fake_prefixed_keys)
9249 || NILP (Fmemq (key, fake_prefixed_keys))))
9250 {
9251 if (bufsize - t <= 1)
9252 error ("Key sequence too long");
9253
9254 keybuf[t] = posn;
9255 keybuf[t + 1] = key;
9256 mock_input = t + 2;
9257
9258 /* Record that a fake prefix key has been generated
9259 for KEY. Don't modify the event; this would
9260 prevent proper action when the event is pushed
9261 back into unread-command-events. */
9262 fake_prefixed_keys = Fcons (key, fake_prefixed_keys);
9263 goto replay_key;
9264 }
9265 }
9266 else if (CONSP (XCDR (key))
9267 && CONSP (EVENT_START (key))
9268 && CONSP (XCDR (EVENT_START (key))))
9269 {
9270 Lisp_Object posn;
9271
9272 posn = POSN_POSN (EVENT_START (key));
9273 /* Handle menu-bar events:
9274 insert the dummy prefix event `menu-bar'. */
9275 if (EQ (posn, Qmenu_bar) || EQ (posn, Qtool_bar))
9276 {
9277 if (bufsize - t <= 1)
9278 error ("Key sequence too long");
9279 keybuf[t] = posn;
9280 keybuf[t + 1] = key;
9281
9282 /* Zap the position in key, so we know that we've
9283 expanded it, and don't try to do so again. */
9284 POSN_SET_POSN (EVENT_START (key), list1 (posn));
9285
9286 mock_input = t + 2;
9287 goto replay_sequence;
9288 }
9289 else if (CONSP (posn))
9290 {
9291 /* We're looking at the second event of a
9292 sequence which we expanded before. Set
9293 last_real_key_start appropriately. */
9294 if (last_real_key_start == t && t > 0)
9295 last_real_key_start = t - 1;
9296 }
9297 }
9298 }
9299
9300 /* We have finally decided that KEY is something we might want
9301 to look up. */
9302 new_binding = follow_key (current_binding, key);
9303
9304 /* If KEY wasn't bound, we'll try some fallbacks. */
9305 if (!NILP (new_binding))
9306 /* This is needed for the following scenario:
9307 event 0: a down-event that gets dropped by calling replay_key.
9308 event 1: some normal prefix like C-h.
9309 After event 0, first_unbound is 0, after event 1 indec.start,
9310 fkey.start, and keytran.start are all 1, so when we see that
9311 C-h is bound, we need to update first_unbound. */
9312 first_unbound = max (t + 1, first_unbound);
9313 else
9314 {
9315 Lisp_Object head;
9316
9317 /* Remember the position to put an upper bound on indec.start. */
9318 first_unbound = min (t, first_unbound);
9319
9320 head = EVENT_HEAD (key);
9321
9322 if (SYMBOLP (head))
9323 {
9324 Lisp_Object breakdown;
9325 int modifiers;
9326
9327 breakdown = parse_modifiers (head);
9328 modifiers = XINT (XCAR (XCDR (breakdown)));
9329 /* Attempt to reduce an unbound mouse event to a simpler
9330 event that is bound:
9331 Drags reduce to clicks.
9332 Double-clicks reduce to clicks.
9333 Triple-clicks reduce to double-clicks, then to clicks.
9334 Up/Down-clicks are eliminated.
9335 Double-downs reduce to downs, then are eliminated.
9336 Triple-downs reduce to double-downs, then to downs,
9337 then are eliminated. */
9338 if (modifiers & (up_modifier | down_modifier
9339 | drag_modifier
9340 | double_modifier | triple_modifier))
9341 {
9342 while (modifiers & (up_modifier | down_modifier
9343 | drag_modifier
9344 | double_modifier | triple_modifier))
9345 {
9346 Lisp_Object new_head, new_click;
9347 if (modifiers & triple_modifier)
9348 modifiers ^= (double_modifier | triple_modifier);
9349 else if (modifiers & double_modifier)
9350 modifiers &= ~double_modifier;
9351 else if (modifiers & drag_modifier)
9352 modifiers &= ~drag_modifier;
9353 else
9354 {
9355 /* Dispose of this `up/down' event by simply jumping
9356 back to replay_key, to get another event.
9357
9358 Note that if this event came from mock input,
9359 then just jumping back to replay_key will just
9360 hand it to us again. So we have to wipe out any
9361 mock input.
9362
9363 We could delete keybuf[t] and shift everything
9364 after that to the left by one spot, but we'd also
9365 have to fix up any variable that points into
9366 keybuf, and shifting isn't really necessary
9367 anyway.
9368
9369 Adding prefixes for non-textual mouse clicks
9370 creates two characters of mock input, and both
9371 must be thrown away. If we're only looking at
9372 the prefix now, we can just jump back to
9373 replay_key. On the other hand, if we've already
9374 processed the prefix, and now the actual click
9375 itself is giving us trouble, then we've lost the
9376 state of the keymaps we want to backtrack to, and
9377 we need to replay the whole sequence to rebuild
9378 it.
9379
9380 Beyond that, only function key expansion could
9381 create more than two keys, but that should never
9382 generate mouse events, so it's okay to zero
9383 mock_input in that case too.
9384
9385 FIXME: The above paragraph seems just plain
9386 wrong, if you consider things like
9387 xterm-mouse-mode. -stef
9388
9389 Isn't this just the most wonderful code ever? */
9390
9391 /* If mock_input > t + 1, the above simplification
9392 will actually end up dropping keys on the floor.
9393 This is probably OK for now, but even
9394 if mock_input <= t + 1, we need to adjust indec,
9395 fkey, and keytran.
9396 Typical case [header-line down-mouse-N]:
9397 mock_input = 2, t = 1, fkey.end = 1,
9398 last_real_key_start = 0. */
9399 if (indec.end > last_real_key_start)
9400 {
9401 indec.end = indec.start
9402 = min (last_real_key_start, indec.start);
9403 indec.map = indec.parent;
9404 if (fkey.end > last_real_key_start)
9405 {
9406 fkey.end = fkey.start
9407 = min (last_real_key_start, fkey.start);
9408 fkey.map = fkey.parent;
9409 if (keytran.end > last_real_key_start)
9410 {
9411 keytran.end = keytran.start
9412 = min (last_real_key_start, keytran.start);
9413 keytran.map = keytran.parent;
9414 }
9415 }
9416 }
9417 if (t == last_real_key_start)
9418 {
9419 mock_input = 0;
9420 goto replay_key;
9421 }
9422 else
9423 {
9424 mock_input = last_real_key_start;
9425 goto replay_sequence;
9426 }
9427 }
9428
9429 new_head
9430 = apply_modifiers (modifiers, XCAR (breakdown));
9431 new_click = list2 (new_head, EVENT_START (key));
9432
9433 /* Look for a binding for this new key. */
9434 new_binding = follow_key (current_binding, new_click);
9435
9436 /* If that click is bound, go for it. */
9437 if (!NILP (new_binding))
9438 {
9439 current_binding = new_binding;
9440 key = new_click;
9441 break;
9442 }
9443 /* Otherwise, we'll leave key set to the drag event. */
9444 }
9445 }
9446 }
9447 }
9448 current_binding = new_binding;
9449
9450 keybuf[t++] = key;
9451 /* Normally, last_nonmenu_event gets the previous key we read.
9452 But when a mouse popup menu is being used,
9453 we don't update last_nonmenu_event; it continues to hold the mouse
9454 event that preceded the first level of menu. */
9455 if (!used_mouse_menu)
9456 last_nonmenu_event = key;
9457
9458 /* Record what part of this_command_keys is the current key sequence. */
9459 this_single_command_key_start = this_command_key_count - t;
9460 /* When 'input-method-function' called above causes events to be
9461 put on 'unread-post-input-method-events', and as result
9462 'reread' is set to 'true', the value of 't' can become larger
9463 than 'this_command_key_count', because 'add_command_key' is
9464 not called to update 'this_command_key_count'. If this
9465 happens, 'this_single_command_key_start' will become negative
9466 above, and any call to 'this-single-command-keys' will return
9467 a garbled vector. See bug #20223 for one such situation.
9468 Here we force 'this_single_command_key_start' to never become
9469 negative, to avoid that. */
9470 if (this_single_command_key_start < 0)
9471 this_single_command_key_start = 0;
9472
9473 /* Look for this sequence in input-decode-map.
9474 Scan from indec.end until we find a bound suffix. */
9475 while (indec.end < t)
9476 {
9477 bool done;
9478 int diff;
9479
9480 done = keyremap_step (keybuf, bufsize, &indec, max (t, mock_input),
9481 1, &diff, prompt);
9482 if (done)
9483 {
9484 mock_input = diff + max (t, mock_input);
9485 goto replay_sequence;
9486 }
9487 }
9488
9489 if (!KEYMAPP (current_binding)
9490 && !test_undefined (current_binding)
9491 && indec.start >= t)
9492 /* There is a binding and it's not a prefix.
9493 (and it doesn't have any input-decode-map translation pending).
9494 There is thus no function-key in this sequence.
9495 Moving fkey.start is important in this case to allow keytran.start
9496 to go over the sequence before we return (since we keep the
9497 invariant that keytran.end <= fkey.start). */
9498 {
9499 if (fkey.start < t)
9500 (fkey.start = fkey.end = t, fkey.map = fkey.parent);
9501 }
9502 else
9503 /* If the sequence is unbound, see if we can hang a function key
9504 off the end of it. */
9505 /* Continue scan from fkey.end until we find a bound suffix. */
9506 while (fkey.end < indec.start)
9507 {
9508 bool done;
9509 int diff;
9510
9511 done = keyremap_step (keybuf, bufsize, &fkey,
9512 max (t, mock_input),
9513 /* If there's a binding (i.e.
9514 first_binding >= nmaps) we don't want
9515 to apply this function-key-mapping. */
9516 fkey.end + 1 == t
9517 && (test_undefined (current_binding)),
9518 &diff, prompt);
9519 if (done)
9520 {
9521 mock_input = diff + max (t, mock_input);
9522 /* Adjust the input-decode-map counters. */
9523 indec.end += diff;
9524 indec.start += diff;
9525
9526 goto replay_sequence;
9527 }
9528 }
9529
9530 /* Look for this sequence in key-translation-map.
9531 Scan from keytran.end until we find a bound suffix. */
9532 while (keytran.end < fkey.start)
9533 {
9534 bool done;
9535 int diff;
9536
9537 done = keyremap_step (keybuf, bufsize, &keytran, max (t, mock_input),
9538 1, &diff, prompt);
9539 if (done)
9540 {
9541 mock_input = diff + max (t, mock_input);
9542 /* Adjust the function-key-map and input-decode-map counters. */
9543 indec.end += diff;
9544 indec.start += diff;
9545 fkey.end += diff;
9546 fkey.start += diff;
9547
9548 goto replay_sequence;
9549 }
9550 }
9551
9552 /* If KEY is not defined in any of the keymaps,
9553 and cannot be part of a function key or translation,
9554 and is an upper case letter
9555 use the corresponding lower-case letter instead. */
9556 if (NILP (current_binding)
9557 && /* indec.start >= t && fkey.start >= t && */ keytran.start >= t
9558 && INTEGERP (key)
9559 && ((CHARACTERP (make_number (XINT (key) & ~CHAR_MODIFIER_MASK))
9560 && uppercasep (XINT (key) & ~CHAR_MODIFIER_MASK))
9561 || (XINT (key) & shift_modifier)))
9562 {
9563 Lisp_Object new_key;
9564
9565 original_uppercase = key;
9566 original_uppercase_position = t - 1;
9567
9568 if (XINT (key) & shift_modifier)
9569 XSETINT (new_key, XINT (key) & ~shift_modifier);
9570 else
9571 XSETINT (new_key, (downcase (XINT (key) & ~CHAR_MODIFIER_MASK)
9572 | (XINT (key) & CHAR_MODIFIER_MASK)));
9573
9574 /* We have to do this unconditionally, regardless of whether
9575 the lower-case char is defined in the keymaps, because they
9576 might get translated through function-key-map. */
9577 keybuf[t - 1] = new_key;
9578 mock_input = max (t, mock_input);
9579 shift_translated = true;
9580
9581 goto replay_sequence;
9582 }
9583
9584 if (NILP (current_binding)
9585 && help_char_p (EVENT_HEAD (key)) && t > 1)
9586 {
9587 read_key_sequence_cmd = Vprefix_help_command;
9588 /* The Microsoft C compiler can't handle the goto that
9589 would go here. */
9590 dummyflag = true;
9591 break;
9592 }
9593
9594 /* If KEY is not defined in any of the keymaps,
9595 and cannot be part of a function key or translation,
9596 and is a shifted function key,
9597 use the corresponding unshifted function key instead. */
9598 if (NILP (current_binding)
9599 && /* indec.start >= t && fkey.start >= t && */ keytran.start >= t)
9600 {
9601 Lisp_Object breakdown = parse_modifiers (key);
9602 int modifiers
9603 = CONSP (breakdown) ? (XINT (XCAR (XCDR (breakdown)))) : 0;
9604
9605 if (modifiers & shift_modifier
9606 /* Treat uppercase keys as shifted. */
9607 || (INTEGERP (key)
9608 && (KEY_TO_CHAR (key)
9609 < XCHAR_TABLE (BVAR (current_buffer, downcase_table))->header.size)
9610 && uppercasep (KEY_TO_CHAR (key))))
9611 {
9612 Lisp_Object new_key
9613 = (modifiers & shift_modifier
9614 ? apply_modifiers (modifiers & ~shift_modifier,
9615 XCAR (breakdown))
9616 : make_number (downcase (KEY_TO_CHAR (key)) | modifiers));
9617
9618 original_uppercase = key;
9619 original_uppercase_position = t - 1;
9620
9621 /* We have to do this unconditionally, regardless of whether
9622 the lower-case char is defined in the keymaps, because they
9623 might get translated through function-key-map. */
9624 keybuf[t - 1] = new_key;
9625 mock_input = max (t, mock_input);
9626 /* Reset fkey (and consequently keytran) to apply
9627 function-key-map on the result, so that S-backspace is
9628 correctly mapped to DEL (via backspace). OTOH,
9629 input-decode-map doesn't need to go through it again. */
9630 fkey.start = fkey.end = 0;
9631 keytran.start = keytran.end = 0;
9632 shift_translated = true;
9633
9634 goto replay_sequence;
9635 }
9636 }
9637 }
9638 if (!dummyflag)
9639 read_key_sequence_cmd = current_binding;
9640 read_key_sequence_remapped
9641 /* Remap command through active keymaps.
9642 Do the remapping here, before the unbind_to so it uses the keymaps
9643 of the appropriate buffer. */
9644 = SYMBOLP (read_key_sequence_cmd)
9645 ? Fcommand_remapping (read_key_sequence_cmd, Qnil, Qnil)
9646 : Qnil;
9647
9648 unread_switch_frame = delayed_switch_frame;
9649 unbind_to (count, Qnil);
9650
9651 /* Don't downcase the last character if the caller says don't.
9652 Don't downcase it if the result is undefined, either. */
9653 if ((dont_downcase_last || NILP (current_binding))
9654 && t > 0
9655 && t - 1 == original_uppercase_position)
9656 {
9657 keybuf[t - 1] = original_uppercase;
9658 shift_translated = false;
9659 }
9660
9661 if (shift_translated)
9662 Vthis_command_keys_shift_translated = Qt;
9663
9664 /* Occasionally we fabricate events, perhaps by expanding something
9665 according to function-key-map, or by adding a prefix symbol to a
9666 mouse click in the scroll bar or modeline. In this cases, return
9667 the entire generated key sequence, even if we hit an unbound
9668 prefix or a definition before the end. This means that you will
9669 be able to push back the event properly, and also means that
9670 read-key-sequence will always return a logical unit.
9671
9672 Better ideas? */
9673 for (; t < mock_input; t++)
9674 add_command_key (keybuf[t]);
9675 echo_update ();
9676
9677 return t;
9678 }
9679
9680 static Lisp_Object
9681 read_key_sequence_vs (Lisp_Object prompt, Lisp_Object continue_echo,
9682 Lisp_Object dont_downcase_last,
9683 Lisp_Object can_return_switch_frame,
9684 Lisp_Object cmd_loop, bool allow_string)
9685 {
9686 Lisp_Object keybuf[30];
9687 int i;
9688 ptrdiff_t count = SPECPDL_INDEX ();
9689
9690 if (!NILP (prompt))
9691 CHECK_STRING (prompt);
9692 QUIT;
9693
9694 specbind (Qinput_method_exit_on_first_char,
9695 (NILP (cmd_loop) ? Qt : Qnil));
9696 specbind (Qinput_method_use_echo_area,
9697 (NILP (cmd_loop) ? Qt : Qnil));
9698
9699 if (NILP (continue_echo))
9700 {
9701 this_command_key_count = 0;
9702 this_single_command_key_start = 0;
9703 }
9704
9705 #ifdef HAVE_WINDOW_SYSTEM
9706 if (display_hourglass_p)
9707 cancel_hourglass ();
9708 #endif
9709
9710 i = read_key_sequence (keybuf, ARRAYELTS (keybuf),
9711 prompt, ! NILP (dont_downcase_last),
9712 ! NILP (can_return_switch_frame), 0, 0);
9713
9714 #if 0 /* The following is fine for code reading a key sequence and
9715 then proceeding with a lengthy computation, but it's not good
9716 for code reading keys in a loop, like an input method. */
9717 #ifdef HAVE_WINDOW_SYSTEM
9718 if (display_hourglass_p)
9719 start_hourglass ();
9720 #endif
9721 #endif
9722
9723 if (i == -1)
9724 {
9725 Vquit_flag = Qt;
9726 QUIT;
9727 }
9728
9729 return unbind_to (count,
9730 ((allow_string ? make_event_array : Fvector)
9731 (i, keybuf)));
9732 }
9733
9734 DEFUN ("read-key-sequence", Fread_key_sequence, Sread_key_sequence, 1, 5, 0,
9735 doc: /* Read a sequence of keystrokes and return as a string or vector.
9736 The sequence is sufficient to specify a non-prefix command in the
9737 current local and global maps.
9738
9739 First arg PROMPT is a prompt string. If nil, do not prompt specially.
9740 Second (optional) arg CONTINUE-ECHO, if non-nil, means this key echos
9741 as a continuation of the previous key.
9742
9743 The third (optional) arg DONT-DOWNCASE-LAST, if non-nil, means do not
9744 convert the last event to lower case. (Normally any upper case event
9745 is converted to lower case if the original event is undefined and the lower
9746 case equivalent is defined.) A non-nil value is appropriate for reading
9747 a key sequence to be defined.
9748
9749 A C-g typed while in this function is treated like any other character,
9750 and `quit-flag' is not set.
9751
9752 If the key sequence starts with a mouse click, then the sequence is read
9753 using the keymaps of the buffer of the window clicked in, not the buffer
9754 of the selected window as normal.
9755
9756 `read-key-sequence' drops unbound button-down events, since you normally
9757 only care about the click or drag events which follow them. If a drag
9758 or multi-click event is unbound, but the corresponding click event would
9759 be bound, `read-key-sequence' turns the event into a click event at the
9760 drag's starting position. This means that you don't have to distinguish
9761 between click and drag, double, or triple events unless you want to.
9762
9763 `read-key-sequence' prefixes mouse events on mode lines, the vertical
9764 lines separating windows, and scroll bars with imaginary keys
9765 `mode-line', `vertical-line', and `vertical-scroll-bar'.
9766
9767 Optional fourth argument CAN-RETURN-SWITCH-FRAME non-nil means that this
9768 function will process a switch-frame event if the user switches frames
9769 before typing anything. If the user switches frames in the middle of a
9770 key sequence, or at the start of the sequence but CAN-RETURN-SWITCH-FRAME
9771 is nil, then the event will be put off until after the current key sequence.
9772
9773 `read-key-sequence' checks `function-key-map' for function key
9774 sequences, where they wouldn't conflict with ordinary bindings. See
9775 `function-key-map' for more details.
9776
9777 The optional fifth argument CMD-LOOP, if non-nil, means
9778 that this key sequence is being read by something that will
9779 read commands one after another. It should be nil if the caller
9780 will read just one key sequence. */)
9781 (Lisp_Object prompt, Lisp_Object continue_echo, Lisp_Object dont_downcase_last, Lisp_Object can_return_switch_frame, Lisp_Object cmd_loop)
9782 {
9783 return read_key_sequence_vs (prompt, continue_echo, dont_downcase_last,
9784 can_return_switch_frame, cmd_loop, true);
9785 }
9786
9787 DEFUN ("read-key-sequence-vector", Fread_key_sequence_vector,
9788 Sread_key_sequence_vector, 1, 5, 0,
9789 doc: /* Like `read-key-sequence' but always return a vector. */)
9790 (Lisp_Object prompt, Lisp_Object continue_echo, Lisp_Object dont_downcase_last, Lisp_Object can_return_switch_frame, Lisp_Object cmd_loop)
9791 {
9792 return read_key_sequence_vs (prompt, continue_echo, dont_downcase_last,
9793 can_return_switch_frame, cmd_loop, false);
9794 }
9795 \f
9796 /* Return true if input events are pending. */
9797
9798 bool
9799 detect_input_pending (void)
9800 {
9801 return input_pending || get_input_pending (0);
9802 }
9803
9804 /* Return true if input events other than mouse movements are
9805 pending. */
9806
9807 bool
9808 detect_input_pending_ignore_squeezables (void)
9809 {
9810 return input_pending || get_input_pending (READABLE_EVENTS_IGNORE_SQUEEZABLES);
9811 }
9812
9813 /* Return true if input events are pending, and run any pending timers. */
9814
9815 bool
9816 detect_input_pending_run_timers (bool do_display)
9817 {
9818 unsigned old_timers_run = timers_run;
9819
9820 if (!input_pending)
9821 get_input_pending (READABLE_EVENTS_DO_TIMERS_NOW);
9822
9823 if (old_timers_run != timers_run && do_display)
9824 redisplay_preserve_echo_area (8);
9825
9826 return input_pending;
9827 }
9828
9829 /* This is called in some cases before a possible quit.
9830 It cases the next call to detect_input_pending to recompute input_pending.
9831 So calling this function unnecessarily can't do any harm. */
9832
9833 void
9834 clear_input_pending (void)
9835 {
9836 input_pending = false;
9837 }
9838
9839 /* Return true if there are pending requeued events.
9840 This isn't used yet. The hope is to make wait_reading_process_output
9841 call it, and return if it runs Lisp code that unreads something.
9842 The problem is, kbd_buffer_get_event needs to be fixed to know what
9843 to do in that case. It isn't trivial. */
9844
9845 bool
9846 requeued_events_pending_p (void)
9847 {
9848 return (!NILP (Vunread_command_events));
9849 }
9850
9851 DEFUN ("input-pending-p", Finput_pending_p, Sinput_pending_p, 0, 1, 0,
9852 doc: /* Return t if command input is currently available with no wait.
9853 Actually, the value is nil only if we can be sure that no input is available;
9854 if there is a doubt, the value is t.
9855
9856 If CHECK-TIMERS is non-nil, timers that are ready to run will do so. */)
9857 (Lisp_Object check_timers)
9858 {
9859 if (!NILP (Vunread_command_events)
9860 || !NILP (Vunread_post_input_method_events)
9861 || !NILP (Vunread_input_method_events))
9862 return (Qt);
9863
9864 /* Process non-user-visible events (Bug#10195). */
9865 process_special_events ();
9866
9867 return (get_input_pending ((NILP (check_timers)
9868 ? 0 : READABLE_EVENTS_DO_TIMERS_NOW)
9869 | READABLE_EVENTS_FILTER_EVENTS)
9870 ? Qt : Qnil);
9871 }
9872
9873 DEFUN ("recent-keys", Frecent_keys, Srecent_keys, 0, 1, 0,
9874 doc: /* Return vector of last few events, not counting those from keyboard macros.
9875 If INCLUDE-CMDS is non-nil, include the commands that were run,
9876 represented as events of the form (nil . COMMAND). */)
9877 (Lisp_Object include_cmds)
9878 {
9879 bool cmds = !NILP (include_cmds);
9880
9881 if (!total_keys
9882 || (cmds && total_keys < NUM_RECENT_KEYS))
9883 return Fvector (total_keys,
9884 XVECTOR (recent_keys)->contents);
9885 else
9886 {
9887 Lisp_Object es = Qnil;
9888 int i = (total_keys < NUM_RECENT_KEYS
9889 ? 0 : recent_keys_index);
9890 eassert (recent_keys_index < NUM_RECENT_KEYS);
9891 do
9892 {
9893 Lisp_Object e = AREF (recent_keys, i);
9894 if (cmds || !CONSP (e) || !NILP (XCAR (e)))
9895 es = Fcons (e, es);
9896 if (++i >= NUM_RECENT_KEYS)
9897 i = 0;
9898 } while (i != recent_keys_index);
9899 es = Fnreverse (es);
9900 return Fvconcat (1, &es);
9901 }
9902 }
9903
9904 DEFUN ("this-command-keys", Fthis_command_keys, Sthis_command_keys, 0, 0, 0,
9905 doc: /* Return the key sequence that invoked this command.
9906 However, if the command has called `read-key-sequence', it returns
9907 the last key sequence that has been read.
9908 The value is a string or a vector.
9909
9910 See also `this-command-keys-vector'. */)
9911 (void)
9912 {
9913 return make_event_array (this_command_key_count,
9914 XVECTOR (this_command_keys)->contents);
9915 }
9916
9917 DEFUN ("this-command-keys-vector", Fthis_command_keys_vector, Sthis_command_keys_vector, 0, 0, 0,
9918 doc: /* Return the key sequence that invoked this command, as a vector.
9919 However, if the command has called `read-key-sequence', it returns
9920 the last key sequence that has been read.
9921
9922 See also `this-command-keys'. */)
9923 (void)
9924 {
9925 return Fvector (this_command_key_count,
9926 XVECTOR (this_command_keys)->contents);
9927 }
9928
9929 DEFUN ("this-single-command-keys", Fthis_single_command_keys,
9930 Sthis_single_command_keys, 0, 0, 0,
9931 doc: /* Return the key sequence that invoked this command.
9932 More generally, it returns the last key sequence read, either by
9933 the command loop or by `read-key-sequence'.
9934 Unlike `this-command-keys', this function's value
9935 does not include prefix arguments.
9936 The value is always a vector. */)
9937 (void)
9938 {
9939 return Fvector (this_command_key_count
9940 - this_single_command_key_start,
9941 (XVECTOR (this_command_keys)->contents
9942 + this_single_command_key_start));
9943 }
9944
9945 DEFUN ("this-single-command-raw-keys", Fthis_single_command_raw_keys,
9946 Sthis_single_command_raw_keys, 0, 0, 0,
9947 doc: /* Return the raw events that were read for this command.
9948 More generally, it returns the last key sequence read, either by
9949 the command loop or by `read-key-sequence'.
9950 Unlike `this-single-command-keys', this function's value
9951 shows the events before all translations (except for input methods).
9952 The value is always a vector. */)
9953 (void)
9954 {
9955 return Fvector (raw_keybuf_count, XVECTOR (raw_keybuf)->contents);
9956 }
9957
9958 DEFUN ("clear-this-command-keys", Fclear_this_command_keys,
9959 Sclear_this_command_keys, 0, 1, 0,
9960 doc: /* Clear out the vector that `this-command-keys' returns.
9961 Also clear the record of the last 100 events, unless optional arg
9962 KEEP-RECORD is non-nil. */)
9963 (Lisp_Object keep_record)
9964 {
9965 int i;
9966
9967 this_command_key_count = 0;
9968
9969 if (NILP (keep_record))
9970 {
9971 for (i = 0; i < ASIZE (recent_keys); ++i)
9972 ASET (recent_keys, i, Qnil);
9973 total_keys = 0;
9974 recent_keys_index = 0;
9975 }
9976 return Qnil;
9977 }
9978
9979 DEFUN ("recursion-depth", Frecursion_depth, Srecursion_depth, 0, 0, 0,
9980 doc: /* Return the current depth in recursive edits. */)
9981 (void)
9982 {
9983 Lisp_Object temp;
9984 /* Wrap around reliably on integer overflow. */
9985 EMACS_INT sum = (command_loop_level & INTMASK) + (minibuf_level & INTMASK);
9986 XSETINT (temp, sum);
9987 return temp;
9988 }
9989
9990 DEFUN ("open-dribble-file", Fopen_dribble_file, Sopen_dribble_file, 1, 1,
9991 "FOpen dribble file: ",
9992 doc: /* Start writing all keyboard characters to a dribble file called FILE.
9993 If FILE is nil, close any open dribble file.
9994 The file will be closed when Emacs exits.
9995
9996 Be aware that this records ALL characters you type!
9997 This may include sensitive information such as passwords. */)
9998 (Lisp_Object file)
9999 {
10000 if (dribble)
10001 {
10002 block_input ();
10003 fclose (dribble);
10004 unblock_input ();
10005 dribble = 0;
10006 }
10007 if (!NILP (file))
10008 {
10009 int fd;
10010 Lisp_Object encfile;
10011
10012 file = Fexpand_file_name (file, Qnil);
10013 encfile = ENCODE_FILE (file);
10014 fd = emacs_open (SSDATA (encfile), O_WRONLY | O_CREAT | O_EXCL, 0600);
10015 if (fd < 0 && errno == EEXIST && unlink (SSDATA (encfile)) == 0)
10016 fd = emacs_open (SSDATA (encfile), O_WRONLY | O_CREAT | O_EXCL, 0600);
10017 dribble = fd < 0 ? 0 : fdopen (fd, "w");
10018 if (dribble == 0)
10019 report_file_error ("Opening dribble", file);
10020 }
10021 return Qnil;
10022 }
10023
10024 DEFUN ("discard-input", Fdiscard_input, Sdiscard_input, 0, 0, 0,
10025 doc: /* Discard the contents of the terminal input buffer.
10026 Also end any kbd macro being defined. */)
10027 (void)
10028 {
10029 if (!NILP (KVAR (current_kboard, defining_kbd_macro)))
10030 {
10031 /* Discard the last command from the macro. */
10032 Fcancel_kbd_macro_events ();
10033 end_kbd_macro ();
10034 }
10035
10036 Vunread_command_events = Qnil;
10037
10038 discard_tty_input ();
10039
10040 kbd_fetch_ptr = kbd_store_ptr;
10041 input_pending = false;
10042
10043 return Qnil;
10044 }
10045 \f
10046 DEFUN ("suspend-emacs", Fsuspend_emacs, Ssuspend_emacs, 0, 1, "",
10047 doc: /* Stop Emacs and return to superior process. You can resume later.
10048 If `cannot-suspend' is non-nil, or if the system doesn't support job
10049 control, run a subshell instead.
10050
10051 If optional arg STUFFSTRING is non-nil, its characters are stuffed
10052 to be read as terminal input by Emacs's parent, after suspension.
10053
10054 Before suspending, run the normal hook `suspend-hook'.
10055 After resumption run the normal hook `suspend-resume-hook'.
10056
10057 Some operating systems cannot stop the Emacs process and resume it later.
10058 On such systems, Emacs starts a subshell instead of suspending. */)
10059 (Lisp_Object stuffstring)
10060 {
10061 ptrdiff_t count = SPECPDL_INDEX ();
10062 int old_height, old_width;
10063 int width, height;
10064
10065 if (tty_list && tty_list->next)
10066 error ("There are other tty frames open; close them before suspending Emacs");
10067
10068 if (!NILP (stuffstring))
10069 CHECK_STRING (stuffstring);
10070
10071 run_hook (intern ("suspend-hook"));
10072
10073 get_tty_size (fileno (CURTTY ()->input), &old_width, &old_height);
10074 reset_all_sys_modes ();
10075 /* sys_suspend can get an error if it tries to fork a subshell
10076 and the system resources aren't available for that. */
10077 record_unwind_protect_void (init_all_sys_modes);
10078 stuff_buffered_input (stuffstring);
10079 if (cannot_suspend)
10080 sys_subshell ();
10081 else
10082 sys_suspend ();
10083 unbind_to (count, Qnil);
10084
10085 /* Check if terminal/window size has changed.
10086 Note that this is not useful when we are running directly
10087 with a window system; but suspend should be disabled in that case. */
10088 get_tty_size (fileno (CURTTY ()->input), &width, &height);
10089 if (width != old_width || height != old_height)
10090 change_frame_size (SELECTED_FRAME (), width,
10091 height - FRAME_MENU_BAR_LINES (SELECTED_FRAME ()),
10092 0, 0, 0, 0);
10093
10094 run_hook (intern ("suspend-resume-hook"));
10095
10096 return Qnil;
10097 }
10098
10099 /* If STUFFSTRING is a string, stuff its contents as pending terminal input.
10100 Then in any case stuff anything Emacs has read ahead and not used. */
10101
10102 void
10103 stuff_buffered_input (Lisp_Object stuffstring)
10104 {
10105 #ifdef SIGTSTP /* stuff_char is defined if SIGTSTP. */
10106 register unsigned char *p;
10107
10108 if (STRINGP (stuffstring))
10109 {
10110 register ptrdiff_t count;
10111
10112 p = SDATA (stuffstring);
10113 count = SBYTES (stuffstring);
10114 while (count-- > 0)
10115 stuff_char (*p++);
10116 stuff_char ('\n');
10117 }
10118
10119 /* Anything we have read ahead, put back for the shell to read. */
10120 /* ?? What should this do when we have multiple keyboards??
10121 Should we ignore anything that was typed in at the "wrong" kboard?
10122
10123 rms: we should stuff everything back into the kboard
10124 it came from. */
10125 for (; kbd_fetch_ptr != kbd_store_ptr; kbd_fetch_ptr++)
10126 {
10127
10128 if (kbd_fetch_ptr == kbd_buffer + KBD_BUFFER_SIZE)
10129 kbd_fetch_ptr = kbd_buffer;
10130 if (kbd_fetch_ptr->kind == ASCII_KEYSTROKE_EVENT)
10131 stuff_char (kbd_fetch_ptr->ie.code);
10132
10133 clear_event (kbd_fetch_ptr);
10134 }
10135
10136 input_pending = false;
10137 #endif /* SIGTSTP */
10138 }
10139 \f
10140 void
10141 set_waiting_for_input (struct timespec *time_to_clear)
10142 {
10143 input_available_clear_time = time_to_clear;
10144
10145 /* Tell handle_interrupt to throw back to read_char, */
10146 waiting_for_input = true;
10147
10148 /* If handle_interrupt was called before and buffered a C-g,
10149 make it run again now, to avoid timing error. */
10150 if (!NILP (Vquit_flag))
10151 quit_throw_to_read_char (0);
10152 }
10153
10154 void
10155 clear_waiting_for_input (void)
10156 {
10157 /* Tell handle_interrupt not to throw back to read_char, */
10158 waiting_for_input = false;
10159 input_available_clear_time = 0;
10160 }
10161
10162 /* The SIGINT handler.
10163
10164 If we have a frame on the controlling tty, we assume that the
10165 SIGINT was generated by C-g, so we call handle_interrupt.
10166 Otherwise, tell QUIT to kill Emacs. */
10167
10168 static void
10169 handle_interrupt_signal (int sig)
10170 {
10171 /* See if we have an active terminal on our controlling tty. */
10172 struct terminal *terminal = get_named_terminal ("/dev/tty");
10173 if (!terminal)
10174 {
10175 /* If there are no frames there, let's pretend that we are a
10176 well-behaving UN*X program and quit. We must not call Lisp
10177 in a signal handler, so tell QUIT to exit when it is
10178 safe. */
10179 Vquit_flag = Qkill_emacs;
10180 }
10181 else
10182 {
10183 /* Otherwise, the SIGINT was probably generated by C-g. */
10184
10185 /* Set internal_last_event_frame to the top frame of the
10186 controlling tty, if we have a frame there. We disable the
10187 interrupt key on secondary ttys, so the SIGINT must have come
10188 from the controlling tty. */
10189 internal_last_event_frame = terminal->display_info.tty->top_frame;
10190
10191 handle_interrupt (1);
10192 }
10193 }
10194
10195 static void
10196 deliver_interrupt_signal (int sig)
10197 {
10198 deliver_process_signal (sig, handle_interrupt_signal);
10199 }
10200
10201
10202 /* If Emacs is stuck because `inhibit-quit' is true, then keep track
10203 of the number of times C-g has been requested. If C-g is pressed
10204 enough times, then quit anyway. See bug#6585. */
10205 static int volatile force_quit_count;
10206
10207 /* This routine is called at interrupt level in response to C-g.
10208
10209 It is called from the SIGINT handler or kbd_buffer_store_event.
10210
10211 If `waiting_for_input' is non zero, then unless `echoing' is
10212 nonzero, immediately throw back to read_char.
10213
10214 Otherwise it sets the Lisp variable quit-flag not-nil. This causes
10215 eval to throw, when it gets a chance. If quit-flag is already
10216 non-nil, it stops the job right away. */
10217
10218 static void
10219 handle_interrupt (bool in_signal_handler)
10220 {
10221 char c;
10222
10223 cancel_echoing ();
10224
10225 /* XXX This code needs to be revised for multi-tty support. */
10226 if (!NILP (Vquit_flag) && get_named_terminal ("/dev/tty"))
10227 {
10228 if (! in_signal_handler)
10229 {
10230 /* If SIGINT isn't blocked, don't let us be interrupted by
10231 a SIGINT. It might be harmful due to non-reentrancy
10232 in I/O functions. */
10233 sigset_t blocked;
10234 sigemptyset (&blocked);
10235 sigaddset (&blocked, SIGINT);
10236 pthread_sigmask (SIG_BLOCK, &blocked, 0);
10237 }
10238
10239 fflush (stdout);
10240 reset_all_sys_modes ();
10241
10242 #ifdef SIGTSTP
10243 /*
10244 * On systems which can suspend the current process and return to the original
10245 * shell, this command causes the user to end up back at the shell.
10246 * The "Auto-save" and "Abort" questions are not asked until
10247 * the user elects to return to emacs, at which point he can save the current
10248 * job and either dump core or continue.
10249 */
10250 sys_suspend ();
10251 #else
10252 /* Perhaps should really fork an inferior shell?
10253 But that would not provide any way to get back
10254 to the original shell, ever. */
10255 printf ("No support for stopping a process on this operating system;\n");
10256 printf ("you can continue or abort.\n");
10257 #endif /* not SIGTSTP */
10258 #ifdef MSDOS
10259 /* We must remain inside the screen area when the internal terminal
10260 is used. Note that [Enter] is not echoed by dos. */
10261 cursor_to (SELECTED_FRAME (), 0, 0);
10262 #endif
10263 /* It doesn't work to autosave while GC is in progress;
10264 the code used for auto-saving doesn't cope with the mark bit. */
10265 if (!gc_in_progress)
10266 {
10267 printf ("Auto-save? (y or n) ");
10268 fflush (stdout);
10269 if (((c = getchar ()) & ~040) == 'Y')
10270 {
10271 Fdo_auto_save (Qt, Qnil);
10272 #ifdef MSDOS
10273 printf ("\r\nAuto-save done");
10274 #else /* not MSDOS */
10275 printf ("Auto-save done\n");
10276 #endif /* not MSDOS */
10277 }
10278 while (c != '\n') c = getchar ();
10279 }
10280 else
10281 {
10282 /* During GC, it must be safe to reenable quitting again. */
10283 Vinhibit_quit = Qnil;
10284 #ifdef MSDOS
10285 printf ("\r\n");
10286 #endif /* not MSDOS */
10287 printf ("Garbage collection in progress; cannot auto-save now\r\n");
10288 printf ("but will instead do a real quit after garbage collection ends\r\n");
10289 fflush (stdout);
10290 }
10291
10292 #ifdef MSDOS
10293 printf ("\r\nAbort? (y or n) ");
10294 #else /* not MSDOS */
10295 printf ("Abort (and dump core)? (y or n) ");
10296 #endif /* not MSDOS */
10297 fflush (stdout);
10298 if (((c = getchar ()) & ~040) == 'Y')
10299 emacs_abort ();
10300 while (c != '\n') c = getchar ();
10301 #ifdef MSDOS
10302 printf ("\r\nContinuing...\r\n");
10303 #else /* not MSDOS */
10304 printf ("Continuing...\n");
10305 #endif /* not MSDOS */
10306 fflush (stdout);
10307 init_all_sys_modes ();
10308 }
10309 else
10310 {
10311 /* If executing a function that wants to be interrupted out of
10312 and the user has not deferred quitting by binding `inhibit-quit'
10313 then quit right away. */
10314 if (immediate_quit && NILP (Vinhibit_quit))
10315 {
10316 struct gl_state_s saved;
10317
10318 immediate_quit = false;
10319 pthread_sigmask (SIG_SETMASK, &empty_mask, 0);
10320 saved = gl_state;
10321 Fsignal (Qquit, Qnil);
10322 gl_state = saved;
10323 }
10324 else
10325 { /* Else request quit when it's safe. */
10326 int count = NILP (Vquit_flag) ? 1 : force_quit_count + 1;
10327 force_quit_count = count;
10328 if (count == 3)
10329 {
10330 immediate_quit = true;
10331 Vinhibit_quit = Qnil;
10332 }
10333 Vquit_flag = Qt;
10334 }
10335 }
10336
10337 pthread_sigmask (SIG_SETMASK, &empty_mask, 0);
10338
10339 /* TODO: The longjmp in this call throws the NS event loop integration off,
10340 and it seems to do fine without this. Probably some attention
10341 needs to be paid to the setting of waiting_for_input in
10342 wait_reading_process_output() under HAVE_NS because of the call
10343 to ns_select there (needed because otherwise events aren't picked up
10344 outside of polling since we don't get SIGIO like X and we don't have a
10345 separate event loop thread like W32. */
10346 #ifndef HAVE_NS
10347 if (waiting_for_input && !echoing)
10348 quit_throw_to_read_char (in_signal_handler);
10349 #endif
10350 }
10351
10352 /* Handle a C-g by making read_char return C-g. */
10353
10354 static void
10355 quit_throw_to_read_char (bool from_signal)
10356 {
10357 /* When not called from a signal handler it is safe to call
10358 Lisp. */
10359 if (!from_signal && EQ (Vquit_flag, Qkill_emacs))
10360 Fkill_emacs (Qnil);
10361
10362 /* Prevent another signal from doing this before we finish. */
10363 clear_waiting_for_input ();
10364 input_pending = false;
10365
10366 Vunread_command_events = Qnil;
10367
10368 if (FRAMEP (internal_last_event_frame)
10369 && !EQ (internal_last_event_frame, selected_frame))
10370 do_switch_frame (make_lispy_switch_frame (internal_last_event_frame),
10371 0, 0, Qnil);
10372
10373 sys_longjmp (getcjmp, 1);
10374 }
10375 \f
10376 DEFUN ("set-input-interrupt-mode", Fset_input_interrupt_mode,
10377 Sset_input_interrupt_mode, 1, 1, 0,
10378 doc: /* Set interrupt mode of reading keyboard input.
10379 If INTERRUPT is non-nil, Emacs will use input interrupts;
10380 otherwise Emacs uses CBREAK mode.
10381
10382 See also `current-input-mode'. */)
10383 (Lisp_Object interrupt)
10384 {
10385 bool new_interrupt_input;
10386 #ifdef USABLE_SIGIO
10387 #ifdef HAVE_X_WINDOWS
10388 if (x_display_list != NULL)
10389 {
10390 /* When using X, don't give the user a real choice,
10391 because we haven't implemented the mechanisms to support it. */
10392 new_interrupt_input = true;
10393 }
10394 else
10395 #endif /* HAVE_X_WINDOWS */
10396 new_interrupt_input = !NILP (interrupt);
10397 #else /* not USABLE_SIGIO */
10398 new_interrupt_input = false;
10399 #endif /* not USABLE_SIGIO */
10400
10401 if (new_interrupt_input != interrupt_input)
10402 {
10403 #ifdef POLL_FOR_INPUT
10404 stop_polling ();
10405 #endif
10406 #ifndef DOS_NT
10407 /* this causes startup screen to be restored and messes with the mouse */
10408 reset_all_sys_modes ();
10409 interrupt_input = new_interrupt_input;
10410 init_all_sys_modes ();
10411 #else
10412 interrupt_input = new_interrupt_input;
10413 #endif
10414
10415 #ifdef POLL_FOR_INPUT
10416 poll_suppress_count = 1;
10417 start_polling ();
10418 #endif
10419 }
10420 return Qnil;
10421 }
10422
10423 DEFUN ("set-output-flow-control", Fset_output_flow_control, Sset_output_flow_control, 1, 2, 0,
10424 doc: /* Enable or disable ^S/^Q flow control for output to TERMINAL.
10425 If FLOW is non-nil, flow control is enabled and you cannot use C-s or
10426 C-q in key sequences.
10427
10428 This setting only has an effect on tty terminals and only when
10429 Emacs reads input in CBREAK mode; see `set-input-interrupt-mode'.
10430
10431 See also `current-input-mode'. */)
10432 (Lisp_Object flow, Lisp_Object terminal)
10433 {
10434 struct terminal *t = decode_tty_terminal (terminal);
10435 struct tty_display_info *tty;
10436
10437 if (!t)
10438 return Qnil;
10439 tty = t->display_info.tty;
10440
10441 if (tty->flow_control != !NILP (flow))
10442 {
10443 #ifndef DOS_NT
10444 /* This causes startup screen to be restored and messes with the mouse. */
10445 reset_sys_modes (tty);
10446 #endif
10447
10448 tty->flow_control = !NILP (flow);
10449
10450 #ifndef DOS_NT
10451 init_sys_modes (tty);
10452 #endif
10453 }
10454 return Qnil;
10455 }
10456
10457 DEFUN ("set-input-meta-mode", Fset_input_meta_mode, Sset_input_meta_mode, 1, 2, 0,
10458 doc: /* Enable or disable 8-bit input on TERMINAL.
10459 If META is t, Emacs will accept 8-bit input, and interpret the 8th
10460 bit as the Meta modifier.
10461
10462 If META is nil, Emacs will ignore the top bit, on the assumption it is
10463 parity.
10464
10465 Otherwise, Emacs will accept and pass through 8-bit input without
10466 specially interpreting the top bit.
10467
10468 This setting only has an effect on tty terminal devices.
10469
10470 Optional parameter TERMINAL specifies the tty terminal device to use.
10471 It may be a terminal object, a frame, or nil for the terminal used by
10472 the currently selected frame.
10473
10474 See also `current-input-mode'. */)
10475 (Lisp_Object meta, Lisp_Object terminal)
10476 {
10477 struct terminal *t = decode_tty_terminal (terminal);
10478 struct tty_display_info *tty;
10479 int new_meta;
10480
10481 if (!t)
10482 return Qnil;
10483 tty = t->display_info.tty;
10484
10485 if (NILP (meta))
10486 new_meta = 0;
10487 else if (EQ (meta, Qt))
10488 new_meta = 1;
10489 else
10490 new_meta = 2;
10491
10492 if (tty->meta_key != new_meta)
10493 {
10494 #ifndef DOS_NT
10495 /* this causes startup screen to be restored and messes with the mouse */
10496 reset_sys_modes (tty);
10497 #endif
10498
10499 tty->meta_key = new_meta;
10500
10501 #ifndef DOS_NT
10502 init_sys_modes (tty);
10503 #endif
10504 }
10505 return Qnil;
10506 }
10507
10508 DEFUN ("set-quit-char", Fset_quit_char, Sset_quit_char, 1, 1, 0,
10509 doc: /* Specify character used for quitting.
10510 QUIT must be an ASCII character.
10511
10512 This function only has an effect on the controlling tty of the Emacs
10513 process.
10514
10515 See also `current-input-mode'. */)
10516 (Lisp_Object quit)
10517 {
10518 struct terminal *t = get_named_terminal ("/dev/tty");
10519 struct tty_display_info *tty;
10520
10521 if (!t)
10522 return Qnil;
10523 tty = t->display_info.tty;
10524
10525 if (NILP (quit) || !INTEGERP (quit) || XINT (quit) < 0 || XINT (quit) > 0400)
10526 error ("QUIT must be an ASCII character");
10527
10528 #ifndef DOS_NT
10529 /* this causes startup screen to be restored and messes with the mouse */
10530 reset_sys_modes (tty);
10531 #endif
10532
10533 /* Don't let this value be out of range. */
10534 quit_char = XINT (quit) & (tty->meta_key == 0 ? 0177 : 0377);
10535
10536 #ifndef DOS_NT
10537 init_sys_modes (tty);
10538 #endif
10539
10540 return Qnil;
10541 }
10542
10543 DEFUN ("set-input-mode", Fset_input_mode, Sset_input_mode, 3, 4, 0,
10544 doc: /* Set mode of reading keyboard input.
10545 First arg INTERRUPT non-nil means use input interrupts;
10546 nil means use CBREAK mode.
10547 Second arg FLOW non-nil means use ^S/^Q flow control for output to terminal
10548 (no effect except in CBREAK mode).
10549 Third arg META t means accept 8-bit input (for a Meta key).
10550 META nil means ignore the top bit, on the assumption it is parity.
10551 Otherwise, accept 8-bit input and don't use the top bit for Meta.
10552 Optional fourth arg QUIT if non-nil specifies character to use for quitting.
10553 See also `current-input-mode'. */)
10554 (Lisp_Object interrupt, Lisp_Object flow, Lisp_Object meta, Lisp_Object quit)
10555 {
10556 Fset_input_interrupt_mode (interrupt);
10557 Fset_output_flow_control (flow, Qnil);
10558 Fset_input_meta_mode (meta, Qnil);
10559 if (!NILP (quit))
10560 Fset_quit_char (quit);
10561 return Qnil;
10562 }
10563
10564 DEFUN ("current-input-mode", Fcurrent_input_mode, Scurrent_input_mode, 0, 0, 0,
10565 doc: /* Return information about the way Emacs currently reads keyboard input.
10566 The value is a list of the form (INTERRUPT FLOW META QUIT), where
10567 INTERRUPT is non-nil if Emacs is using interrupt-driven input; if
10568 nil, Emacs is using CBREAK mode.
10569 FLOW is non-nil if Emacs uses ^S/^Q flow control for output to the
10570 terminal; this does not apply if Emacs uses interrupt-driven input.
10571 META is t if accepting 8-bit input with 8th bit as Meta flag.
10572 META nil means ignoring the top bit, on the assumption it is parity.
10573 META is neither t nor nil if accepting 8-bit input and using
10574 all 8 bits as the character code.
10575 QUIT is the character Emacs currently uses to quit.
10576 The elements of this list correspond to the arguments of
10577 `set-input-mode'. */)
10578 (void)
10579 {
10580 struct frame *sf = XFRAME (selected_frame);
10581
10582 Lisp_Object interrupt = interrupt_input ? Qt : Qnil;
10583 Lisp_Object flow, meta;
10584 if (FRAME_TERMCAP_P (sf) || FRAME_MSDOS_P (sf))
10585 {
10586 flow = FRAME_TTY (sf)->flow_control ? Qt : Qnil;
10587 meta = (FRAME_TTY (sf)->meta_key == 2
10588 ? make_number (0)
10589 : (CURTTY ()->meta_key == 1 ? Qt : Qnil));
10590 }
10591 else
10592 {
10593 flow = Qnil;
10594 meta = Qt;
10595 }
10596 Lisp_Object quit = make_number (quit_char);
10597
10598 return list4 (interrupt, flow, meta, quit);
10599 }
10600
10601 DEFUN ("posn-at-x-y", Fposn_at_x_y, Sposn_at_x_y, 2, 4, 0,
10602 doc: /* Return position information for pixel coordinates X and Y.
10603 By default, X and Y are relative to text area of the selected window.
10604 Optional third arg FRAME-OR-WINDOW non-nil specifies frame or window.
10605 If optional fourth arg WHOLE is non-nil, X is relative to the left
10606 edge of the window.
10607
10608 The return value is similar to a mouse click position:
10609 (WINDOW AREA-OR-POS (X . Y) TIMESTAMP OBJECT POS (COL . ROW)
10610 IMAGE (DX . DY) (WIDTH . HEIGHT))
10611 The `posn-' functions access elements of such lists. */)
10612 (Lisp_Object x, Lisp_Object y, Lisp_Object frame_or_window, Lisp_Object whole)
10613 {
10614 CHECK_NUMBER (x);
10615 /* We allow X of -1, for the newline in a R2L line that overflowed
10616 into the left fringe. */
10617 if (XINT (x) != -1)
10618 CHECK_NATNUM (x);
10619 CHECK_NATNUM (y);
10620
10621 if (NILP (frame_or_window))
10622 frame_or_window = selected_window;
10623
10624 if (WINDOWP (frame_or_window))
10625 {
10626 struct window *w = decode_live_window (frame_or_window);
10627
10628 XSETINT (x, (XINT (x)
10629 + WINDOW_LEFT_EDGE_X (w)
10630 + (NILP (whole)
10631 ? window_box_left_offset (w, TEXT_AREA)
10632 : 0)));
10633 XSETINT (y, WINDOW_TO_FRAME_PIXEL_Y (w, XINT (y)));
10634 frame_or_window = w->frame;
10635 }
10636
10637 CHECK_LIVE_FRAME (frame_or_window);
10638
10639 return make_lispy_position (XFRAME (frame_or_window), x, y, 0);
10640 }
10641
10642 DEFUN ("posn-at-point", Fposn_at_point, Sposn_at_point, 0, 2, 0,
10643 doc: /* Return position information for buffer POS in WINDOW.
10644 POS defaults to point in WINDOW; WINDOW defaults to the selected window.
10645
10646 Return nil if position is not visible in window. Otherwise,
10647 the return value is similar to that returned by `event-start' for
10648 a mouse click at the upper left corner of the glyph corresponding
10649 to the given buffer position:
10650 (WINDOW AREA-OR-POS (X . Y) TIMESTAMP OBJECT POS (COL . ROW)
10651 IMAGE (DX . DY) (WIDTH . HEIGHT))
10652 The `posn-' functions access elements of such lists. */)
10653 (Lisp_Object pos, Lisp_Object window)
10654 {
10655 Lisp_Object tem;
10656
10657 if (NILP (window))
10658 window = selected_window;
10659
10660 tem = Fpos_visible_in_window_p (pos, window, Qt);
10661 if (!NILP (tem))
10662 {
10663 Lisp_Object x = XCAR (tem);
10664 Lisp_Object y = XCAR (XCDR (tem));
10665
10666 /* Point invisible due to hscrolling? X can be -1 when a
10667 newline in a R2L line overflows into the left fringe. */
10668 if (XINT (x) < -1)
10669 return Qnil;
10670 tem = Fposn_at_x_y (x, y, window, Qnil);
10671 }
10672
10673 return tem;
10674 }
10675
10676 /* Set up a new kboard object with reasonable initial values.
10677 TYPE is a window system for which this keyboard is used. */
10678
10679 static void
10680 init_kboard (KBOARD *kb, Lisp_Object type)
10681 {
10682 kset_overriding_terminal_local_map (kb, Qnil);
10683 kset_last_command (kb, Qnil);
10684 kset_real_last_command (kb, Qnil);
10685 kset_keyboard_translate_table (kb, Qnil);
10686 kset_last_repeatable_command (kb, Qnil);
10687 kset_prefix_arg (kb, Qnil);
10688 kset_last_prefix_arg (kb, Qnil);
10689 kset_kbd_queue (kb, Qnil);
10690 kb->kbd_queue_has_data = false;
10691 kb->immediate_echo = false;
10692 kset_echo_string (kb, Qnil);
10693 kset_echo_prompt (kb, Qnil);
10694 kb->kbd_macro_buffer = 0;
10695 kb->kbd_macro_bufsize = 0;
10696 kset_defining_kbd_macro (kb, Qnil);
10697 kset_last_kbd_macro (kb, Qnil);
10698 kb->reference_count = 0;
10699 kset_system_key_alist (kb, Qnil);
10700 kset_system_key_syms (kb, Qnil);
10701 kset_window_system (kb, type);
10702 kset_input_decode_map (kb, Fmake_sparse_keymap (Qnil));
10703 kset_local_function_key_map (kb, Fmake_sparse_keymap (Qnil));
10704 Fset_keymap_parent (KVAR (kb, Vlocal_function_key_map), Vfunction_key_map);
10705 kset_default_minibuffer_frame (kb, Qnil);
10706 }
10707
10708 /* Allocate and basically initialize keyboard
10709 object to use with window system TYPE. */
10710
10711 KBOARD *
10712 allocate_kboard (Lisp_Object type)
10713 {
10714 KBOARD *kb = xmalloc (sizeof *kb);
10715
10716 init_kboard (kb, type);
10717 kb->next_kboard = all_kboards;
10718 all_kboards = kb;
10719 return kb;
10720 }
10721
10722 /*
10723 * Destroy the contents of a kboard object, but not the object itself.
10724 * We use this just before deleting it, or if we're going to initialize
10725 * it a second time.
10726 */
10727 static void
10728 wipe_kboard (KBOARD *kb)
10729 {
10730 xfree (kb->kbd_macro_buffer);
10731 }
10732
10733 /* Free KB and memory referenced from it. */
10734
10735 void
10736 delete_kboard (KBOARD *kb)
10737 {
10738 KBOARD **kbp;
10739
10740 for (kbp = &all_kboards; *kbp != kb; kbp = &(*kbp)->next_kboard)
10741 if (*kbp == NULL)
10742 emacs_abort ();
10743 *kbp = kb->next_kboard;
10744
10745 /* Prevent a dangling reference to KB. */
10746 if (kb == current_kboard
10747 && FRAMEP (selected_frame)
10748 && FRAME_LIVE_P (XFRAME (selected_frame)))
10749 {
10750 current_kboard = FRAME_KBOARD (XFRAME (selected_frame));
10751 single_kboard = false;
10752 if (current_kboard == kb)
10753 emacs_abort ();
10754 }
10755
10756 wipe_kboard (kb);
10757 xfree (kb);
10758 }
10759
10760 void
10761 init_keyboard (void)
10762 {
10763 /* This is correct before outermost invocation of the editor loop. */
10764 command_loop_level = -1;
10765 immediate_quit = false;
10766 quit_char = Ctl ('g');
10767 Vunread_command_events = Qnil;
10768 timer_idleness_start_time = invalid_timespec ();
10769 total_keys = 0;
10770 recent_keys_index = 0;
10771 kbd_fetch_ptr = kbd_buffer;
10772 kbd_store_ptr = kbd_buffer;
10773 do_mouse_tracking = Qnil;
10774 input_pending = false;
10775 interrupt_input_blocked = 0;
10776 pending_signals = false;
10777
10778 /* This means that command_loop_1 won't try to select anything the first
10779 time through. */
10780 internal_last_event_frame = Qnil;
10781 Vlast_event_frame = internal_last_event_frame;
10782
10783 current_kboard = initial_kboard;
10784 /* Re-initialize the keyboard again. */
10785 wipe_kboard (current_kboard);
10786 /* A value of nil for Vwindow_system normally means a tty, but we also use
10787 it for the initial terminal since there is no window system there. */
10788 init_kboard (current_kboard, Qnil);
10789
10790 if (!noninteractive)
10791 {
10792 /* Before multi-tty support, these handlers used to be installed
10793 only if the current session was a tty session. Now an Emacs
10794 session may have multiple display types, so we always handle
10795 SIGINT. There is special code in handle_interrupt_signal to exit
10796 Emacs on SIGINT when there are no termcap frames on the
10797 controlling terminal. */
10798 struct sigaction action;
10799 emacs_sigaction_init (&action, deliver_interrupt_signal);
10800 sigaction (SIGINT, &action, 0);
10801 #ifndef DOS_NT
10802 /* For systems with SysV TERMIO, C-g is set up for both SIGINT and
10803 SIGQUIT and we can't tell which one it will give us. */
10804 sigaction (SIGQUIT, &action, 0);
10805 #endif /* not DOS_NT */
10806 }
10807 #ifdef USABLE_SIGIO
10808 if (!noninteractive)
10809 {
10810 struct sigaction action;
10811 emacs_sigaction_init (&action, deliver_input_available_signal);
10812 sigaction (SIGIO, &action, 0);
10813 }
10814 #endif
10815
10816 /* Use interrupt input by default, if it works and noninterrupt input
10817 has deficiencies. */
10818
10819 #ifdef INTERRUPT_INPUT
10820 interrupt_input = 1;
10821 #else
10822 interrupt_input = 0;
10823 #endif
10824
10825 pthread_sigmask (SIG_SETMASK, &empty_mask, 0);
10826 dribble = 0;
10827
10828 if (keyboard_init_hook)
10829 (*keyboard_init_hook) ();
10830
10831 #ifdef POLL_FOR_INPUT
10832 poll_timer = NULL;
10833 poll_suppress_count = 1;
10834 start_polling ();
10835 #endif
10836 }
10837
10838 /* This type's only use is in syms_of_keyboard, to put properties on the
10839 event header symbols. */
10840 struct event_head
10841 {
10842 short var;
10843 short kind;
10844 };
10845
10846 static const struct event_head head_table[] = {
10847 {SYMBOL_INDEX (Qmouse_movement), SYMBOL_INDEX (Qmouse_movement)},
10848 {SYMBOL_INDEX (Qscroll_bar_movement), SYMBOL_INDEX (Qmouse_movement)},
10849
10850 /* Some of the event heads. */
10851 {SYMBOL_INDEX (Qswitch_frame), SYMBOL_INDEX (Qswitch_frame)},
10852
10853 {SYMBOL_INDEX (Qfocus_in), SYMBOL_INDEX (Qfocus_in)},
10854 {SYMBOL_INDEX (Qfocus_out), SYMBOL_INDEX (Qfocus_out)},
10855 {SYMBOL_INDEX (Qdelete_frame), SYMBOL_INDEX (Qdelete_frame)},
10856 {SYMBOL_INDEX (Qiconify_frame), SYMBOL_INDEX (Qiconify_frame)},
10857 {SYMBOL_INDEX (Qmake_frame_visible), SYMBOL_INDEX (Qmake_frame_visible)},
10858 /* `select-window' should be handled just like `switch-frame'
10859 in read_key_sequence. */
10860 {SYMBOL_INDEX (Qselect_window), SYMBOL_INDEX (Qswitch_frame)}
10861 };
10862
10863 void
10864 syms_of_keyboard (void)
10865 {
10866 pending_funcalls = Qnil;
10867 staticpro (&pending_funcalls);
10868
10869 Vlispy_mouse_stem = build_pure_c_string ("mouse");
10870 staticpro (&Vlispy_mouse_stem);
10871
10872 regular_top_level_message = build_pure_c_string ("Back to top level");
10873 #ifdef HAVE_STACK_OVERFLOW_HANDLING
10874 recover_top_level_message
10875 = build_pure_c_string ("Re-entering top level after C stack overflow");
10876 #endif
10877 DEFVAR_LISP ("internal--top-level-message", Vinternal__top_level_message,
10878 doc: /* Message displayed by `normal-top-level'. */);
10879 Vinternal__top_level_message = regular_top_level_message;
10880
10881 /* Tool-bars. */
10882 DEFSYM (QCimage, ":image");
10883 DEFSYM (Qhelp_echo, "help-echo");
10884 DEFSYM (QCrtl, ":rtl");
10885
10886 staticpro (&item_properties);
10887 item_properties = Qnil;
10888
10889 staticpro (&tool_bar_item_properties);
10890 tool_bar_item_properties = Qnil;
10891 staticpro (&tool_bar_items_vector);
10892 tool_bar_items_vector = Qnil;
10893
10894 DEFSYM (Qtimer_event_handler, "timer-event-handler");
10895
10896 /* Non-nil disable property on a command means do not execute it;
10897 call disabled-command-function's value instead. */
10898 DEFSYM (Qdisabled, "disabled");
10899
10900 DEFSYM (Qundefined, "undefined");
10901
10902 /* Hooks to run before and after each command. */
10903 DEFSYM (Qpre_command_hook, "pre-command-hook");
10904 DEFSYM (Qpost_command_hook, "post-command-hook");
10905
10906 DEFSYM (Qundo_auto__add_boundary, "undo-auto--add-boundary");
10907
10908 DEFSYM (Qdeferred_action_function, "deferred-action-function");
10909 DEFSYM (Qdelayed_warnings_hook, "delayed-warnings-hook");
10910 DEFSYM (Qfunction_key, "function-key");
10911
10912 /* The values of Qevent_kind properties. */
10913 DEFSYM (Qmouse_click, "mouse-click");
10914
10915 DEFSYM (Qdrag_n_drop, "drag-n-drop");
10916 DEFSYM (Qsave_session, "save-session");
10917 DEFSYM (Qconfig_changed_event, "config-changed-event");
10918
10919 /* Menu and tool bar item parts. */
10920 DEFSYM (Qmenu_enable, "menu-enable");
10921
10922 #ifdef HAVE_NTGUI
10923 DEFSYM (Qlanguage_change, "language-change");
10924 #endif
10925
10926 #ifdef HAVE_DBUS
10927 DEFSYM (Qdbus_event, "dbus-event");
10928 #endif
10929
10930 #ifdef USE_FILE_NOTIFY
10931 DEFSYM (Qfile_notify, "file-notify");
10932 #endif /* USE_FILE_NOTIFY */
10933
10934 /* Menu and tool bar item parts. */
10935 DEFSYM (QCenable, ":enable");
10936 DEFSYM (QCvisible, ":visible");
10937 DEFSYM (QChelp, ":help");
10938 DEFSYM (QCfilter, ":filter");
10939 DEFSYM (QCbutton, ":button");
10940 DEFSYM (QCkeys, ":keys");
10941 DEFSYM (QCkey_sequence, ":key-sequence");
10942
10943 /* Non-nil disable property on a command means
10944 do not execute it; call disabled-command-function's value instead. */
10945 DEFSYM (QCtoggle, ":toggle");
10946 DEFSYM (QCradio, ":radio");
10947 DEFSYM (QClabel, ":label");
10948 DEFSYM (QCvert_only, ":vert-only");
10949
10950 /* Symbols to use for parts of windows. */
10951 DEFSYM (Qvertical_line, "vertical-line");
10952 DEFSYM (Qright_divider, "right-divider");
10953 DEFSYM (Qbottom_divider, "bottom-divider");
10954
10955 DEFSYM (Qmouse_fixup_help_message, "mouse-fixup-help-message");
10956
10957 DEFSYM (Qabove_handle, "above-handle");
10958 DEFSYM (Qhandle, "handle");
10959 DEFSYM (Qbelow_handle, "below-handle");
10960 DEFSYM (Qup, "up");
10961 DEFSYM (Qdown, "down");
10962 DEFSYM (Qtop, "top");
10963 DEFSYM (Qbottom, "bottom");
10964 DEFSYM (Qend_scroll, "end-scroll");
10965 DEFSYM (Qratio, "ratio");
10966 DEFSYM (Qbefore_handle, "before-handle");
10967 DEFSYM (Qhorizontal_handle, "horizontal-handle");
10968 DEFSYM (Qafter_handle, "after-handle");
10969 DEFSYM (Qleft, "left");
10970 DEFSYM (Qright, "right");
10971 DEFSYM (Qleftmost, "leftmost");
10972 DEFSYM (Qrightmost, "rightmost");
10973
10974 /* Properties of event headers. */
10975 DEFSYM (Qevent_kind, "event-kind");
10976 DEFSYM (Qevent_symbol_elements, "event-symbol-elements");
10977
10978 /* An event header symbol HEAD may have a property named
10979 Qevent_symbol_element_mask, which is of the form (BASE MODIFIERS);
10980 BASE is the base, unmodified version of HEAD, and MODIFIERS is the
10981 mask of modifiers applied to it. If present, this is used to help
10982 speed up parse_modifiers. */
10983 DEFSYM (Qevent_symbol_element_mask, "event-symbol-element-mask");
10984
10985 /* An unmodified event header BASE may have a property named
10986 Qmodifier_cache, which is an alist mapping modifier masks onto
10987 modified versions of BASE. If present, this helps speed up
10988 apply_modifiers. */
10989 DEFSYM (Qmodifier_cache, "modifier-cache");
10990
10991 DEFSYM (Qrecompute_lucid_menubar, "recompute-lucid-menubar");
10992 DEFSYM (Qactivate_menubar_hook, "activate-menubar-hook");
10993
10994 DEFSYM (Qpolling_period, "polling-period");
10995
10996 DEFSYM (Qgui_set_selection, "gui-set-selection");
10997
10998 /* The primary selection. */
10999 DEFSYM (QPRIMARY, "PRIMARY");
11000
11001 DEFSYM (Qhandle_switch_frame, "handle-switch-frame");
11002 DEFSYM (Qhandle_select_window, "handle-select-window");
11003
11004 DEFSYM (Qinput_method_exit_on_first_char, "input-method-exit-on-first-char");
11005 DEFSYM (Qinput_method_use_echo_area, "input-method-use-echo-area");
11006
11007 DEFSYM (Qhelp_form_show, "help-form-show");
11008
11009 DEFSYM (Qecho_keystrokes, "echo-keystrokes");
11010
11011 Fset (Qinput_method_exit_on_first_char, Qnil);
11012 Fset (Qinput_method_use_echo_area, Qnil);
11013
11014 /* Symbols to head events. */
11015 DEFSYM (Qmouse_movement, "mouse-movement");
11016 DEFSYM (Qscroll_bar_movement, "scroll-bar-movement");
11017 DEFSYM (Qswitch_frame, "switch-frame");
11018 DEFSYM (Qfocus_in, "focus-in");
11019 DEFSYM (Qfocus_out, "focus-out");
11020 DEFSYM (Qdelete_frame, "delete-frame");
11021 DEFSYM (Qiconify_frame, "iconify-frame");
11022 DEFSYM (Qmake_frame_visible, "make-frame-visible");
11023 DEFSYM (Qselect_window, "select-window");
11024 {
11025 int i;
11026
11027 for (i = 0; i < ARRAYELTS (head_table); i++)
11028 {
11029 const struct event_head *p = &head_table[i];
11030 Lisp_Object var = builtin_lisp_symbol (p->var);
11031 Lisp_Object kind = builtin_lisp_symbol (p->kind);
11032 Fput (var, Qevent_kind, kind);
11033 Fput (var, Qevent_symbol_elements, list1 (var));
11034 }
11035 }
11036
11037 button_down_location = Fmake_vector (make_number (5), Qnil);
11038 staticpro (&button_down_location);
11039 mouse_syms = Fmake_vector (make_number (5), Qnil);
11040 staticpro (&mouse_syms);
11041 wheel_syms = Fmake_vector (make_number (ARRAYELTS (lispy_wheel_names)),
11042 Qnil);
11043 staticpro (&wheel_syms);
11044
11045 {
11046 int i;
11047 int len = ARRAYELTS (modifier_names);
11048
11049 modifier_symbols = Fmake_vector (make_number (len), Qnil);
11050 for (i = 0; i < len; i++)
11051 if (modifier_names[i])
11052 ASET (modifier_symbols, i, intern_c_string (modifier_names[i]));
11053 staticpro (&modifier_symbols);
11054 }
11055
11056 recent_keys = Fmake_vector (make_number (NUM_RECENT_KEYS), Qnil);
11057 staticpro (&recent_keys);
11058
11059 this_command_keys = Fmake_vector (make_number (40), Qnil);
11060 staticpro (&this_command_keys);
11061
11062 raw_keybuf = Fmake_vector (make_number (30), Qnil);
11063 staticpro (&raw_keybuf);
11064
11065 DEFSYM (Qcommand_execute, "command-execute");
11066 DEFSYM (Qinternal_echo_keystrokes_prefix, "internal-echo-keystrokes-prefix");
11067
11068 accent_key_syms = Qnil;
11069 staticpro (&accent_key_syms);
11070
11071 func_key_syms = Qnil;
11072 staticpro (&func_key_syms);
11073
11074 drag_n_drop_syms = Qnil;
11075 staticpro (&drag_n_drop_syms);
11076
11077 unread_switch_frame = Qnil;
11078 staticpro (&unread_switch_frame);
11079
11080 internal_last_event_frame = Qnil;
11081 staticpro (&internal_last_event_frame);
11082
11083 read_key_sequence_cmd = Qnil;
11084 staticpro (&read_key_sequence_cmd);
11085 read_key_sequence_remapped = Qnil;
11086 staticpro (&read_key_sequence_remapped);
11087
11088 menu_bar_one_keymap_changed_items = Qnil;
11089 staticpro (&menu_bar_one_keymap_changed_items);
11090
11091 menu_bar_items_vector = Qnil;
11092 staticpro (&menu_bar_items_vector);
11093
11094 help_form_saved_window_configs = Qnil;
11095 staticpro (&help_form_saved_window_configs);
11096
11097 defsubr (&Scurrent_idle_time);
11098 defsubr (&Sevent_symbol_parse_modifiers);
11099 defsubr (&Sevent_convert_list);
11100 defsubr (&Sread_key_sequence);
11101 defsubr (&Sread_key_sequence_vector);
11102 defsubr (&Srecursive_edit);
11103 defsubr (&Strack_mouse);
11104 defsubr (&Sinput_pending_p);
11105 defsubr (&Srecent_keys);
11106 defsubr (&Sthis_command_keys);
11107 defsubr (&Sthis_command_keys_vector);
11108 defsubr (&Sthis_single_command_keys);
11109 defsubr (&Sthis_single_command_raw_keys);
11110 defsubr (&Sclear_this_command_keys);
11111 defsubr (&Ssuspend_emacs);
11112 defsubr (&Sabort_recursive_edit);
11113 defsubr (&Sexit_recursive_edit);
11114 defsubr (&Srecursion_depth);
11115 defsubr (&Scommand_error_default_function);
11116 defsubr (&Stop_level);
11117 defsubr (&Sdiscard_input);
11118 defsubr (&Sopen_dribble_file);
11119 defsubr (&Sset_input_interrupt_mode);
11120 defsubr (&Sset_output_flow_control);
11121 defsubr (&Sset_input_meta_mode);
11122 defsubr (&Sset_quit_char);
11123 defsubr (&Sset_input_mode);
11124 defsubr (&Scurrent_input_mode);
11125 defsubr (&Sposn_at_point);
11126 defsubr (&Sposn_at_x_y);
11127
11128 DEFVAR_LISP ("last-command-event", last_command_event,
11129 doc: /* Last input event that was part of a command. */);
11130
11131 DEFVAR_LISP ("last-nonmenu-event", last_nonmenu_event,
11132 doc: /* Last input event in a command, except for mouse menu events.
11133 Mouse menus give back keys that don't look like mouse events;
11134 this variable holds the actual mouse event that led to the menu,
11135 so that you can determine whether the command was run by mouse or not. */);
11136
11137 DEFVAR_LISP ("last-input-event", last_input_event,
11138 doc: /* Last input event. */);
11139
11140 DEFVAR_LISP ("unread-command-events", Vunread_command_events,
11141 doc: /* List of events to be read as the command input.
11142 These events are processed first, before actual keyboard input.
11143 Events read from this list are not normally added to `this-command-keys',
11144 as they will already have been added once as they were read for the first time.
11145 An element of the form (t . EVENT) forces EVENT to be added to that list. */);
11146 Vunread_command_events = Qnil;
11147
11148 DEFVAR_LISP ("unread-post-input-method-events", Vunread_post_input_method_events,
11149 doc: /* List of events to be processed as input by input methods.
11150 These events are processed before `unread-command-events'
11151 and actual keyboard input, but are not given to `input-method-function'. */);
11152 Vunread_post_input_method_events = Qnil;
11153
11154 DEFVAR_LISP ("unread-input-method-events", Vunread_input_method_events,
11155 doc: /* List of events to be processed as input by input methods.
11156 These events are processed after `unread-command-events', but
11157 before actual keyboard input.
11158 If there's an active input method, the events are given to
11159 `input-method-function'. */);
11160 Vunread_input_method_events = Qnil;
11161
11162 DEFVAR_LISP ("meta-prefix-char", meta_prefix_char,
11163 doc: /* Meta-prefix character code.
11164 Meta-foo as command input turns into this character followed by foo. */);
11165 XSETINT (meta_prefix_char, 033);
11166
11167 DEFVAR_KBOARD ("last-command", Vlast_command,
11168 doc: /* The last command executed.
11169 Normally a symbol with a function definition, but can be whatever was found
11170 in the keymap, or whatever the variable `this-command' was set to by that
11171 command.
11172
11173 The value `mode-exit' is special; it means that the previous command
11174 read an event that told it to exit, and it did so and unread that event.
11175 In other words, the present command is the event that made the previous
11176 command exit.
11177
11178 The value `kill-region' is special; it means that the previous command
11179 was a kill command.
11180
11181 `last-command' has a separate binding for each terminal device.
11182 See Info node `(elisp)Multiple Terminals'. */);
11183
11184 DEFVAR_KBOARD ("real-last-command", Vreal_last_command,
11185 doc: /* Same as `last-command', but never altered by Lisp code.
11186 Taken from the previous value of `real-this-command'. */);
11187
11188 DEFVAR_KBOARD ("last-repeatable-command", Vlast_repeatable_command,
11189 doc: /* Last command that may be repeated.
11190 The last command executed that was not bound to an input event.
11191 This is the command `repeat' will try to repeat.
11192 Taken from a previous value of `real-this-command'. */);
11193
11194 DEFVAR_LISP ("this-command", Vthis_command,
11195 doc: /* The command now being executed.
11196 The command can set this variable; whatever is put here
11197 will be in `last-command' during the following command. */);
11198 Vthis_command = Qnil;
11199
11200 DEFVAR_LISP ("real-this-command", Vreal_this_command,
11201 doc: /* This is like `this-command', except that commands should never modify it. */);
11202 Vreal_this_command = Qnil;
11203
11204 DEFVAR_LISP ("this-command-keys-shift-translated",
11205 Vthis_command_keys_shift_translated,
11206 doc: /* Non-nil if the key sequence activating this command was shift-translated.
11207 Shift-translation occurs when there is no binding for the key sequence
11208 as entered, but a binding was found by changing an upper-case letter
11209 to lower-case, or a shifted function key to an unshifted one. */);
11210 Vthis_command_keys_shift_translated = Qnil;
11211
11212 DEFVAR_LISP ("this-original-command", Vthis_original_command,
11213 doc: /* The command bound to the current key sequence before remapping.
11214 It equals `this-command' if the original command was not remapped through
11215 any of the active keymaps. Otherwise, the value of `this-command' is the
11216 result of looking up the original command in the active keymaps. */);
11217 Vthis_original_command = Qnil;
11218
11219 DEFVAR_INT ("auto-save-interval", auto_save_interval,
11220 doc: /* Number of input events between auto-saves.
11221 Zero means disable autosaving due to number of characters typed. */);
11222 auto_save_interval = 300;
11223
11224 DEFVAR_LISP ("auto-save-timeout", Vauto_save_timeout,
11225 doc: /* Number of seconds idle time before auto-save.
11226 Zero or nil means disable auto-saving due to idleness.
11227 After auto-saving due to this many seconds of idle time,
11228 Emacs also does a garbage collection if that seems to be warranted. */);
11229 XSETFASTINT (Vauto_save_timeout, 30);
11230
11231 DEFVAR_LISP ("echo-keystrokes", Vecho_keystrokes,
11232 doc: /* Nonzero means echo unfinished commands after this many seconds of pause.
11233 The value may be integer or floating point.
11234 If the value is zero, don't echo at all. */);
11235 Vecho_keystrokes = make_number (1);
11236
11237 DEFVAR_INT ("polling-period", polling_period,
11238 doc: /* Interval between polling for input during Lisp execution.
11239 The reason for polling is to make C-g work to stop a running program.
11240 Polling is needed only when using X windows and SIGIO does not work.
11241 Polling is automatically disabled in all other cases. */);
11242 polling_period = 2;
11243
11244 DEFVAR_LISP ("double-click-time", Vdouble_click_time,
11245 doc: /* Maximum time between mouse clicks to make a double-click.
11246 Measured in milliseconds. The value nil means disable double-click
11247 recognition; t means double-clicks have no time limit and are detected
11248 by position only. */);
11249 Vdouble_click_time = make_number (500);
11250
11251 DEFVAR_INT ("double-click-fuzz", double_click_fuzz,
11252 doc: /* Maximum mouse movement between clicks to make a double-click.
11253 On window-system frames, value is the number of pixels the mouse may have
11254 moved horizontally or vertically between two clicks to make a double-click.
11255 On non window-system frames, value is interpreted in units of 1/8 characters
11256 instead of pixels.
11257
11258 This variable is also the threshold for motion of the mouse
11259 to count as a drag. */);
11260 double_click_fuzz = 3;
11261
11262 DEFVAR_INT ("num-input-keys", num_input_keys,
11263 doc: /* Number of complete key sequences read as input so far.
11264 This includes key sequences read from keyboard macros.
11265 The number is effectively the number of interactive command invocations. */);
11266 num_input_keys = 0;
11267
11268 DEFVAR_INT ("num-nonmacro-input-events", num_nonmacro_input_events,
11269 doc: /* Number of input events read from the keyboard so far.
11270 This does not include events generated by keyboard macros. */);
11271 num_nonmacro_input_events = 0;
11272
11273 DEFVAR_LISP ("last-event-frame", Vlast_event_frame,
11274 doc: /* The frame in which the most recently read event occurred.
11275 If the last event came from a keyboard macro, this is set to `macro'. */);
11276 Vlast_event_frame = Qnil;
11277
11278 /* This variable is set up in sysdep.c. */
11279 DEFVAR_LISP ("tty-erase-char", Vtty_erase_char,
11280 doc: /* The ERASE character as set by the user with stty. */);
11281
11282 DEFVAR_LISP ("help-char", Vhelp_char,
11283 doc: /* Character to recognize as meaning Help.
11284 When it is read, do `(eval help-form)', and display result if it's a string.
11285 If the value of `help-form' is nil, this char can be read normally. */);
11286 XSETINT (Vhelp_char, Ctl ('H'));
11287
11288 DEFVAR_LISP ("help-event-list", Vhelp_event_list,
11289 doc: /* List of input events to recognize as meaning Help.
11290 These work just like the value of `help-char' (see that). */);
11291 Vhelp_event_list = Qnil;
11292
11293 DEFVAR_LISP ("help-form", Vhelp_form,
11294 doc: /* Form to execute when character `help-char' is read.
11295 If the form returns a string, that string is displayed.
11296 If `help-form' is nil, the help char is not recognized. */);
11297 Vhelp_form = Qnil;
11298
11299 DEFVAR_LISP ("prefix-help-command", Vprefix_help_command,
11300 doc: /* Command to run when `help-char' character follows a prefix key.
11301 This command is used only when there is no actual binding
11302 for that character after that prefix key. */);
11303 Vprefix_help_command = Qnil;
11304
11305 DEFVAR_LISP ("top-level", Vtop_level,
11306 doc: /* Form to evaluate when Emacs starts up.
11307 Useful to set before you dump a modified Emacs. */);
11308 Vtop_level = Qnil;
11309 XSYMBOL (Qtop_level)->declared_special = false;
11310
11311 DEFVAR_KBOARD ("keyboard-translate-table", Vkeyboard_translate_table,
11312 doc: /* Translate table for local keyboard input, or nil.
11313 If non-nil, the value should be a char-table. Each character read
11314 from the keyboard is looked up in this char-table. If the value found
11315 there is non-nil, then it is used instead of the actual input character.
11316
11317 The value can also be a string or vector, but this is considered obsolete.
11318 If it is a string or vector of length N, character codes N and up are left
11319 untranslated. In a vector, an element which is nil means "no translation".
11320
11321 This is applied to the characters supplied to input methods, not their
11322 output. See also `translation-table-for-input'.
11323
11324 This variable has a separate binding for each terminal.
11325 See Info node `(elisp)Multiple Terminals'. */);
11326
11327 DEFVAR_BOOL ("cannot-suspend", cannot_suspend,
11328 doc: /* Non-nil means to always spawn a subshell instead of suspending.
11329 (Even if the operating system has support for stopping a process.) */);
11330 cannot_suspend = false;
11331
11332 DEFVAR_BOOL ("menu-prompting", menu_prompting,
11333 doc: /* Non-nil means prompt with menus when appropriate.
11334 This is done when reading from a keymap that has a prompt string,
11335 for elements that have prompt strings.
11336 The menu is displayed on the screen
11337 if X menus were enabled at configuration
11338 time and the previous event was a mouse click prefix key.
11339 Otherwise, menu prompting uses the echo area. */);
11340 menu_prompting = true;
11341
11342 DEFVAR_LISP ("menu-prompt-more-char", menu_prompt_more_char,
11343 doc: /* Character to see next line of menu prompt.
11344 Type this character while in a menu prompt to rotate around the lines of it. */);
11345 XSETINT (menu_prompt_more_char, ' ');
11346
11347 DEFVAR_INT ("extra-keyboard-modifiers", extra_keyboard_modifiers,
11348 doc: /* A mask of additional modifier keys to use with every keyboard character.
11349 Emacs applies the modifiers of the character stored here to each keyboard
11350 character it reads. For example, after evaluating the expression
11351 (setq extra-keyboard-modifiers ?\\C-x)
11352 all input characters will have the control modifier applied to them.
11353
11354 Note that the character ?\\C-@, equivalent to the integer zero, does
11355 not count as a control character; rather, it counts as a character
11356 with no modifiers; thus, setting `extra-keyboard-modifiers' to zero
11357 cancels any modification. */);
11358 extra_keyboard_modifiers = 0;
11359
11360 DEFSYM (Qdeactivate_mark, "deactivate-mark");
11361 DEFVAR_LISP ("deactivate-mark", Vdeactivate_mark,
11362 doc: /* If an editing command sets this to t, deactivate the mark afterward.
11363 The command loop sets this to nil before each command,
11364 and tests the value when the command returns.
11365 Buffer modification stores t in this variable. */);
11366 Vdeactivate_mark = Qnil;
11367 Fmake_variable_buffer_local (Qdeactivate_mark);
11368
11369 DEFVAR_LISP ("pre-command-hook", Vpre_command_hook,
11370 doc: /* Normal hook run before each command is executed.
11371 If an unhandled error happens in running this hook,
11372 the function in which the error occurred is unconditionally removed, since
11373 otherwise the error might happen repeatedly and make Emacs nonfunctional.
11374
11375 See also `pre-command-hook'. */);
11376 Vpre_command_hook = Qnil;
11377
11378 DEFVAR_LISP ("post-command-hook", Vpost_command_hook,
11379 doc: /* Normal hook run after each command is executed.
11380 If an unhandled error happens in running this hook,
11381 the function in which the error occurred is unconditionally removed, since
11382 otherwise the error might happen repeatedly and make Emacs nonfunctional.
11383
11384 It is a bad idea to use this hook for expensive processing. If
11385 unavoidable, wrap your code in `(while-no-input (redisplay) CODE)' to
11386 avoid making Emacs unresponsive while the user types.
11387
11388 See also `pre-command-hook'. */);
11389 Vpost_command_hook = Qnil;
11390
11391 #if 0
11392 DEFVAR_LISP ("echo-area-clear-hook", ...,
11393 doc: /* Normal hook run when clearing the echo area. */);
11394 #endif
11395 DEFSYM (Qecho_area_clear_hook, "echo-area-clear-hook");
11396 Fset (Qecho_area_clear_hook, Qnil);
11397
11398 DEFVAR_LISP ("lucid-menu-bar-dirty-flag", Vlucid_menu_bar_dirty_flag,
11399 doc: /* Non-nil means menu bar, specified Lucid style, needs to be recomputed. */);
11400 Vlucid_menu_bar_dirty_flag = Qnil;
11401
11402 DEFVAR_LISP ("menu-bar-final-items", Vmenu_bar_final_items,
11403 doc: /* List of menu bar items to move to the end of the menu bar.
11404 The elements of the list are event types that may have menu bar bindings. */);
11405 Vmenu_bar_final_items = Qnil;
11406
11407 DEFVAR_LISP ("tool-bar-separator-image-expression", Vtool_bar_separator_image_expression,
11408 doc: /* Expression evaluating to the image spec for a tool-bar separator.
11409 This is used internally by graphical displays that do not render
11410 tool-bar separators natively. Otherwise it is unused (e.g. on GTK). */);
11411 Vtool_bar_separator_image_expression = Qnil;
11412
11413 DEFVAR_KBOARD ("overriding-terminal-local-map",
11414 Voverriding_terminal_local_map,
11415 doc: /* Per-terminal keymap that takes precedence over all other keymaps.
11416 This variable is intended to let commands such as `universal-argument'
11417 set up a different keymap for reading the next command.
11418
11419 `overriding-terminal-local-map' has a separate binding for each
11420 terminal device. See Info node `(elisp)Multiple Terminals'. */);
11421
11422 DEFVAR_LISP ("overriding-local-map", Voverriding_local_map,
11423 doc: /* Keymap that replaces (overrides) local keymaps.
11424 If this variable is non-nil, Emacs looks up key bindings in this
11425 keymap INSTEAD OF the keymap char property, minor mode maps, and the
11426 buffer's local map. Hence, the only active keymaps would be
11427 `overriding-terminal-local-map', this keymap, and `global-keymap', in
11428 order of precedence. */);
11429 Voverriding_local_map = Qnil;
11430
11431 DEFVAR_LISP ("overriding-local-map-menu-flag", Voverriding_local_map_menu_flag,
11432 doc: /* Non-nil means `overriding-local-map' applies to the menu bar.
11433 Otherwise, the menu bar continues to reflect the buffer's local map
11434 and the minor mode maps regardless of `overriding-local-map'. */);
11435 Voverriding_local_map_menu_flag = Qnil;
11436
11437 DEFVAR_LISP ("special-event-map", Vspecial_event_map,
11438 doc: /* Keymap defining bindings for special events to execute at low level. */);
11439 Vspecial_event_map = list1 (Qkeymap);
11440
11441 DEFVAR_LISP ("track-mouse", do_mouse_tracking,
11442 doc: /* Non-nil means generate motion events for mouse motion. */);
11443
11444 DEFVAR_KBOARD ("system-key-alist", Vsystem_key_alist,
11445 doc: /* Alist of system-specific X windows key symbols.
11446 Each element should have the form (N . SYMBOL) where N is the
11447 numeric keysym code (sans the \"system-specific\" bit 1<<28)
11448 and SYMBOL is its name.
11449
11450 `system-key-alist' has a separate binding for each terminal device.
11451 See Info node `(elisp)Multiple Terminals'. */);
11452
11453 DEFVAR_KBOARD ("local-function-key-map", Vlocal_function_key_map,
11454 doc: /* Keymap that translates key sequences to key sequences during input.
11455 This is used mainly for mapping key sequences into some preferred
11456 key events (symbols).
11457
11458 The `read-key-sequence' function replaces any subsequence bound by
11459 `local-function-key-map' with its binding. More precisely, when the
11460 active keymaps have no binding for the current key sequence but
11461 `local-function-key-map' binds a suffix of the sequence to a vector or
11462 string, `read-key-sequence' replaces the matching suffix with its
11463 binding, and continues with the new sequence.
11464
11465 If the binding is a function, it is called with one argument (the prompt)
11466 and its return value (a key sequence) is used.
11467
11468 The events that come from bindings in `local-function-key-map' are not
11469 themselves looked up in `local-function-key-map'.
11470
11471 For example, suppose `local-function-key-map' binds `ESC O P' to [f1].
11472 Typing `ESC O P' to `read-key-sequence' would return [f1]. Typing
11473 `C-x ESC O P' would return [?\\C-x f1]. If [f1] were a prefix key,
11474 typing `ESC O P x' would return [f1 x].
11475
11476 `local-function-key-map' has a separate binding for each terminal
11477 device. See Info node `(elisp)Multiple Terminals'. If you need to
11478 define a binding on all terminals, change `function-key-map'
11479 instead. Initially, `local-function-key-map' is an empty keymap that
11480 has `function-key-map' as its parent on all terminal devices. */);
11481
11482 DEFVAR_KBOARD ("input-decode-map", Vinput_decode_map,
11483 doc: /* Keymap that decodes input escape sequences.
11484 This is used mainly for mapping ASCII function key sequences into
11485 real Emacs function key events (symbols).
11486
11487 The `read-key-sequence' function replaces any subsequence bound by
11488 `input-decode-map' with its binding. Contrary to `function-key-map',
11489 this map applies its rebinding regardless of the presence of an ordinary
11490 binding. So it is more like `key-translation-map' except that it applies
11491 before `function-key-map' rather than after.
11492
11493 If the binding is a function, it is called with one argument (the prompt)
11494 and its return value (a key sequence) is used.
11495
11496 The events that come from bindings in `input-decode-map' are not
11497 themselves looked up in `input-decode-map'. */);
11498
11499 DEFVAR_LISP ("function-key-map", Vfunction_key_map,
11500 doc: /* The parent keymap of all `local-function-key-map' instances.
11501 Function key definitions that apply to all terminal devices should go
11502 here. If a mapping is defined in both the current
11503 `local-function-key-map' binding and this variable, then the local
11504 definition will take precedence. */);
11505 Vfunction_key_map = Fmake_sparse_keymap (Qnil);
11506
11507 DEFVAR_LISP ("key-translation-map", Vkey_translation_map,
11508 doc: /* Keymap of key translations that can override keymaps.
11509 This keymap works like `input-decode-map', but comes after `function-key-map'.
11510 Another difference is that it is global rather than terminal-local. */);
11511 Vkey_translation_map = Fmake_sparse_keymap (Qnil);
11512
11513 DEFVAR_LISP ("deferred-action-list", Vdeferred_action_list,
11514 doc: /* List of deferred actions to be performed at a later time.
11515 The precise format isn't relevant here; we just check whether it is nil. */);
11516 Vdeferred_action_list = Qnil;
11517
11518 DEFVAR_LISP ("deferred-action-function", Vdeferred_action_function,
11519 doc: /* Function to call to handle deferred actions, after each command.
11520 This function is called with no arguments after each command
11521 whenever `deferred-action-list' is non-nil. */);
11522 Vdeferred_action_function = Qnil;
11523
11524 DEFVAR_LISP ("delayed-warnings-list", Vdelayed_warnings_list,
11525 doc: /* List of warnings to be displayed after this command.
11526 Each element must be a list (TYPE MESSAGE [LEVEL [BUFFER-NAME]]),
11527 as per the args of `display-warning' (which see).
11528 If this variable is non-nil, `delayed-warnings-hook' will be run
11529 immediately after running `post-command-hook'. */);
11530 Vdelayed_warnings_list = Qnil;
11531
11532 DEFVAR_LISP ("timer-list", Vtimer_list,
11533 doc: /* List of active absolute time timers in order of increasing time. */);
11534 Vtimer_list = Qnil;
11535
11536 DEFVAR_LISP ("timer-idle-list", Vtimer_idle_list,
11537 doc: /* List of active idle-time timers in order of increasing time. */);
11538 Vtimer_idle_list = Qnil;
11539
11540 DEFVAR_LISP ("input-method-function", Vinput_method_function,
11541 doc: /* If non-nil, the function that implements the current input method.
11542 It's called with one argument, a printing character that was just read.
11543 (That means a character with code 040...0176.)
11544 Typically this function uses `read-event' to read additional events.
11545 When it does so, it should first bind `input-method-function' to nil
11546 so it will not be called recursively.
11547
11548 The function should return a list of zero or more events
11549 to be used as input. If it wants to put back some events
11550 to be reconsidered, separately, by the input method,
11551 it can add them to the beginning of `unread-command-events'.
11552
11553 The input method function can find in `input-method-previous-message'
11554 the previous echo area message.
11555
11556 The input method function should refer to the variables
11557 `input-method-use-echo-area' and `input-method-exit-on-first-char'
11558 for guidance on what to do. */);
11559 Vinput_method_function = Qlist;
11560
11561 DEFVAR_LISP ("input-method-previous-message",
11562 Vinput_method_previous_message,
11563 doc: /* When `input-method-function' is called, hold the previous echo area message.
11564 This variable exists because `read-event' clears the echo area
11565 before running the input method. It is nil if there was no message. */);
11566 Vinput_method_previous_message = Qnil;
11567
11568 DEFVAR_LISP ("show-help-function", Vshow_help_function,
11569 doc: /* If non-nil, the function that implements the display of help.
11570 It's called with one argument, the help string to display. */);
11571 Vshow_help_function = Qnil;
11572
11573 DEFVAR_LISP ("disable-point-adjustment", Vdisable_point_adjustment,
11574 doc: /* If non-nil, suppress point adjustment after executing a command.
11575
11576 After a command is executed, if point is moved into a region that has
11577 special properties (e.g. composition, display), we adjust point to
11578 the boundary of the region. But, when a command sets this variable to
11579 non-nil, we suppress the point adjustment.
11580
11581 This variable is set to nil before reading a command, and is checked
11582 just after executing the command. */);
11583 Vdisable_point_adjustment = Qnil;
11584
11585 DEFVAR_LISP ("global-disable-point-adjustment",
11586 Vglobal_disable_point_adjustment,
11587 doc: /* If non-nil, always suppress point adjustment.
11588
11589 The default value is nil, in which case, point adjustment are
11590 suppressed only after special commands that set
11591 `disable-point-adjustment' (which see) to non-nil. */);
11592 Vglobal_disable_point_adjustment = Qnil;
11593
11594 DEFVAR_LISP ("minibuffer-message-timeout", Vminibuffer_message_timeout,
11595 doc: /* How long to display an echo-area message when the minibuffer is active.
11596 If the value is not a number, such messages don't time out. */);
11597 Vminibuffer_message_timeout = make_number (2);
11598
11599 DEFVAR_LISP ("throw-on-input", Vthrow_on_input,
11600 doc: /* If non-nil, any keyboard input throws to this symbol.
11601 The value of that variable is passed to `quit-flag' and later causes a
11602 peculiar kind of quitting. */);
11603 Vthrow_on_input = Qnil;
11604
11605 DEFVAR_LISP ("command-error-function", Vcommand_error_function,
11606 doc: /* Function to output error messages.
11607 Called with three arguments:
11608 - the error data, a list of the form (SIGNALED-CONDITION . SIGNAL-DATA)
11609 such as what `condition-case' would bind its variable to,
11610 - the context (a string which normally goes at the start of the message),
11611 - the Lisp function within which the error was signaled. */);
11612 Vcommand_error_function = intern ("command-error-default-function");
11613
11614 DEFVAR_LISP ("enable-disabled-menus-and-buttons",
11615 Venable_disabled_menus_and_buttons,
11616 doc: /* If non-nil, don't ignore events produced by disabled menu items and tool-bar.
11617
11618 Help functions bind this to allow help on disabled menu items
11619 and tool-bar buttons. */);
11620 Venable_disabled_menus_and_buttons = Qnil;
11621
11622 DEFVAR_LISP ("select-active-regions",
11623 Vselect_active_regions,
11624 doc: /* If non-nil, an active region automatically sets the primary selection.
11625 If the value is `only', only temporarily active regions (usually made
11626 by mouse-dragging or shift-selection) set the window selection.
11627
11628 This takes effect only when Transient Mark mode is enabled. */);
11629 Vselect_active_regions = Qt;
11630
11631 DEFVAR_LISP ("saved-region-selection",
11632 Vsaved_region_selection,
11633 doc: /* Contents of active region prior to buffer modification.
11634 If `select-active-regions' is non-nil, Emacs sets this to the
11635 text in the region before modifying the buffer. The next call to
11636 the function `deactivate-mark' uses this to set the window selection. */);
11637 Vsaved_region_selection = Qnil;
11638
11639 DEFVAR_LISP ("selection-inhibit-update-commands",
11640 Vselection_inhibit_update_commands,
11641 doc: /* List of commands which should not update the selection.
11642 Normally, if `select-active-regions' is non-nil and the mark remains
11643 active after a command (i.e. the mark was not deactivated), the Emacs
11644 command loop sets the selection to the text in the region. However,
11645 if the command is in this list, the selection is not updated. */);
11646 Vselection_inhibit_update_commands
11647 = list2 (Qhandle_switch_frame, Qhandle_select_window);
11648
11649 DEFVAR_LISP ("debug-on-event",
11650 Vdebug_on_event,
11651 doc: /* Enter debugger on this event. When Emacs
11652 receives the special event specified by this variable, it will try to
11653 break into the debugger as soon as possible instead of processing the
11654 event normally through `special-event-map'.
11655
11656 Currently, the only supported values for this
11657 variable are `sigusr1' and `sigusr2'. */);
11658 Vdebug_on_event = intern_c_string ("sigusr2");
11659
11660 /* Create the initial keyboard. Qt means 'unset'. */
11661 initial_kboard = allocate_kboard (Qt);
11662 }
11663
11664 void
11665 keys_of_keyboard (void)
11666 {
11667 initial_define_key (global_map, Ctl ('Z'), "suspend-emacs");
11668 initial_define_key (control_x_map, Ctl ('Z'), "suspend-emacs");
11669 initial_define_key (meta_map, Ctl ('C'), "exit-recursive-edit");
11670 initial_define_key (global_map, Ctl (']'), "abort-recursive-edit");
11671 initial_define_key (meta_map, 'x', "execute-extended-command");
11672
11673 initial_define_lispy_key (Vspecial_event_map, "delete-frame",
11674 "handle-delete-frame");
11675 initial_define_lispy_key (Vspecial_event_map, "ns-put-working-text",
11676 "ns-put-working-text");
11677 initial_define_lispy_key (Vspecial_event_map, "ns-unput-working-text",
11678 "ns-unput-working-text");
11679 /* Here we used to use `ignore-event' which would simple set prefix-arg to
11680 current-prefix-arg, as is done in `handle-switch-frame'.
11681 But `handle-switch-frame is not run from the special-map.
11682 Commands from that map are run in a special way that automatically
11683 preserves the prefix-arg. Restoring the prefix arg here is not just
11684 redundant but harmful:
11685 - C-u C-x v =
11686 - current-prefix-arg is set to non-nil, prefix-arg is set to nil.
11687 - after the first prompt, the exit-minibuffer-hook is run which may
11688 iconify a frame and thus push a `iconify-frame' event.
11689 - after running exit-minibuffer-hook, current-prefix-arg is
11690 restored to the non-nil value it had before the prompt.
11691 - we enter the second prompt.
11692 current-prefix-arg is non-nil, prefix-arg is nil.
11693 - before running the first real event, we run the special iconify-frame
11694 event, but we pass the `special' arg to command-execute so
11695 current-prefix-arg and prefix-arg are left untouched.
11696 - here we foolishly copy the non-nil current-prefix-arg to prefix-arg.
11697 - the next key event will have a spuriously non-nil current-prefix-arg. */
11698 initial_define_lispy_key (Vspecial_event_map, "iconify-frame",
11699 "ignore");
11700 initial_define_lispy_key (Vspecial_event_map, "make-frame-visible",
11701 "ignore");
11702 /* Handling it at such a low-level causes read_key_sequence to get
11703 * confused because it doesn't realize that the current_buffer was
11704 * changed by read_char.
11705 *
11706 * initial_define_lispy_key (Vspecial_event_map, "select-window",
11707 * "handle-select-window"); */
11708 initial_define_lispy_key (Vspecial_event_map, "save-session",
11709 "handle-save-session");
11710
11711 #ifdef HAVE_DBUS
11712 /* Define a special event which is raised for dbus callback
11713 functions. */
11714 initial_define_lispy_key (Vspecial_event_map, "dbus-event",
11715 "dbus-handle-event");
11716 #endif
11717
11718 #ifdef USE_FILE_NOTIFY
11719 /* Define a special event which is raised for notification callback
11720 functions. */
11721 initial_define_lispy_key (Vspecial_event_map, "file-notify",
11722 "file-notify-handle-event");
11723 #endif /* USE_FILE_NOTIFY */
11724
11725 initial_define_lispy_key (Vspecial_event_map, "config-changed-event",
11726 "ignore");
11727 #if defined (WINDOWSNT)
11728 initial_define_lispy_key (Vspecial_event_map, "language-change",
11729 "ignore");
11730 #endif
11731 initial_define_lispy_key (Vspecial_event_map, "focus-in",
11732 "handle-focus-in");
11733 initial_define_lispy_key (Vspecial_event_map, "focus-out",
11734 "handle-focus-out");
11735 }
11736
11737 /* Mark the pointers in the kboard objects.
11738 Called by Fgarbage_collect. */
11739 void
11740 mark_kboards (void)
11741 {
11742 KBOARD *kb;
11743 Lisp_Object *p;
11744 for (kb = all_kboards; kb; kb = kb->next_kboard)
11745 {
11746 if (kb->kbd_macro_buffer)
11747 for (p = kb->kbd_macro_buffer; p < kb->kbd_macro_ptr; p++)
11748 mark_object (*p);
11749 mark_object (KVAR (kb, Voverriding_terminal_local_map));
11750 mark_object (KVAR (kb, Vlast_command));
11751 mark_object (KVAR (kb, Vreal_last_command));
11752 mark_object (KVAR (kb, Vkeyboard_translate_table));
11753 mark_object (KVAR (kb, Vlast_repeatable_command));
11754 mark_object (KVAR (kb, Vprefix_arg));
11755 mark_object (KVAR (kb, Vlast_prefix_arg));
11756 mark_object (KVAR (kb, kbd_queue));
11757 mark_object (KVAR (kb, defining_kbd_macro));
11758 mark_object (KVAR (kb, Vlast_kbd_macro));
11759 mark_object (KVAR (kb, Vsystem_key_alist));
11760 mark_object (KVAR (kb, system_key_syms));
11761 mark_object (KVAR (kb, Vwindow_system));
11762 mark_object (KVAR (kb, Vinput_decode_map));
11763 mark_object (KVAR (kb, Vlocal_function_key_map));
11764 mark_object (KVAR (kb, Vdefault_minibuffer_frame));
11765 mark_object (KVAR (kb, echo_string));
11766 mark_object (KVAR (kb, echo_prompt));
11767 }
11768 {
11769 union buffered_input_event *event;
11770 for (event = kbd_fetch_ptr; event != kbd_store_ptr; event++)
11771 {
11772 if (event == kbd_buffer + KBD_BUFFER_SIZE)
11773 event = kbd_buffer;
11774 /* These two special event types has no Lisp_Objects to mark. */
11775 if (event->kind != SELECTION_REQUEST_EVENT
11776 && event->kind != SELECTION_CLEAR_EVENT)
11777 {
11778 mark_object (event->ie.x);
11779 mark_object (event->ie.y);
11780 mark_object (event->ie.frame_or_window);
11781 mark_object (event->ie.arg);
11782 }
11783 }
11784 }
11785 }