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