Merge from emacs-24; up to 2012-12-25T11:37:21Z!dmantipov@yandex.ru
[bpt/emacs.git] / src / keymap.c
1 /* Manipulation of keymaps
2 Copyright (C) 1985-1988, 1993-1995, 1998-2013 Free Software
3 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 /* Old BUGS:
21 - [M-C-a] != [?\M-\C-a]
22 - [M-f2] != [?\e f2].
23 - (define-key map [menu-bar foo] <bla>) does not always place <bla>
24 at the head of the menu (if `foo' was already bound earlier and
25 then unbound, for example).
26 TODO:
27 - allow many more Meta -> ESC mappings (like Hyper -> C-e for Emacspeak)
28 - Think about the various defaulting that's currently hard-coded in
29 keyboard.c (uppercase->lowercase, char->charset, button-events, ...)
30 and make it more generic. Maybe we should allow mappings of the
31 form (PREDICATE . BINDING) as generalization of the default binding,
32 tho probably a cleaner way to attack this is to allow functional
33 keymaps (i.e. keymaps that are implemented as functions that implement
34 a few different methods like `lookup', `map', ...).
35 - Make [a] equivalent to [?a].
36 BEWARE:
37 - map-keymap should work meaningfully even if entries are added/removed
38 to the keymap while iterating through it:
39 start - removed <= visited <= start + added
40 */
41
42 #include <config.h>
43 #include <stdio.h>
44
45 #include "lisp.h"
46 #include "commands.h"
47 #include "character.h"
48 #include "buffer.h"
49 #include "charset.h"
50 #include "keyboard.h"
51 #include "frame.h"
52 #include "termhooks.h"
53 #include "blockinput.h"
54 #include "puresize.h"
55 #include "intervals.h"
56 #include "keymap.h"
57 #include "window.h"
58
59 /* Actually allocate storage for these variables */
60
61 Lisp_Object current_global_map; /* Current global keymap */
62
63 Lisp_Object global_map; /* default global key bindings */
64
65 Lisp_Object meta_map; /* The keymap used for globally bound
66 ESC-prefixed default commands */
67
68 Lisp_Object control_x_map; /* The keymap used for globally bound
69 C-x-prefixed default commands */
70
71 /* The keymap used by the minibuf for local
72 bindings when spaces are allowed in the
73 minibuf */
74
75 /* The keymap used by the minibuf for local
76 bindings when spaces are not encouraged
77 in the minibuf */
78
79 /* keymap used for minibuffers when doing completion */
80 /* keymap used for minibuffers when doing completion and require a match */
81 static Lisp_Object Qkeymapp, Qnon_ascii;
82 Lisp_Object Qkeymap, Qmenu_item, Qremap;
83 static Lisp_Object QCadvertised_binding;
84
85 /* Alist of elements like (DEL . "\d"). */
86 static Lisp_Object exclude_keys;
87
88 /* Pre-allocated 2-element vector for Fcommand_remapping to use. */
89 static Lisp_Object command_remapping_vector;
90
91 /* Hash table used to cache a reverse-map to speed up calls to where-is. */
92 static Lisp_Object where_is_cache;
93 /* Which keymaps are reverse-stored in the cache. */
94 static Lisp_Object where_is_cache_keymaps;
95
96 static Lisp_Object store_in_keymap (Lisp_Object, Lisp_Object, Lisp_Object);
97
98 static Lisp_Object define_as_prefix (Lisp_Object, Lisp_Object);
99 static void describe_command (Lisp_Object, Lisp_Object);
100 static void describe_translation (Lisp_Object, Lisp_Object);
101 static void describe_map (Lisp_Object, Lisp_Object,
102 void (*) (Lisp_Object, Lisp_Object),
103 bool, Lisp_Object, Lisp_Object*, bool, bool);
104 static void describe_vector (Lisp_Object, Lisp_Object, Lisp_Object,
105 void (*) (Lisp_Object, Lisp_Object), bool,
106 Lisp_Object, Lisp_Object, bool, bool);
107 static void silly_event_symbol_error (Lisp_Object);
108 static Lisp_Object get_keyelt (Lisp_Object, bool);
109 \f
110 /* Keymap object support - constructors and predicates. */
111
112 DEFUN ("make-keymap", Fmake_keymap, Smake_keymap, 0, 1, 0,
113 doc: /* Construct and return a new keymap, of the form (keymap CHARTABLE . ALIST).
114 CHARTABLE is a char-table that holds the bindings for all characters
115 without modifiers. All entries in it are initially nil, meaning
116 "command undefined". ALIST is an assoc-list which holds bindings for
117 function keys, mouse events, and any other things that appear in the
118 input stream. Initially, ALIST is nil.
119
120 The optional arg STRING supplies a menu name for the keymap
121 in case you use it as a menu with `x-popup-menu'. */)
122 (Lisp_Object string)
123 {
124 Lisp_Object tail;
125 if (!NILP (string))
126 tail = Fcons (string, Qnil);
127 else
128 tail = Qnil;
129 return Fcons (Qkeymap,
130 Fcons (Fmake_char_table (Qkeymap, Qnil), tail));
131 }
132
133 DEFUN ("make-sparse-keymap", Fmake_sparse_keymap, Smake_sparse_keymap, 0, 1, 0,
134 doc: /* Construct and return a new sparse keymap.
135 Its car is `keymap' and its cdr is an alist of (CHAR . DEFINITION),
136 which binds the character CHAR to DEFINITION, or (SYMBOL . DEFINITION),
137 which binds the function key or mouse event SYMBOL to DEFINITION.
138 Initially the alist is nil.
139
140 The optional arg STRING supplies a menu name for the keymap
141 in case you use it as a menu with `x-popup-menu'. */)
142 (Lisp_Object string)
143 {
144 if (!NILP (string))
145 {
146 if (!NILP (Vpurify_flag))
147 string = Fpurecopy (string);
148 return Fcons (Qkeymap, Fcons (string, Qnil));
149 }
150 return Fcons (Qkeymap, Qnil);
151 }
152
153 /* This function is used for installing the standard key bindings
154 at initialization time.
155
156 For example:
157
158 initial_define_key (control_x_map, Ctl('X'), "exchange-point-and-mark"); */
159
160 void
161 initial_define_key (Lisp_Object keymap, int key, const char *defname)
162 {
163 store_in_keymap (keymap, make_number (key), intern_c_string (defname));
164 }
165
166 void
167 initial_define_lispy_key (Lisp_Object keymap, const char *keyname, const char *defname)
168 {
169 store_in_keymap (keymap, intern_c_string (keyname), intern_c_string (defname));
170 }
171
172 DEFUN ("keymapp", Fkeymapp, Skeymapp, 1, 1, 0,
173 doc: /* Return t if OBJECT is a keymap.
174
175 A keymap is a list (keymap . ALIST),
176 or a symbol whose function definition is itself a keymap.
177 ALIST elements look like (CHAR . DEFN) or (SYMBOL . DEFN);
178 a vector of densely packed bindings for small character codes
179 is also allowed as an element. */)
180 (Lisp_Object object)
181 {
182 return (KEYMAPP (object) ? Qt : Qnil);
183 }
184
185 DEFUN ("keymap-prompt", Fkeymap_prompt, Skeymap_prompt, 1, 1, 0,
186 doc: /* Return the prompt-string of a keymap MAP.
187 If non-nil, the prompt is shown in the echo-area
188 when reading a key-sequence to be looked-up in this keymap. */)
189 (Lisp_Object map)
190 {
191 map = get_keymap (map, 0, 0);
192 while (CONSP (map))
193 {
194 Lisp_Object tem = XCAR (map);
195 if (STRINGP (tem))
196 return tem;
197 else if (KEYMAPP (tem))
198 {
199 tem = Fkeymap_prompt (tem);
200 if (!NILP (tem))
201 return tem;
202 }
203 map = XCDR (map);
204 }
205 return Qnil;
206 }
207
208 /* Check that OBJECT is a keymap (after dereferencing through any
209 symbols). If it is, return it.
210
211 If AUTOLOAD and if OBJECT is a symbol whose function value
212 is an autoload form, do the autoload and try again.
213 If AUTOLOAD, callers must assume GC is possible.
214
215 ERROR_IF_NOT_KEYMAP controls how we respond if OBJECT isn't a keymap.
216 If ERROR_IF_NOT_KEYMAP, signal an error; otherwise,
217 just return Qnil.
218
219 Note that most of the time, we don't want to pursue autoloads.
220 Functions like Faccessible_keymaps which scan entire keymap trees
221 shouldn't load every autoloaded keymap. I'm not sure about this,
222 but it seems to me that only read_key_sequence, Flookup_key, and
223 Fdefine_key should cause keymaps to be autoloaded.
224
225 This function can GC when AUTOLOAD is true, because it calls
226 Fautoload_do_load which can GC. */
227
228 Lisp_Object
229 get_keymap (Lisp_Object object, bool error_if_not_keymap, bool autoload)
230 {
231 Lisp_Object tem;
232
233 autoload_retry:
234 if (NILP (object))
235 goto end;
236 if (CONSP (object) && EQ (XCAR (object), Qkeymap))
237 return object;
238
239 tem = indirect_function (object);
240 if (CONSP (tem))
241 {
242 if (EQ (XCAR (tem), Qkeymap))
243 return tem;
244
245 /* Should we do an autoload? Autoload forms for keymaps have
246 Qkeymap as their fifth element. */
247 if ((autoload || !error_if_not_keymap) && EQ (XCAR (tem), Qautoload)
248 && SYMBOLP (object))
249 {
250 Lisp_Object tail;
251
252 tail = Fnth (make_number (4), tem);
253 if (EQ (tail, Qkeymap))
254 {
255 if (autoload)
256 {
257 struct gcpro gcpro1, gcpro2;
258
259 GCPRO2 (tem, object);
260 Fautoload_do_load (tem, object, Qnil);
261 UNGCPRO;
262
263 goto autoload_retry;
264 }
265 else
266 return object;
267 }
268 }
269 }
270
271 end:
272 if (error_if_not_keymap)
273 wrong_type_argument (Qkeymapp, object);
274 return Qnil;
275 }
276 \f
277 /* Return the parent map of KEYMAP, or nil if it has none.
278 We assume that KEYMAP is a valid keymap. */
279
280 static Lisp_Object
281 keymap_parent (Lisp_Object keymap, bool autoload)
282 {
283 Lisp_Object list;
284
285 keymap = get_keymap (keymap, 1, autoload);
286
287 /* Skip past the initial element `keymap'. */
288 list = XCDR (keymap);
289 for (; CONSP (list); list = XCDR (list))
290 {
291 /* See if there is another `keymap'. */
292 if (KEYMAPP (list))
293 return list;
294 }
295
296 return get_keymap (list, 0, autoload);
297 }
298
299 DEFUN ("keymap-parent", Fkeymap_parent, Skeymap_parent, 1, 1, 0,
300 doc: /* Return the parent keymap of KEYMAP.
301 If KEYMAP has no parent, return nil. */)
302 (Lisp_Object keymap)
303 {
304 return keymap_parent (keymap, 1);
305 }
306
307 /* Check whether MAP is one of MAPS parents. */
308 static bool
309 keymap_memberp (Lisp_Object map, Lisp_Object maps)
310 {
311 if (NILP (map)) return 0;
312 while (KEYMAPP (maps) && !EQ (map, maps))
313 maps = keymap_parent (maps, 0);
314 return (EQ (map, maps));
315 }
316
317 /* Set the parent keymap of MAP to PARENT. */
318
319 DEFUN ("set-keymap-parent", Fset_keymap_parent, Sset_keymap_parent, 2, 2, 0,
320 doc: /* Modify KEYMAP to set its parent map to PARENT.
321 Return PARENT. PARENT should be nil or another keymap. */)
322 (Lisp_Object keymap, Lisp_Object parent)
323 {
324 Lisp_Object list, prev;
325 struct gcpro gcpro1, gcpro2;
326
327 /* Flush any reverse-map cache. */
328 where_is_cache = Qnil; where_is_cache_keymaps = Qt;
329
330 GCPRO2 (keymap, parent);
331 keymap = get_keymap (keymap, 1, 1);
332
333 if (!NILP (parent))
334 {
335 parent = get_keymap (parent, 1, 0);
336
337 /* Check for cycles. */
338 if (keymap_memberp (keymap, parent))
339 error ("Cyclic keymap inheritance");
340 }
341
342 /* Skip past the initial element `keymap'. */
343 prev = keymap;
344 while (1)
345 {
346 list = XCDR (prev);
347 /* If there is a parent keymap here, replace it.
348 If we came to the end, add the parent in PREV. */
349 if (!CONSP (list) || KEYMAPP (list))
350 {
351 CHECK_IMPURE (prev);
352 XSETCDR (prev, parent);
353 RETURN_UNGCPRO (parent);
354 }
355 prev = list;
356 }
357 }
358 \f
359
360 /* Look up IDX in MAP. IDX may be any sort of event.
361 Note that this does only one level of lookup; IDX must be a single
362 event, not a sequence.
363
364 MAP must be a keymap or a list of keymaps.
365
366 If T_OK, bindings for Qt are treated as default
367 bindings; any key left unmentioned by other tables and bindings is
368 given the binding of Qt.
369
370 If not T_OK, bindings for Qt are not treated specially.
371
372 If NOINHERIT, don't accept a subkeymap found in an inherited keymap.
373
374 Return Qunbound if no binding was found (and return Qnil if a nil
375 binding was found). */
376
377 static Lisp_Object
378 access_keymap_1 (Lisp_Object map, Lisp_Object idx,
379 bool t_ok, bool noinherit, bool autoload)
380 {
381 /* If idx is a list (some sort of mouse click, perhaps?),
382 the index we want to use is the car of the list, which
383 ought to be a symbol. */
384 idx = EVENT_HEAD (idx);
385
386 /* If idx is a symbol, it might have modifiers, which need to
387 be put in the canonical order. */
388 if (SYMBOLP (idx))
389 idx = reorder_modifiers (idx);
390 else if (INTEGERP (idx))
391 /* Clobber the high bits that can be present on a machine
392 with more than 24 bits of integer. */
393 XSETFASTINT (idx, XINT (idx) & (CHAR_META | (CHAR_META - 1)));
394
395 /* Handle the special meta -> esc mapping. */
396 if (INTEGERP (idx) && XFASTINT (idx) & meta_modifier)
397 {
398 /* See if there is a meta-map. If there's none, there is
399 no binding for IDX, unless a default binding exists in MAP. */
400 struct gcpro gcpro1;
401 Lisp_Object event_meta_binding, event_meta_map;
402 GCPRO1 (map);
403 /* A strange value in which Meta is set would cause
404 infinite recursion. Protect against that. */
405 if (XINT (meta_prefix_char) & CHAR_META)
406 meta_prefix_char = make_number (27);
407 event_meta_binding = access_keymap_1 (map, meta_prefix_char, t_ok,
408 noinherit, autoload);
409 event_meta_map = get_keymap (event_meta_binding, 0, autoload);
410 UNGCPRO;
411 if (CONSP (event_meta_map))
412 {
413 map = event_meta_map;
414 idx = make_number (XFASTINT (idx) & ~meta_modifier);
415 }
416 else if (t_ok)
417 /* Set IDX to t, so that we only find a default binding. */
418 idx = Qt;
419 else
420 /* An explicit nil binding, or no binding at all. */
421 return NILP (event_meta_binding) ? Qnil : Qunbound;
422 }
423
424 /* t_binding is where we put a default binding that applies,
425 to use in case we do not find a binding specifically
426 for this key sequence. */
427 {
428 Lisp_Object tail;
429 Lisp_Object t_binding = Qunbound;
430 Lisp_Object retval = Qunbound;
431 Lisp_Object retval_tail = Qnil;
432 struct gcpro gcpro1, gcpro2, gcpro3, gcpro4;
433
434 GCPRO4 (tail, idx, t_binding, retval);
435
436 for (tail = (CONSP (map) && EQ (Qkeymap, XCAR (map))) ? XCDR (map) : map;
437 (CONSP (tail)
438 || (tail = get_keymap (tail, 0, autoload), CONSP (tail)));
439 tail = XCDR (tail))
440 {
441 /* Qunbound in VAL means we have found no binding. */
442 Lisp_Object val = Qunbound;
443 Lisp_Object binding = XCAR (tail);
444 Lisp_Object submap = get_keymap (binding, 0, autoload);
445
446 if (EQ (binding, Qkeymap))
447 {
448 if (noinherit || NILP (retval))
449 /* If NOINHERIT, stop here, the rest is inherited. */
450 break;
451 else if (!EQ (retval, Qunbound))
452 {
453 Lisp_Object parent_entry;
454 eassert (KEYMAPP (retval));
455 parent_entry
456 = get_keymap (access_keymap_1 (tail, idx,
457 t_ok, 0, autoload),
458 0, autoload);
459 if (KEYMAPP (parent_entry))
460 {
461 if (CONSP (retval_tail))
462 XSETCDR (retval_tail, parent_entry);
463 else
464 {
465 retval_tail = Fcons (retval, parent_entry);
466 retval = Fcons (Qkeymap, retval_tail);
467 }
468 }
469 break;
470 }
471 }
472 else if (CONSP (submap))
473 {
474 val = access_keymap_1 (submap, idx, t_ok, noinherit, autoload);
475 }
476 else if (CONSP (binding))
477 {
478 Lisp_Object key = XCAR (binding);
479
480 if (EQ (key, idx))
481 val = XCDR (binding);
482 else if (t_ok && EQ (key, Qt))
483 {
484 t_binding = XCDR (binding);
485 t_ok = 0;
486 }
487 }
488 else if (VECTORP (binding))
489 {
490 if (INTEGERP (idx) && XFASTINT (idx) < ASIZE (binding))
491 val = AREF (binding, XFASTINT (idx));
492 }
493 else if (CHAR_TABLE_P (binding))
494 {
495 /* Character codes with modifiers
496 are not included in a char-table.
497 All character codes without modifiers are included. */
498 if (INTEGERP (idx) && (XFASTINT (idx) & CHAR_MODIFIER_MASK) == 0)
499 {
500 val = Faref (binding, idx);
501 /* `nil' has a special meaning for char-tables, so
502 we use something else to record an explicitly
503 unbound entry. */
504 if (NILP (val))
505 val = Qunbound;
506 }
507 }
508
509 /* If we found a binding, clean it up and return it. */
510 if (!EQ (val, Qunbound))
511 {
512 if (EQ (val, Qt))
513 /* A Qt binding is just like an explicit nil binding
514 (i.e. it shadows any parent binding but not bindings in
515 keymaps of lower precedence). */
516 val = Qnil;
517
518 val = get_keyelt (val, autoload);
519
520 if (!KEYMAPP (val))
521 {
522 if (NILP (retval) || EQ (retval, Qunbound))
523 retval = val;
524 if (!NILP (val))
525 break; /* Shadows everything that follows. */
526 }
527 else if (NILP (retval) || EQ (retval, Qunbound))
528 retval = val;
529 else if (CONSP (retval_tail))
530 {
531 XSETCDR (retval_tail, Fcons (val, Qnil));
532 retval_tail = XCDR (retval_tail);
533 }
534 else
535 {
536 retval_tail = Fcons (val, Qnil);
537 retval = Fcons (Qkeymap, Fcons (retval, retval_tail));
538 }
539 }
540 QUIT;
541 }
542 UNGCPRO;
543 return EQ (Qunbound, retval) ? get_keyelt (t_binding, autoload) : retval;
544 }
545 }
546
547 Lisp_Object
548 access_keymap (Lisp_Object map, Lisp_Object idx,
549 bool t_ok, bool noinherit, bool autoload)
550 {
551 Lisp_Object val = access_keymap_1 (map, idx, t_ok, noinherit, autoload);
552 return EQ (val, Qunbound) ? Qnil : val;
553 }
554
555 static void
556 map_keymap_item (map_keymap_function_t fun, Lisp_Object args, Lisp_Object key, Lisp_Object val, void *data)
557 {
558 if (EQ (val, Qt))
559 val = Qnil;
560 (*fun) (key, val, args, data);
561 }
562
563 static void
564 map_keymap_char_table_item (Lisp_Object args, Lisp_Object key, Lisp_Object val)
565 {
566 if (!NILP (val))
567 {
568 map_keymap_function_t fun = XSAVE_POINTER (args, 0);
569 /* If the key is a range, make a copy since map_char_table modifies
570 it in place. */
571 if (CONSP (key))
572 key = Fcons (XCAR (key), XCDR (key));
573 map_keymap_item (fun, XSAVE_OBJECT (args, 2), key,
574 val, XSAVE_POINTER (args, 1));
575 }
576 }
577
578 /* Call FUN for every binding in MAP and stop at (and return) the parent.
579 FUN is called with 4 arguments: FUN (KEY, BINDING, ARGS, DATA). */
580 static Lisp_Object
581 map_keymap_internal (Lisp_Object map,
582 map_keymap_function_t fun,
583 Lisp_Object args,
584 void *data)
585 {
586 struct gcpro gcpro1, gcpro2, gcpro3;
587 Lisp_Object tail
588 = (CONSP (map) && EQ (Qkeymap, XCAR (map))) ? XCDR (map) : map;
589
590 GCPRO3 (map, args, tail);
591 for (; CONSP (tail) && !EQ (Qkeymap, XCAR (tail)); tail = XCDR (tail))
592 {
593 Lisp_Object binding = XCAR (tail);
594
595 if (KEYMAPP (binding)) /* An embedded parent. */
596 break;
597 else if (CONSP (binding))
598 map_keymap_item (fun, args, XCAR (binding), XCDR (binding), data);
599 else if (VECTORP (binding))
600 {
601 /* Loop over the char values represented in the vector. */
602 int len = ASIZE (binding);
603 int c;
604 for (c = 0; c < len; c++)
605 {
606 Lisp_Object character;
607 XSETFASTINT (character, c);
608 map_keymap_item (fun, args, character, AREF (binding, c), data);
609 }
610 }
611 else if (CHAR_TABLE_P (binding))
612 map_char_table (map_keymap_char_table_item, Qnil, binding,
613 make_save_value ("ppo", fun, data, args));
614 }
615 UNGCPRO;
616 return tail;
617 }
618
619 static void
620 map_keymap_call (Lisp_Object key, Lisp_Object val, Lisp_Object fun, void *dummy)
621 {
622 call2 (fun, key, val);
623 }
624
625 /* Same as map_keymap_internal, but traverses parent keymaps as well.
626 AUTOLOAD indicates that autoloaded keymaps should be loaded. */
627 void
628 map_keymap (Lisp_Object map, map_keymap_function_t fun, Lisp_Object args,
629 void *data, bool autoload)
630 {
631 struct gcpro gcpro1;
632 GCPRO1 (args);
633 map = get_keymap (map, 1, autoload);
634 while (CONSP (map))
635 {
636 if (KEYMAPP (XCAR (map)))
637 {
638 map_keymap (XCAR (map), fun, args, data, autoload);
639 map = XCDR (map);
640 }
641 else
642 map = map_keymap_internal (map, fun, args, data);
643 if (!CONSP (map))
644 map = get_keymap (map, 0, autoload);
645 }
646 UNGCPRO;
647 }
648
649 static Lisp_Object Qkeymap_canonicalize;
650
651 /* Same as map_keymap, but does it right, properly eliminating duplicate
652 bindings due to inheritance. */
653 void
654 map_keymap_canonical (Lisp_Object map, map_keymap_function_t fun, Lisp_Object args, void *data)
655 {
656 struct gcpro gcpro1;
657 GCPRO1 (args);
658 /* map_keymap_canonical may be used from redisplay (e.g. when building menus)
659 so be careful to ignore errors and to inhibit redisplay. */
660 map = safe_call1 (Qkeymap_canonicalize, map);
661 /* No need to use `map_keymap' here because canonical map has no parent. */
662 map_keymap_internal (map, fun, args, data);
663 UNGCPRO;
664 }
665
666 DEFUN ("map-keymap-internal", Fmap_keymap_internal, Smap_keymap_internal, 2, 2, 0,
667 doc: /* Call FUNCTION once for each event binding in KEYMAP.
668 FUNCTION is called with two arguments: the event that is bound, and
669 the definition it is bound to. The event may be a character range.
670 If KEYMAP has a parent, this function returns it without processing it. */)
671 (Lisp_Object function, Lisp_Object keymap)
672 {
673 struct gcpro gcpro1;
674 GCPRO1 (function);
675 keymap = get_keymap (keymap, 1, 1);
676 keymap = map_keymap_internal (keymap, map_keymap_call, function, NULL);
677 UNGCPRO;
678 return keymap;
679 }
680
681 DEFUN ("map-keymap", Fmap_keymap, Smap_keymap, 2, 3, 0,
682 doc: /* Call FUNCTION once for each event binding in KEYMAP.
683 FUNCTION is called with two arguments: the event that is bound, and
684 the definition it is bound to. The event may be a character range.
685
686 If KEYMAP has a parent, the parent's bindings are included as well.
687 This works recursively: if the parent has itself a parent, then the
688 grandparent's bindings are also included and so on.
689 usage: (map-keymap FUNCTION KEYMAP) */)
690 (Lisp_Object function, Lisp_Object keymap, Lisp_Object sort_first)
691 {
692 if (! NILP (sort_first))
693 return call2 (intern ("map-keymap-sorted"), function, keymap);
694
695 map_keymap (keymap, map_keymap_call, function, NULL, 1);
696 return Qnil;
697 }
698
699 /* Given OBJECT which was found in a slot in a keymap,
700 trace indirect definitions to get the actual definition of that slot.
701 An indirect definition is a list of the form
702 (KEYMAP . INDEX), where KEYMAP is a keymap or a symbol defined as one
703 and INDEX is the object to look up in KEYMAP to yield the definition.
704
705 Also if OBJECT has a menu string as the first element,
706 remove that. Also remove a menu help string as second element.
707
708 If AUTOLOAD, load autoloadable keymaps
709 that are referred to with indirection.
710
711 This can GC because menu_item_eval_property calls Feval. */
712
713 static Lisp_Object
714 get_keyelt (Lisp_Object object, bool autoload)
715 {
716 while (1)
717 {
718 if (!(CONSP (object)))
719 /* This is really the value. */
720 return object;
721
722 /* If the keymap contents looks like (keymap ...) or (lambda ...)
723 then use itself. */
724 else if (EQ (XCAR (object), Qkeymap) || EQ (XCAR (object), Qlambda))
725 return object;
726
727 /* If the keymap contents looks like (menu-item name . DEFN)
728 or (menu-item name DEFN ...) then use DEFN.
729 This is a new format menu item. */
730 else if (EQ (XCAR (object), Qmenu_item))
731 {
732 if (CONSP (XCDR (object)))
733 {
734 Lisp_Object tem;
735
736 object = XCDR (XCDR (object));
737 tem = object;
738 if (CONSP (object))
739 object = XCAR (object);
740
741 /* If there's a `:filter FILTER', apply FILTER to the
742 menu-item's definition to get the real definition to
743 use. */
744 for (; CONSP (tem) && CONSP (XCDR (tem)); tem = XCDR (tem))
745 if (EQ (XCAR (tem), QCfilter) && autoload)
746 {
747 Lisp_Object filter;
748 filter = XCAR (XCDR (tem));
749 filter = list2 (filter, list2 (Qquote, object));
750 object = menu_item_eval_property (filter);
751 break;
752 }
753 }
754 else
755 /* Invalid keymap. */
756 return object;
757 }
758
759 /* If the keymap contents looks like (STRING . DEFN), use DEFN.
760 Keymap alist elements like (CHAR MENUSTRING . DEFN)
761 will be used by HierarKey menus. */
762 else if (STRINGP (XCAR (object)))
763 {
764 object = XCDR (object);
765 /* Also remove a menu help string, if any,
766 following the menu item name. */
767 if (CONSP (object) && STRINGP (XCAR (object)))
768 object = XCDR (object);
769 /* Also remove the sublist that caches key equivalences, if any. */
770 if (CONSP (object) && CONSP (XCAR (object)))
771 {
772 Lisp_Object carcar;
773 carcar = XCAR (XCAR (object));
774 if (NILP (carcar) || VECTORP (carcar))
775 object = XCDR (object);
776 }
777 }
778
779 /* If the contents are (KEYMAP . ELEMENT), go indirect. */
780 else if (KEYMAPP (XCAR (object)))
781 error ("Wow, indirect keymap entry!!");
782 else
783 return object;
784 }
785 }
786
787 static Lisp_Object
788 store_in_keymap (Lisp_Object keymap, register Lisp_Object idx, Lisp_Object def)
789 {
790 /* Flush any reverse-map cache. */
791 where_is_cache = Qnil;
792 where_is_cache_keymaps = Qt;
793
794 if (EQ (idx, Qkeymap))
795 error ("`keymap' is reserved for embedded parent maps");
796
797 /* If we are preparing to dump, and DEF is a menu element
798 with a menu item indicator, copy it to ensure it is not pure. */
799 if (CONSP (def) && PURE_P (def)
800 && (EQ (XCAR (def), Qmenu_item) || STRINGP (XCAR (def))))
801 def = Fcons (XCAR (def), XCDR (def));
802
803 if (!CONSP (keymap) || !EQ (XCAR (keymap), Qkeymap))
804 error ("attempt to define a key in a non-keymap");
805
806 /* If idx is a cons, and the car part is a character, idx must be of
807 the form (FROM-CHAR . TO-CHAR). */
808 if (CONSP (idx) && CHARACTERP (XCAR (idx)))
809 CHECK_CHARACTER_CDR (idx);
810 else
811 /* If idx is a list (some sort of mouse click, perhaps?),
812 the index we want to use is the car of the list, which
813 ought to be a symbol. */
814 idx = EVENT_HEAD (idx);
815
816 /* If idx is a symbol, it might have modifiers, which need to
817 be put in the canonical order. */
818 if (SYMBOLP (idx))
819 idx = reorder_modifiers (idx);
820 else if (INTEGERP (idx))
821 /* Clobber the high bits that can be present on a machine
822 with more than 24 bits of integer. */
823 XSETFASTINT (idx, XINT (idx) & (CHAR_META | (CHAR_META - 1)));
824
825 /* Scan the keymap for a binding of idx. */
826 {
827 Lisp_Object tail;
828
829 /* The cons after which we should insert new bindings. If the
830 keymap has a table element, we record its position here, so new
831 bindings will go after it; this way, the table will stay
832 towards the front of the alist and character lookups in dense
833 keymaps will remain fast. Otherwise, this just points at the
834 front of the keymap. */
835 Lisp_Object insertion_point;
836
837 insertion_point = keymap;
838 for (tail = XCDR (keymap); CONSP (tail); tail = XCDR (tail))
839 {
840 Lisp_Object elt;
841
842 elt = XCAR (tail);
843 if (VECTORP (elt))
844 {
845 if (NATNUMP (idx) && XFASTINT (idx) < ASIZE (elt))
846 {
847 CHECK_IMPURE (elt);
848 ASET (elt, XFASTINT (idx), def);
849 return def;
850 }
851 else if (CONSP (idx) && CHARACTERP (XCAR (idx)))
852 {
853 int from = XFASTINT (XCAR (idx));
854 int to = XFASTINT (XCDR (idx));
855
856 if (to >= ASIZE (elt))
857 to = ASIZE (elt) - 1;
858 for (; from <= to; from++)
859 ASET (elt, from, def);
860 if (to == XFASTINT (XCDR (idx)))
861 /* We have defined all keys in IDX. */
862 return def;
863 }
864 insertion_point = tail;
865 }
866 else if (CHAR_TABLE_P (elt))
867 {
868 /* Character codes with modifiers
869 are not included in a char-table.
870 All character codes without modifiers are included. */
871 if (NATNUMP (idx) && !(XFASTINT (idx) & CHAR_MODIFIER_MASK))
872 {
873 Faset (elt, idx,
874 /* `nil' has a special meaning for char-tables, so
875 we use something else to record an explicitly
876 unbound entry. */
877 NILP (def) ? Qt : def);
878 return def;
879 }
880 else if (CONSP (idx) && CHARACTERP (XCAR (idx)))
881 {
882 Fset_char_table_range (elt, idx, NILP (def) ? Qt : def);
883 return def;
884 }
885 insertion_point = tail;
886 }
887 else if (CONSP (elt))
888 {
889 if (EQ (Qkeymap, XCAR (elt)))
890 { /* A sub keymap. This might be due to a lookup that found
891 two matching bindings (maybe because of a sub keymap).
892 It almost never happens (since the second binding normally
893 only happens in the inherited part of the keymap), but
894 if it does, we want to update the sub-keymap since the
895 main one might be temporary (built by access_keymap). */
896 tail = insertion_point = elt;
897 }
898 else if (EQ (idx, XCAR (elt)))
899 {
900 CHECK_IMPURE (elt);
901 XSETCDR (elt, def);
902 return def;
903 }
904 else if (CONSP (idx) && CHARACTERP (XCAR (idx)))
905 {
906 int from = XFASTINT (XCAR (idx));
907 int to = XFASTINT (XCDR (idx));
908
909 if (from <= XFASTINT (XCAR (elt))
910 && to >= XFASTINT (XCAR (elt)))
911 {
912 XSETCDR (elt, def);
913 if (from == to)
914 return def;
915 }
916 }
917 }
918 else if (EQ (elt, Qkeymap))
919 /* If we find a 'keymap' symbol in the spine of KEYMAP,
920 then we must have found the start of a second keymap
921 being used as the tail of KEYMAP, and a binding for IDX
922 should be inserted before it. */
923 goto keymap_end;
924
925 QUIT;
926 }
927
928 keymap_end:
929 /* We have scanned the entire keymap, and not found a binding for
930 IDX. Let's add one. */
931 {
932 Lisp_Object elt;
933
934 if (CONSP (idx) && CHARACTERP (XCAR (idx)))
935 {
936 /* IDX specifies a range of characters, and not all of them
937 were handled yet, which means this keymap doesn't have a
938 char-table. So, we insert a char-table now. */
939 elt = Fmake_char_table (Qkeymap, Qnil);
940 Fset_char_table_range (elt, idx, NILP (def) ? Qt : def);
941 }
942 else
943 elt = Fcons (idx, def);
944 CHECK_IMPURE (insertion_point);
945 XSETCDR (insertion_point, Fcons (elt, XCDR (insertion_point)));
946 }
947 }
948
949 return def;
950 }
951
952 static Lisp_Object
953 copy_keymap_item (Lisp_Object elt)
954 {
955 Lisp_Object res, tem;
956
957 if (!CONSP (elt))
958 return elt;
959
960 res = tem = elt;
961
962 /* Is this a new format menu item. */
963 if (EQ (XCAR (tem), Qmenu_item))
964 {
965 /* Copy cell with menu-item marker. */
966 res = elt = Fcons (XCAR (tem), XCDR (tem));
967 tem = XCDR (elt);
968 if (CONSP (tem))
969 {
970 /* Copy cell with menu-item name. */
971 XSETCDR (elt, Fcons (XCAR (tem), XCDR (tem)));
972 elt = XCDR (elt);
973 tem = XCDR (elt);
974 }
975 if (CONSP (tem))
976 {
977 /* Copy cell with binding and if the binding is a keymap,
978 copy that. */
979 XSETCDR (elt, Fcons (XCAR (tem), XCDR (tem)));
980 elt = XCDR (elt);
981 tem = XCAR (elt);
982 if (CONSP (tem) && EQ (XCAR (tem), Qkeymap))
983 XSETCAR (elt, Fcopy_keymap (tem));
984 tem = XCDR (elt);
985 if (CONSP (tem) && CONSP (XCAR (tem)))
986 /* Delete cache for key equivalences. */
987 XSETCDR (elt, XCDR (tem));
988 }
989 }
990 else
991 {
992 /* It may be an old format menu item.
993 Skip the optional menu string. */
994 if (STRINGP (XCAR (tem)))
995 {
996 /* Copy the cell, since copy-alist didn't go this deep. */
997 res = elt = Fcons (XCAR (tem), XCDR (tem));
998 tem = XCDR (elt);
999 /* Also skip the optional menu help string. */
1000 if (CONSP (tem) && STRINGP (XCAR (tem)))
1001 {
1002 XSETCDR (elt, Fcons (XCAR (tem), XCDR (tem)));
1003 elt = XCDR (elt);
1004 tem = XCDR (elt);
1005 }
1006 /* There may also be a list that caches key equivalences.
1007 Just delete it for the new keymap. */
1008 if (CONSP (tem)
1009 && CONSP (XCAR (tem))
1010 && (NILP (XCAR (XCAR (tem)))
1011 || VECTORP (XCAR (XCAR (tem)))))
1012 {
1013 XSETCDR (elt, XCDR (tem));
1014 tem = XCDR (tem);
1015 }
1016 if (CONSP (tem) && EQ (XCAR (tem), Qkeymap))
1017 XSETCDR (elt, Fcopy_keymap (tem));
1018 }
1019 else if (EQ (XCAR (tem), Qkeymap))
1020 res = Fcopy_keymap (elt);
1021 }
1022 return res;
1023 }
1024
1025 static void
1026 copy_keymap_1 (Lisp_Object chartable, Lisp_Object idx, Lisp_Object elt)
1027 {
1028 Fset_char_table_range (chartable, idx, copy_keymap_item (elt));
1029 }
1030
1031 DEFUN ("copy-keymap", Fcopy_keymap, Scopy_keymap, 1, 1, 0,
1032 doc: /* Return a copy of the keymap KEYMAP.
1033 The copy starts out with the same definitions of KEYMAP,
1034 but changing either the copy or KEYMAP does not affect the other.
1035 Any key definitions that are subkeymaps are recursively copied.
1036 However, a key definition which is a symbol whose definition is a keymap
1037 is not copied. */)
1038 (Lisp_Object keymap)
1039 {
1040 register Lisp_Object copy, tail;
1041 keymap = get_keymap (keymap, 1, 0);
1042 copy = tail = Fcons (Qkeymap, Qnil);
1043 keymap = XCDR (keymap); /* Skip the `keymap' symbol. */
1044
1045 while (CONSP (keymap) && !EQ (XCAR (keymap), Qkeymap))
1046 {
1047 Lisp_Object elt = XCAR (keymap);
1048 if (CHAR_TABLE_P (elt))
1049 {
1050 elt = Fcopy_sequence (elt);
1051 map_char_table (copy_keymap_1, Qnil, elt, elt);
1052 }
1053 else if (VECTORP (elt))
1054 {
1055 int i;
1056 elt = Fcopy_sequence (elt);
1057 for (i = 0; i < ASIZE (elt); i++)
1058 ASET (elt, i, copy_keymap_item (AREF (elt, i)));
1059 }
1060 else if (CONSP (elt))
1061 {
1062 if (EQ (XCAR (elt), Qkeymap))
1063 /* This is a sub keymap. */
1064 elt = Fcopy_keymap (elt);
1065 else
1066 elt = Fcons (XCAR (elt), copy_keymap_item (XCDR (elt)));
1067 }
1068 XSETCDR (tail, Fcons (elt, Qnil));
1069 tail = XCDR (tail);
1070 keymap = XCDR (keymap);
1071 }
1072 XSETCDR (tail, keymap);
1073 return copy;
1074 }
1075 \f
1076 /* Simple Keymap mutators and accessors. */
1077
1078 /* GC is possible in this function if it autoloads a keymap. */
1079
1080 DEFUN ("define-key", Fdefine_key, Sdefine_key, 3, 3, 0,
1081 doc: /* In KEYMAP, define key sequence KEY as DEF.
1082 KEYMAP is a keymap.
1083
1084 KEY is a string or a vector of symbols and characters, representing a
1085 sequence of keystrokes and events. Non-ASCII characters with codes
1086 above 127 (such as ISO Latin-1) can be represented by vectors.
1087 Two types of vector have special meanings:
1088 [remap COMMAND] remaps any key binding for COMMAND.
1089 [t] creates a default definition, which applies to any event with no
1090 other definition in KEYMAP.
1091
1092 DEF is anything that can be a key's definition:
1093 nil (means key is undefined in this keymap),
1094 a command (a Lisp function suitable for interactive calling),
1095 a string (treated as a keyboard macro),
1096 a keymap (to define a prefix key),
1097 a symbol (when the key is looked up, the symbol will stand for its
1098 function definition, which should at that time be one of the above,
1099 or another symbol whose function definition is used, etc.),
1100 a cons (STRING . DEFN), meaning that DEFN is the definition
1101 (DEFN should be a valid definition in its own right),
1102 or a cons (MAP . CHAR), meaning use definition of CHAR in keymap MAP,
1103 or an extended menu item definition.
1104 (See info node `(elisp)Extended Menu Items'.)
1105
1106 If KEYMAP is a sparse keymap with a binding for KEY, the existing
1107 binding is altered. If there is no binding for KEY, the new pair
1108 binding KEY to DEF is added at the front of KEYMAP. */)
1109 (Lisp_Object keymap, Lisp_Object key, Lisp_Object def)
1110 {
1111 ptrdiff_t idx;
1112 Lisp_Object c;
1113 Lisp_Object cmd;
1114 bool metized = 0;
1115 int meta_bit;
1116 ptrdiff_t length;
1117 struct gcpro gcpro1, gcpro2, gcpro3;
1118
1119 GCPRO3 (keymap, key, def);
1120 keymap = get_keymap (keymap, 1, 1);
1121
1122 CHECK_VECTOR_OR_STRING (key);
1123
1124 length = XFASTINT (Flength (key));
1125 if (length == 0)
1126 RETURN_UNGCPRO (Qnil);
1127
1128 if (SYMBOLP (def) && !EQ (Vdefine_key_rebound_commands, Qt))
1129 Vdefine_key_rebound_commands = Fcons (def, Vdefine_key_rebound_commands);
1130
1131 meta_bit = (VECTORP (key) || (STRINGP (key) && STRING_MULTIBYTE (key))
1132 ? meta_modifier : 0x80);
1133
1134 if (VECTORP (def) && ASIZE (def) > 0 && CONSP (AREF (def, 0)))
1135 { /* DEF is apparently an XEmacs-style keyboard macro. */
1136 Lisp_Object tmp = Fmake_vector (make_number (ASIZE (def)), Qnil);
1137 ptrdiff_t i = ASIZE (def);
1138 while (--i >= 0)
1139 {
1140 Lisp_Object defi = AREF (def, i);
1141 if (CONSP (defi) && lucid_event_type_list_p (defi))
1142 defi = Fevent_convert_list (defi);
1143 ASET (tmp, i, defi);
1144 }
1145 def = tmp;
1146 }
1147
1148 idx = 0;
1149 while (1)
1150 {
1151 c = Faref (key, make_number (idx));
1152
1153 if (CONSP (c))
1154 {
1155 /* C may be a Lucid style event type list or a cons (FROM .
1156 TO) specifying a range of characters. */
1157 if (lucid_event_type_list_p (c))
1158 c = Fevent_convert_list (c);
1159 else if (CHARACTERP (XCAR (c)))
1160 CHECK_CHARACTER_CDR (c);
1161 }
1162
1163 if (SYMBOLP (c))
1164 silly_event_symbol_error (c);
1165
1166 if (INTEGERP (c)
1167 && (XINT (c) & meta_bit)
1168 && !metized)
1169 {
1170 c = meta_prefix_char;
1171 metized = 1;
1172 }
1173 else
1174 {
1175 if (INTEGERP (c))
1176 XSETINT (c, XINT (c) & ~meta_bit);
1177
1178 metized = 0;
1179 idx++;
1180 }
1181
1182 if (!INTEGERP (c) && !SYMBOLP (c)
1183 && (!CONSP (c)
1184 /* If C is a range, it must be a leaf. */
1185 || (INTEGERP (XCAR (c)) && idx != length)))
1186 message_with_string ("Key sequence contains invalid event %s", c, 1);
1187
1188 if (idx == length)
1189 RETURN_UNGCPRO (store_in_keymap (keymap, c, def));
1190
1191 cmd = access_keymap (keymap, c, 0, 1, 1);
1192
1193 /* If this key is undefined, make it a prefix. */
1194 if (NILP (cmd))
1195 cmd = define_as_prefix (keymap, c);
1196
1197 keymap = get_keymap (cmd, 0, 1);
1198 if (!CONSP (keymap))
1199 {
1200 const char *trailing_esc = ((EQ (c, meta_prefix_char) && metized)
1201 ? (idx == 0 ? "ESC" : " ESC")
1202 : "");
1203
1204 /* We must use Fkey_description rather than just passing key to
1205 error; key might be a vector, not a string. */
1206 error ("Key sequence %s starts with non-prefix key %s%s",
1207 SDATA (Fkey_description (key, Qnil)),
1208 SDATA (Fkey_description (Fsubstring (key, make_number (0),
1209 make_number (idx)),
1210 Qnil)),
1211 trailing_esc);
1212 }
1213 }
1214 }
1215
1216 /* This function may GC (it calls Fkey_binding). */
1217
1218 DEFUN ("command-remapping", Fcommand_remapping, Scommand_remapping, 1, 3, 0,
1219 doc: /* Return the remapping for command COMMAND.
1220 Returns nil if COMMAND is not remapped (or not a symbol).
1221
1222 If the optional argument POSITION is non-nil, it specifies a mouse
1223 position as returned by `event-start' and `event-end', and the
1224 remapping occurs in the keymaps associated with it. It can also be a
1225 number or marker, in which case the keymap properties at the specified
1226 buffer position instead of point are used. The KEYMAPS argument is
1227 ignored if POSITION is non-nil.
1228
1229 If the optional argument KEYMAPS is non-nil, it should be a list of
1230 keymaps to search for command remapping. Otherwise, search for the
1231 remapping in all currently active keymaps. */)
1232 (Lisp_Object command, Lisp_Object position, Lisp_Object keymaps)
1233 {
1234 if (!SYMBOLP (command))
1235 return Qnil;
1236
1237 ASET (command_remapping_vector, 1, command);
1238
1239 if (NILP (keymaps))
1240 command = Fkey_binding (command_remapping_vector, Qnil, Qt, position);
1241 else
1242 command = Flookup_key (Fcons (Qkeymap, keymaps),
1243 command_remapping_vector, Qnil);
1244 return INTEGERP (command) ? Qnil : command;
1245 }
1246
1247 /* Value is number if KEY is too long; nil if valid but has no definition. */
1248 /* GC is possible in this function. */
1249
1250 DEFUN ("lookup-key", Flookup_key, Slookup_key, 2, 3, 0,
1251 doc: /* In keymap KEYMAP, look up key sequence KEY. Return the definition.
1252 A value of nil means undefined. See doc of `define-key'
1253 for kinds of definitions.
1254
1255 A number as value means KEY is "too long";
1256 that is, characters or symbols in it except for the last one
1257 fail to be a valid sequence of prefix characters in KEYMAP.
1258 The number is how many characters at the front of KEY
1259 it takes to reach a non-prefix key.
1260
1261 Normally, `lookup-key' ignores bindings for t, which act as default
1262 bindings, used when nothing else in the keymap applies; this makes it
1263 usable as a general function for probing keymaps. However, if the
1264 third optional argument ACCEPT-DEFAULT is non-nil, `lookup-key' will
1265 recognize the default bindings, just as `read-key-sequence' does. */)
1266 (Lisp_Object keymap, Lisp_Object key, Lisp_Object accept_default)
1267 {
1268 ptrdiff_t idx;
1269 Lisp_Object cmd;
1270 Lisp_Object c;
1271 ptrdiff_t length;
1272 bool t_ok = !NILP (accept_default);
1273 struct gcpro gcpro1, gcpro2;
1274
1275 GCPRO2 (keymap, key);
1276 keymap = get_keymap (keymap, 1, 1);
1277
1278 CHECK_VECTOR_OR_STRING (key);
1279
1280 length = XFASTINT (Flength (key));
1281 if (length == 0)
1282 RETURN_UNGCPRO (keymap);
1283
1284 idx = 0;
1285 while (1)
1286 {
1287 c = Faref (key, make_number (idx++));
1288
1289 if (CONSP (c) && lucid_event_type_list_p (c))
1290 c = Fevent_convert_list (c);
1291
1292 /* Turn the 8th bit of string chars into a meta modifier. */
1293 if (STRINGP (key) && XINT (c) & 0x80 && !STRING_MULTIBYTE (key))
1294 XSETINT (c, (XINT (c) | meta_modifier) & ~0x80);
1295
1296 /* Allow string since binding for `menu-bar-select-buffer'
1297 includes the buffer name in the key sequence. */
1298 if (!INTEGERP (c) && !SYMBOLP (c) && !CONSP (c) && !STRINGP (c))
1299 message_with_string ("Key sequence contains invalid event %s", c, 1);
1300
1301 cmd = access_keymap (keymap, c, t_ok, 0, 1);
1302 if (idx == length)
1303 RETURN_UNGCPRO (cmd);
1304
1305 keymap = get_keymap (cmd, 0, 1);
1306 if (!CONSP (keymap))
1307 RETURN_UNGCPRO (make_number (idx));
1308
1309 QUIT;
1310 }
1311 }
1312
1313 /* Make KEYMAP define event C as a keymap (i.e., as a prefix).
1314 Assume that currently it does not define C at all.
1315 Return the keymap. */
1316
1317 static Lisp_Object
1318 define_as_prefix (Lisp_Object keymap, Lisp_Object c)
1319 {
1320 Lisp_Object cmd;
1321
1322 cmd = Fmake_sparse_keymap (Qnil);
1323 store_in_keymap (keymap, c, cmd);
1324
1325 return cmd;
1326 }
1327
1328 /* Append a key to the end of a key sequence. We always make a vector. */
1329
1330 static Lisp_Object
1331 append_key (Lisp_Object key_sequence, Lisp_Object key)
1332 {
1333 Lisp_Object args[2];
1334
1335 args[0] = key_sequence;
1336
1337 args[1] = Fcons (key, Qnil);
1338 return Fvconcat (2, args);
1339 }
1340
1341 /* Given a event type C which is a symbol,
1342 signal an error if is a mistake such as RET or M-RET or C-DEL, etc. */
1343
1344 static void
1345 silly_event_symbol_error (Lisp_Object c)
1346 {
1347 Lisp_Object parsed, base, name, assoc;
1348 int modifiers;
1349
1350 parsed = parse_modifiers (c);
1351 modifiers = XFASTINT (XCAR (XCDR (parsed)));
1352 base = XCAR (parsed);
1353 name = Fsymbol_name (base);
1354 /* This alist includes elements such as ("RET" . "\\r"). */
1355 assoc = Fassoc (name, exclude_keys);
1356
1357 if (! NILP (assoc))
1358 {
1359 char new_mods[sizeof ("\\A-\\C-\\H-\\M-\\S-\\s-")];
1360 char *p = new_mods;
1361 Lisp_Object keystring;
1362 if (modifiers & alt_modifier)
1363 { *p++ = '\\'; *p++ = 'A'; *p++ = '-'; }
1364 if (modifiers & ctrl_modifier)
1365 { *p++ = '\\'; *p++ = 'C'; *p++ = '-'; }
1366 if (modifiers & hyper_modifier)
1367 { *p++ = '\\'; *p++ = 'H'; *p++ = '-'; }
1368 if (modifiers & meta_modifier)
1369 { *p++ = '\\'; *p++ = 'M'; *p++ = '-'; }
1370 if (modifiers & shift_modifier)
1371 { *p++ = '\\'; *p++ = 'S'; *p++ = '-'; }
1372 if (modifiers & super_modifier)
1373 { *p++ = '\\'; *p++ = 's'; *p++ = '-'; }
1374 *p = 0;
1375
1376 c = reorder_modifiers (c);
1377 keystring = concat2 (build_string (new_mods), XCDR (assoc));
1378
1379 error ((modifiers & ~meta_modifier
1380 ? "To bind the key %s, use [?%s], not [%s]"
1381 : "To bind the key %s, use \"%s\", not [%s]"),
1382 SDATA (SYMBOL_NAME (c)), SDATA (keystring),
1383 SDATA (SYMBOL_NAME (c)));
1384 }
1385 }
1386 \f
1387 /* Global, local, and minor mode keymap stuff. */
1388
1389 /* We can't put these variables inside current_minor_maps, since under
1390 some systems, static gets macro-defined to be the empty string.
1391 Ickypoo. */
1392 static Lisp_Object *cmm_modes = NULL, *cmm_maps = NULL;
1393 static ptrdiff_t cmm_size = 0;
1394
1395 /* Store a pointer to an array of the currently active minor modes in
1396 *modeptr, a pointer to an array of the keymaps of the currently
1397 active minor modes in *mapptr, and return the number of maps
1398 *mapptr contains.
1399
1400 This function always returns a pointer to the same buffer, and may
1401 free or reallocate it, so if you want to keep it for a long time or
1402 hand it out to lisp code, copy it. This procedure will be called
1403 for every key sequence read, so the nice lispy approach (return a
1404 new assoclist, list, what have you) for each invocation would
1405 result in a lot of consing over time.
1406
1407 If we used xrealloc/xmalloc and ran out of memory, they would throw
1408 back to the command loop, which would try to read a key sequence,
1409 which would call this function again, resulting in an infinite
1410 loop. Instead, we'll use realloc/malloc and silently truncate the
1411 list, let the key sequence be read, and hope some other piece of
1412 code signals the error. */
1413 ptrdiff_t
1414 current_minor_maps (Lisp_Object **modeptr, Lisp_Object **mapptr)
1415 {
1416 ptrdiff_t i = 0;
1417 int list_number = 0;
1418 Lisp_Object alist, assoc, var, val;
1419 Lisp_Object emulation_alists;
1420 Lisp_Object lists[2];
1421
1422 emulation_alists = Vemulation_mode_map_alists;
1423 lists[0] = Vminor_mode_overriding_map_alist;
1424 lists[1] = Vminor_mode_map_alist;
1425
1426 for (list_number = 0; list_number < 2; list_number++)
1427 {
1428 if (CONSP (emulation_alists))
1429 {
1430 alist = XCAR (emulation_alists);
1431 emulation_alists = XCDR (emulation_alists);
1432 if (SYMBOLP (alist))
1433 alist = find_symbol_value (alist);
1434 list_number = -1;
1435 }
1436 else
1437 alist = lists[list_number];
1438
1439 for ( ; CONSP (alist); alist = XCDR (alist))
1440 if ((assoc = XCAR (alist), CONSP (assoc))
1441 && (var = XCAR (assoc), SYMBOLP (var))
1442 && (val = find_symbol_value (var), !EQ (val, Qunbound))
1443 && !NILP (val))
1444 {
1445 Lisp_Object temp;
1446
1447 /* If a variable has an entry in Vminor_mode_overriding_map_alist,
1448 and also an entry in Vminor_mode_map_alist,
1449 ignore the latter. */
1450 if (list_number == 1)
1451 {
1452 val = assq_no_quit (var, lists[0]);
1453 if (!NILP (val))
1454 continue;
1455 }
1456
1457 if (i >= cmm_size)
1458 {
1459 ptrdiff_t newsize, allocsize;
1460 Lisp_Object *newmodes, *newmaps;
1461
1462 /* Check for size calculation overflow. Other code
1463 (e.g., read_key_sequence) adds 3 to the count
1464 later, so subtract 3 from the limit here. */
1465 if (min (PTRDIFF_MAX, SIZE_MAX) / (2 * sizeof *newmodes) - 3
1466 < cmm_size)
1467 break;
1468
1469 newsize = cmm_size == 0 ? 30 : cmm_size * 2;
1470 allocsize = newsize * sizeof *newmodes;
1471
1472 /* Use malloc here. See the comment above this function.
1473 Avoid realloc here; it causes spurious traps on GNU/Linux [KFS] */
1474 block_input ();
1475 newmodes = malloc (allocsize);
1476 if (newmodes)
1477 {
1478 if (cmm_modes)
1479 {
1480 memcpy (newmodes, cmm_modes,
1481 cmm_size * sizeof cmm_modes[0]);
1482 free (cmm_modes);
1483 }
1484 cmm_modes = newmodes;
1485 }
1486
1487 newmaps = malloc (allocsize);
1488 if (newmaps)
1489 {
1490 if (cmm_maps)
1491 {
1492 memcpy (newmaps, cmm_maps,
1493 cmm_size * sizeof cmm_maps[0]);
1494 free (cmm_maps);
1495 }
1496 cmm_maps = newmaps;
1497 }
1498 unblock_input ();
1499
1500 if (newmodes == NULL || newmaps == NULL)
1501 break;
1502 cmm_size = newsize;
1503 }
1504
1505 /* Get the keymap definition--or nil if it is not defined. */
1506 temp = Findirect_function (XCDR (assoc), Qt);
1507 if (!NILP (temp))
1508 {
1509 cmm_modes[i] = var;
1510 cmm_maps [i] = temp;
1511 i++;
1512 }
1513 }
1514 }
1515
1516 if (modeptr) *modeptr = cmm_modes;
1517 if (mapptr) *mapptr = cmm_maps;
1518 return i;
1519 }
1520
1521 /* Return the offset of POSITION, a click position, in the style of
1522 the respective argument of Fkey_binding. */
1523 static ptrdiff_t
1524 click_position (Lisp_Object position)
1525 {
1526 EMACS_INT pos = (INTEGERP (position) ? XINT (position)
1527 : MARKERP (position) ? marker_position (position)
1528 : PT);
1529 if (! (BEGV <= pos && pos <= ZV))
1530 args_out_of_range (Fcurrent_buffer (), position);
1531 return pos;
1532 }
1533
1534 DEFUN ("current-active-maps", Fcurrent_active_maps, Scurrent_active_maps,
1535 0, 2, 0,
1536 doc: /* Return a list of the currently active keymaps.
1537 OLP if non-nil indicates that we should obey `overriding-local-map' and
1538 `overriding-terminal-local-map'. POSITION can specify a click position
1539 like in the respective argument of `key-binding'. */)
1540 (Lisp_Object olp, Lisp_Object position)
1541 {
1542 ptrdiff_t count = SPECPDL_INDEX ();
1543
1544 Lisp_Object keymaps = Fcons (current_global_map, Qnil);
1545
1546 /* If a mouse click position is given, our variables are based on
1547 the buffer clicked on, not the current buffer. So we may have to
1548 switch the buffer here. */
1549
1550 if (CONSP (position))
1551 {
1552 Lisp_Object window;
1553
1554 window = POSN_WINDOW (position);
1555
1556 if (WINDOWP (window)
1557 && BUFFERP (XWINDOW (window)->buffer)
1558 && XBUFFER (XWINDOW (window)->buffer) != current_buffer)
1559 {
1560 /* Arrange to go back to the original buffer once we're done
1561 processing the key sequence. We don't use
1562 save_excursion_{save,restore} here, in analogy to
1563 `read-key-sequence' to avoid saving point. Maybe this
1564 would not be a problem here, but it is easier to keep
1565 things the same.
1566 */
1567 record_unwind_current_buffer ();
1568 set_buffer_internal (XBUFFER (XWINDOW (window)->buffer));
1569 }
1570 }
1571
1572 if (!NILP (olp))
1573 {
1574 if (!NILP (KVAR (current_kboard, Voverriding_terminal_local_map)))
1575 keymaps = Fcons (KVAR (current_kboard, Voverriding_terminal_local_map),
1576 keymaps);
1577 /* The doc said that overriding-terminal-local-map should
1578 override overriding-local-map. The code used them both,
1579 but it seems clearer to use just one. rms, jan 2005. */
1580 else if (!NILP (Voverriding_local_map))
1581 keymaps = Fcons (Voverriding_local_map, keymaps);
1582 }
1583 if (NILP (XCDR (keymaps)))
1584 {
1585 Lisp_Object *maps;
1586 int nmaps, i;
1587 ptrdiff_t pt = click_position (position);
1588 /* This usually returns the buffer's local map,
1589 but that can be overridden by a `local-map' property. */
1590 Lisp_Object local_map = get_local_map (pt, current_buffer, Qlocal_map);
1591 /* This returns nil unless there is a `keymap' property. */
1592 Lisp_Object keymap = get_local_map (pt, current_buffer, Qkeymap);
1593
1594 if (CONSP (position))
1595 {
1596 Lisp_Object string = POSN_STRING (position);
1597
1598 /* For a mouse click, get the local text-property keymap
1599 of the place clicked on, rather than point. */
1600
1601 if (POSN_INBUFFER_P (position))
1602 {
1603 Lisp_Object pos;
1604
1605 pos = POSN_BUFFER_POSN (position);
1606 if (INTEGERP (pos)
1607 && XINT (pos) >= BEG && XINT (pos) <= Z)
1608 {
1609 local_map = get_local_map (XINT (pos),
1610 current_buffer, Qlocal_map);
1611
1612 keymap = get_local_map (XINT (pos),
1613 current_buffer, Qkeymap);
1614 }
1615 }
1616
1617 /* If on a mode line string with a local keymap,
1618 or for a click on a string, i.e. overlay string or a
1619 string displayed via the `display' property,
1620 consider `local-map' and `keymap' properties of
1621 that string. */
1622
1623 if (CONSP (string) && STRINGP (XCAR (string)))
1624 {
1625 Lisp_Object pos, map;
1626
1627 pos = XCDR (string);
1628 string = XCAR (string);
1629 if (INTEGERP (pos)
1630 && XINT (pos) >= 0
1631 && XINT (pos) < SCHARS (string))
1632 {
1633 map = Fget_text_property (pos, Qlocal_map, string);
1634 if (!NILP (map))
1635 local_map = map;
1636
1637 map = Fget_text_property (pos, Qkeymap, string);
1638 if (!NILP (map))
1639 keymap = map;
1640 }
1641 }
1642
1643 }
1644
1645 if (!NILP (local_map))
1646 keymaps = Fcons (local_map, keymaps);
1647
1648 /* Now put all the minor mode keymaps on the list. */
1649 nmaps = current_minor_maps (0, &maps);
1650
1651 for (i = --nmaps; i >= 0; i--)
1652 if (!NILP (maps[i]))
1653 keymaps = Fcons (maps[i], keymaps);
1654
1655 if (!NILP (keymap))
1656 keymaps = Fcons (keymap, keymaps);
1657 }
1658
1659 unbind_to (count, Qnil);
1660
1661 return keymaps;
1662 }
1663
1664 /* GC is possible in this function if it autoloads a keymap. */
1665
1666 DEFUN ("key-binding", Fkey_binding, Skey_binding, 1, 4, 0,
1667 doc: /* Return the binding for command KEY in current keymaps.
1668 KEY is a string or vector, a sequence of keystrokes.
1669 The binding is probably a symbol with a function definition.
1670
1671 Normally, `key-binding' ignores bindings for t, which act as default
1672 bindings, used when nothing else in the keymap applies; this makes it
1673 usable as a general function for probing keymaps. However, if the
1674 optional second argument ACCEPT-DEFAULT is non-nil, `key-binding' does
1675 recognize the default bindings, just as `read-key-sequence' does.
1676
1677 Like the normal command loop, `key-binding' will remap the command
1678 resulting from looking up KEY by looking up the command in the
1679 current keymaps. However, if the optional third argument NO-REMAP
1680 is non-nil, `key-binding' returns the unmapped command.
1681
1682 If KEY is a key sequence initiated with the mouse, the used keymaps
1683 will depend on the clicked mouse position with regard to the buffer
1684 and possible local keymaps on strings.
1685
1686 If the optional argument POSITION is non-nil, it specifies a mouse
1687 position as returned by `event-start' and `event-end', and the lookup
1688 occurs in the keymaps associated with it instead of KEY. It can also
1689 be a number or marker, in which case the keymap properties at the
1690 specified buffer position instead of point are used.
1691 */)
1692 (Lisp_Object key, Lisp_Object accept_default, Lisp_Object no_remap, Lisp_Object position)
1693 {
1694 Lisp_Object value;
1695
1696 if (NILP (position) && VECTORP (key))
1697 {
1698 Lisp_Object event
1699 /* mouse events may have a symbolic prefix indicating the
1700 scrollbar or mode line */
1701 = AREF (key, SYMBOLP (AREF (key, 0)) && ASIZE (key) > 1 ? 1 : 0);
1702
1703 /* We are not interested in locations without event data */
1704
1705 if (EVENT_HAS_PARAMETERS (event) && CONSP (XCDR (event)))
1706 {
1707 Lisp_Object kind = EVENT_HEAD_KIND (EVENT_HEAD (event));
1708 if (EQ (kind, Qmouse_click))
1709 position = EVENT_START (event);
1710 }
1711 }
1712
1713 value = Flookup_key (Fcons (Qkeymap, Fcurrent_active_maps (Qt, position)),
1714 key, accept_default);
1715
1716 if (NILP (value) || INTEGERP (value))
1717 return Qnil;
1718
1719 /* If the result of the ordinary keymap lookup is an interactive
1720 command, look for a key binding (ie. remapping) for that command. */
1721
1722 if (NILP (no_remap) && SYMBOLP (value))
1723 {
1724 Lisp_Object value1;
1725 if (value1 = Fcommand_remapping (value, position, Qnil), !NILP (value1))
1726 value = value1;
1727 }
1728
1729 return value;
1730 }
1731
1732 /* GC is possible in this function if it autoloads a keymap. */
1733
1734 DEFUN ("local-key-binding", Flocal_key_binding, Slocal_key_binding, 1, 2, 0,
1735 doc: /* Return the binding for command KEYS in current local keymap only.
1736 KEYS is a string or vector, a sequence of keystrokes.
1737 The binding is probably a symbol with a function definition.
1738
1739 If optional argument ACCEPT-DEFAULT is non-nil, recognize default
1740 bindings; see the description of `lookup-key' for more details about this. */)
1741 (Lisp_Object keys, Lisp_Object accept_default)
1742 {
1743 register Lisp_Object map;
1744 map = BVAR (current_buffer, keymap);
1745 if (NILP (map))
1746 return Qnil;
1747 return Flookup_key (map, keys, accept_default);
1748 }
1749
1750 /* GC is possible in this function if it autoloads a keymap. */
1751
1752 DEFUN ("global-key-binding", Fglobal_key_binding, Sglobal_key_binding, 1, 2, 0,
1753 doc: /* Return the binding for command KEYS in current global keymap only.
1754 KEYS is a string or vector, a sequence of keystrokes.
1755 The binding is probably a symbol with a function definition.
1756 This function's return values are the same as those of `lookup-key'
1757 \(which see).
1758
1759 If optional argument ACCEPT-DEFAULT is non-nil, recognize default
1760 bindings; see the description of `lookup-key' for more details about this. */)
1761 (Lisp_Object keys, Lisp_Object accept_default)
1762 {
1763 return Flookup_key (current_global_map, keys, accept_default);
1764 }
1765
1766 /* GC is possible in this function if it autoloads a keymap. */
1767
1768 DEFUN ("minor-mode-key-binding", Fminor_mode_key_binding, Sminor_mode_key_binding, 1, 2, 0,
1769 doc: /* Find the visible minor mode bindings of KEY.
1770 Return an alist of pairs (MODENAME . BINDING), where MODENAME is
1771 the symbol which names the minor mode binding KEY, and BINDING is
1772 KEY's definition in that mode. In particular, if KEY has no
1773 minor-mode bindings, return nil. If the first binding is a
1774 non-prefix, all subsequent bindings will be omitted, since they would
1775 be ignored. Similarly, the list doesn't include non-prefix bindings
1776 that come after prefix bindings.
1777
1778 If optional argument ACCEPT-DEFAULT is non-nil, recognize default
1779 bindings; see the description of `lookup-key' for more details about this. */)
1780 (Lisp_Object key, Lisp_Object accept_default)
1781 {
1782 Lisp_Object *modes, *maps;
1783 int nmaps;
1784 Lisp_Object binding;
1785 int i, j;
1786 struct gcpro gcpro1, gcpro2;
1787
1788 nmaps = current_minor_maps (&modes, &maps);
1789 /* Note that all these maps are GCPRO'd
1790 in the places where we found them. */
1791
1792 binding = Qnil;
1793 GCPRO2 (key, binding);
1794
1795 for (i = j = 0; i < nmaps; i++)
1796 if (!NILP (maps[i])
1797 && !NILP (binding = Flookup_key (maps[i], key, accept_default))
1798 && !INTEGERP (binding))
1799 {
1800 if (KEYMAPP (binding))
1801 maps[j++] = Fcons (modes[i], binding);
1802 else if (j == 0)
1803 RETURN_UNGCPRO (Fcons (Fcons (modes[i], binding), Qnil));
1804 }
1805
1806 UNGCPRO;
1807 return Flist (j, maps);
1808 }
1809
1810 DEFUN ("define-prefix-command", Fdefine_prefix_command, Sdefine_prefix_command, 1, 3, 0,
1811 doc: /* Define COMMAND as a prefix command. COMMAND should be a symbol.
1812 A new sparse keymap is stored as COMMAND's function definition and its value.
1813 If a second optional argument MAPVAR is given, the map is stored as
1814 its value instead of as COMMAND's value; but COMMAND is still defined
1815 as a function.
1816 The third optional argument NAME, if given, supplies a menu name
1817 string for the map. This is required to use the keymap as a menu.
1818 This function returns COMMAND. */)
1819 (Lisp_Object command, Lisp_Object mapvar, Lisp_Object name)
1820 {
1821 Lisp_Object map;
1822 map = Fmake_sparse_keymap (name);
1823 Ffset (command, map);
1824 if (!NILP (mapvar))
1825 Fset (mapvar, map);
1826 else
1827 Fset (command, map);
1828 return command;
1829 }
1830
1831 DEFUN ("use-global-map", Fuse_global_map, Suse_global_map, 1, 1, 0,
1832 doc: /* Select KEYMAP as the global keymap. */)
1833 (Lisp_Object keymap)
1834 {
1835 keymap = get_keymap (keymap, 1, 1);
1836 current_global_map = keymap;
1837
1838 return Qnil;
1839 }
1840
1841 DEFUN ("use-local-map", Fuse_local_map, Suse_local_map, 1, 1, 0,
1842 doc: /* Select KEYMAP as the local keymap.
1843 If KEYMAP is nil, that means no local keymap. */)
1844 (Lisp_Object keymap)
1845 {
1846 if (!NILP (keymap))
1847 keymap = get_keymap (keymap, 1, 1);
1848
1849 bset_keymap (current_buffer, keymap);
1850
1851 return Qnil;
1852 }
1853
1854 DEFUN ("current-local-map", Fcurrent_local_map, Scurrent_local_map, 0, 0, 0,
1855 doc: /* Return current buffer's local keymap, or nil if it has none.
1856 Normally the local keymap is set by the major mode with `use-local-map'. */)
1857 (void)
1858 {
1859 return BVAR (current_buffer, keymap);
1860 }
1861
1862 DEFUN ("current-global-map", Fcurrent_global_map, Scurrent_global_map, 0, 0, 0,
1863 doc: /* Return the current global keymap. */)
1864 (void)
1865 {
1866 return current_global_map;
1867 }
1868
1869 DEFUN ("current-minor-mode-maps", Fcurrent_minor_mode_maps, Scurrent_minor_mode_maps, 0, 0, 0,
1870 doc: /* Return a list of keymaps for the minor modes of the current buffer. */)
1871 (void)
1872 {
1873 Lisp_Object *maps;
1874 int nmaps = current_minor_maps (0, &maps);
1875
1876 return Flist (nmaps, maps);
1877 }
1878 \f
1879 /* Help functions for describing and documenting keymaps. */
1880
1881 struct accessible_keymaps_data {
1882 Lisp_Object maps, tail, thisseq;
1883 /* Does the current sequence end in the meta-prefix-char? */
1884 bool is_metized;
1885 };
1886
1887 static void
1888 accessible_keymaps_1 (Lisp_Object key, Lisp_Object cmd, Lisp_Object args, void *data)
1889 /* Use void* data to be compatible with map_keymap_function_t. */
1890 {
1891 struct accessible_keymaps_data *d = data; /* Cast! */
1892 Lisp_Object maps = d->maps;
1893 Lisp_Object tail = d->tail;
1894 Lisp_Object thisseq = d->thisseq;
1895 bool is_metized = d->is_metized && INTEGERP (key);
1896 Lisp_Object tem;
1897
1898 cmd = get_keymap (get_keyelt (cmd, 0), 0, 0);
1899 if (NILP (cmd))
1900 return;
1901
1902 /* Look for and break cycles. */
1903 while (!NILP (tem = Frassq (cmd, maps)))
1904 {
1905 Lisp_Object prefix = XCAR (tem);
1906 ptrdiff_t lim = XINT (Flength (XCAR (tem)));
1907 if (lim <= XINT (Flength (thisseq)))
1908 { /* This keymap was already seen with a smaller prefix. */
1909 ptrdiff_t i = 0;
1910 while (i < lim && EQ (Faref (prefix, make_number (i)),
1911 Faref (thisseq, make_number (i))))
1912 i++;
1913 if (i >= lim)
1914 /* `prefix' is a prefix of `thisseq' => there's a cycle. */
1915 return;
1916 }
1917 /* This occurrence of `cmd' in `maps' does not correspond to a cycle,
1918 but maybe `cmd' occurs again further down in `maps', so keep
1919 looking. */
1920 maps = XCDR (Fmemq (tem, maps));
1921 }
1922
1923 /* If the last key in thisseq is meta-prefix-char,
1924 turn it into a meta-ized keystroke. We know
1925 that the event we're about to append is an
1926 ascii keystroke since we're processing a
1927 keymap table. */
1928 if (is_metized)
1929 {
1930 int meta_bit = meta_modifier;
1931 Lisp_Object last = make_number (XINT (Flength (thisseq)) - 1);
1932 tem = Fcopy_sequence (thisseq);
1933
1934 Faset (tem, last, make_number (XINT (key) | meta_bit));
1935
1936 /* This new sequence is the same length as
1937 thisseq, so stick it in the list right
1938 after this one. */
1939 XSETCDR (tail,
1940 Fcons (Fcons (tem, cmd), XCDR (tail)));
1941 }
1942 else
1943 {
1944 tem = append_key (thisseq, key);
1945 nconc2 (tail, Fcons (Fcons (tem, cmd), Qnil));
1946 }
1947 }
1948
1949 /* This function cannot GC. */
1950
1951 DEFUN ("accessible-keymaps", Faccessible_keymaps, Saccessible_keymaps,
1952 1, 2, 0,
1953 doc: /* Find all keymaps accessible via prefix characters from KEYMAP.
1954 Returns a list of elements of the form (KEYS . MAP), where the sequence
1955 KEYS starting from KEYMAP gets you to MAP. These elements are ordered
1956 so that the KEYS increase in length. The first element is ([] . KEYMAP).
1957 An optional argument PREFIX, if non-nil, should be a key sequence;
1958 then the value includes only maps for prefixes that start with PREFIX. */)
1959 (Lisp_Object keymap, Lisp_Object prefix)
1960 {
1961 Lisp_Object maps, tail;
1962 EMACS_INT prefixlen = XFASTINT (Flength (prefix));
1963
1964 /* no need for gcpro because we don't autoload any keymaps. */
1965
1966 if (!NILP (prefix))
1967 {
1968 /* If a prefix was specified, start with the keymap (if any) for
1969 that prefix, so we don't waste time considering other prefixes. */
1970 Lisp_Object tem;
1971 tem = Flookup_key (keymap, prefix, Qt);
1972 /* Flookup_key may give us nil, or a number,
1973 if the prefix is not defined in this particular map.
1974 It might even give us a list that isn't a keymap. */
1975 tem = get_keymap (tem, 0, 0);
1976 /* If the keymap is autoloaded `tem' is not a cons-cell, but we still
1977 want to return it. */
1978 if (!NILP (tem))
1979 {
1980 /* Convert PREFIX to a vector now, so that later on
1981 we don't have to deal with the possibility of a string. */
1982 if (STRINGP (prefix))
1983 {
1984 int i, i_byte, c;
1985 Lisp_Object copy;
1986
1987 copy = Fmake_vector (make_number (SCHARS (prefix)), Qnil);
1988 for (i = 0, i_byte = 0; i < SCHARS (prefix);)
1989 {
1990 int i_before = i;
1991
1992 FETCH_STRING_CHAR_ADVANCE (c, prefix, i, i_byte);
1993 if (SINGLE_BYTE_CHAR_P (c) && (c & 0200))
1994 c ^= 0200 | meta_modifier;
1995 ASET (copy, i_before, make_number (c));
1996 }
1997 prefix = copy;
1998 }
1999 maps = Fcons (Fcons (prefix, tem), Qnil);
2000 }
2001 else
2002 return Qnil;
2003 }
2004 else
2005 maps = Fcons (Fcons (zero_vector, get_keymap (keymap, 1, 0)), Qnil);
2006
2007 /* For each map in the list maps,
2008 look at any other maps it points to,
2009 and stick them at the end if they are not already in the list.
2010
2011 This is a breadth-first traversal, where tail is the queue of
2012 nodes, and maps accumulates a list of all nodes visited. */
2013
2014 for (tail = maps; CONSP (tail); tail = XCDR (tail))
2015 {
2016 struct accessible_keymaps_data data;
2017 register Lisp_Object thismap = Fcdr (XCAR (tail));
2018 Lisp_Object last;
2019
2020 data.thisseq = Fcar (XCAR (tail));
2021 data.maps = maps;
2022 data.tail = tail;
2023 last = make_number (XINT (Flength (data.thisseq)) - 1);
2024 /* Does the current sequence end in the meta-prefix-char? */
2025 data.is_metized = (XINT (last) >= 0
2026 /* Don't metize the last char of PREFIX. */
2027 && XINT (last) >= prefixlen
2028 && EQ (Faref (data.thisseq, last), meta_prefix_char));
2029
2030 /* Since we can't run lisp code, we can't scan autoloaded maps. */
2031 if (CONSP (thismap))
2032 map_keymap (thismap, accessible_keymaps_1, Qnil, &data, 0);
2033 }
2034 return maps;
2035 }
2036 static Lisp_Object Qsingle_key_description, Qkey_description;
2037
2038 /* This function cannot GC. */
2039
2040 DEFUN ("key-description", Fkey_description, Skey_description, 1, 2, 0,
2041 doc: /* Return a pretty description of key-sequence KEYS.
2042 Optional arg PREFIX is the sequence of keys leading up to KEYS.
2043 For example, [?\C-x ?l] is converted into the string \"C-x l\".
2044
2045 For an approximate inverse of this, see `kbd'. */)
2046 (Lisp_Object keys, Lisp_Object prefix)
2047 {
2048 ptrdiff_t len = 0;
2049 EMACS_INT i;
2050 ptrdiff_t i_byte;
2051 Lisp_Object *args;
2052 EMACS_INT size = XINT (Flength (keys));
2053 Lisp_Object list;
2054 Lisp_Object sep = build_string (" ");
2055 Lisp_Object key;
2056 Lisp_Object result;
2057 bool add_meta = 0;
2058 USE_SAFE_ALLOCA;
2059
2060 if (!NILP (prefix))
2061 size += XINT (Flength (prefix));
2062
2063 /* This has one extra element at the end that we don't pass to Fconcat. */
2064 if (min (PTRDIFF_MAX, SIZE_MAX) / word_size / 4 < size)
2065 memory_full (SIZE_MAX);
2066 SAFE_ALLOCA_LISP (args, size * 4);
2067
2068 /* In effect, this computes
2069 (mapconcat 'single-key-description keys " ")
2070 but we shouldn't use mapconcat because it can do GC. */
2071
2072 next_list:
2073 if (!NILP (prefix))
2074 list = prefix, prefix = Qnil;
2075 else if (!NILP (keys))
2076 list = keys, keys = Qnil;
2077 else
2078 {
2079 if (add_meta)
2080 {
2081 args[len] = Fsingle_key_description (meta_prefix_char, Qnil);
2082 result = Fconcat (len + 1, args);
2083 }
2084 else if (len == 0)
2085 result = empty_unibyte_string;
2086 else
2087 result = Fconcat (len - 1, args);
2088 SAFE_FREE ();
2089 return result;
2090 }
2091
2092 if (STRINGP (list))
2093 size = SCHARS (list);
2094 else if (VECTORP (list))
2095 size = ASIZE (list);
2096 else if (CONSP (list))
2097 size = XINT (Flength (list));
2098 else
2099 wrong_type_argument (Qarrayp, list);
2100
2101 i = i_byte = 0;
2102
2103 while (i < size)
2104 {
2105 if (STRINGP (list))
2106 {
2107 int c;
2108 FETCH_STRING_CHAR_ADVANCE (c, list, i, i_byte);
2109 if (SINGLE_BYTE_CHAR_P (c) && (c & 0200))
2110 c ^= 0200 | meta_modifier;
2111 XSETFASTINT (key, c);
2112 }
2113 else if (VECTORP (list))
2114 {
2115 key = AREF (list, i); i++;
2116 }
2117 else
2118 {
2119 key = XCAR (list);
2120 list = XCDR (list);
2121 i++;
2122 }
2123
2124 if (add_meta)
2125 {
2126 if (!INTEGERP (key)
2127 || EQ (key, meta_prefix_char)
2128 || (XINT (key) & meta_modifier))
2129 {
2130 args[len++] = Fsingle_key_description (meta_prefix_char, Qnil);
2131 args[len++] = sep;
2132 if (EQ (key, meta_prefix_char))
2133 continue;
2134 }
2135 else
2136 XSETINT (key, XINT (key) | meta_modifier);
2137 add_meta = 0;
2138 }
2139 else if (EQ (key, meta_prefix_char))
2140 {
2141 add_meta = 1;
2142 continue;
2143 }
2144 args[len++] = Fsingle_key_description (key, Qnil);
2145 args[len++] = sep;
2146 }
2147 goto next_list;
2148 }
2149
2150
2151 char *
2152 push_key_description (EMACS_INT ch, char *p)
2153 {
2154 int c, c2;
2155 bool tab_as_ci;
2156
2157 /* Clear all the meaningless bits above the meta bit. */
2158 c = ch & (meta_modifier | ~ - meta_modifier);
2159 c2 = c & ~(alt_modifier | ctrl_modifier | hyper_modifier
2160 | meta_modifier | shift_modifier | super_modifier);
2161
2162 if (! CHARACTERP (make_number (c2)))
2163 {
2164 /* KEY_DESCRIPTION_SIZE is large enough for this. */
2165 p += sprintf (p, "[%d]", c);
2166 return p;
2167 }
2168
2169 tab_as_ci = (c2 == '\t' && (c & meta_modifier));
2170
2171 if (c & alt_modifier)
2172 {
2173 *p++ = 'A';
2174 *p++ = '-';
2175 c -= alt_modifier;
2176 }
2177 if ((c & ctrl_modifier) != 0
2178 || (c2 < ' ' && c2 != 27 && c2 != '\t' && c2 != Ctl ('M'))
2179 || tab_as_ci)
2180 {
2181 *p++ = 'C';
2182 *p++ = '-';
2183 c &= ~ctrl_modifier;
2184 }
2185 if (c & hyper_modifier)
2186 {
2187 *p++ = 'H';
2188 *p++ = '-';
2189 c -= hyper_modifier;
2190 }
2191 if (c & meta_modifier)
2192 {
2193 *p++ = 'M';
2194 *p++ = '-';
2195 c -= meta_modifier;
2196 }
2197 if (c & shift_modifier)
2198 {
2199 *p++ = 'S';
2200 *p++ = '-';
2201 c -= shift_modifier;
2202 }
2203 if (c & super_modifier)
2204 {
2205 *p++ = 's';
2206 *p++ = '-';
2207 c -= super_modifier;
2208 }
2209 if (c < 040)
2210 {
2211 if (c == 033)
2212 {
2213 *p++ = 'E';
2214 *p++ = 'S';
2215 *p++ = 'C';
2216 }
2217 else if (tab_as_ci)
2218 {
2219 *p++ = 'i';
2220 }
2221 else if (c == '\t')
2222 {
2223 *p++ = 'T';
2224 *p++ = 'A';
2225 *p++ = 'B';
2226 }
2227 else if (c == Ctl ('M'))
2228 {
2229 *p++ = 'R';
2230 *p++ = 'E';
2231 *p++ = 'T';
2232 }
2233 else
2234 {
2235 /* `C-' already added above. */
2236 if (c > 0 && c <= Ctl ('Z'))
2237 *p++ = c + 0140;
2238 else
2239 *p++ = c + 0100;
2240 }
2241 }
2242 else if (c == 0177)
2243 {
2244 *p++ = 'D';
2245 *p++ = 'E';
2246 *p++ = 'L';
2247 }
2248 else if (c == ' ')
2249 {
2250 *p++ = 'S';
2251 *p++ = 'P';
2252 *p++ = 'C';
2253 }
2254 else if (c < 128)
2255 *p++ = c;
2256 else
2257 {
2258 /* Now we are sure that C is a valid character code. */
2259 p += CHAR_STRING (c, (unsigned char *) p);
2260 }
2261
2262 return p;
2263 }
2264
2265 /* This function cannot GC. */
2266
2267 DEFUN ("single-key-description", Fsingle_key_description,
2268 Ssingle_key_description, 1, 2, 0,
2269 doc: /* Return a pretty description of command character KEY.
2270 Control characters turn into C-whatever, etc.
2271 Optional argument NO-ANGLES non-nil means don't put angle brackets
2272 around function keys and event symbols. */)
2273 (Lisp_Object key, Lisp_Object no_angles)
2274 {
2275 if (CONSP (key) && lucid_event_type_list_p (key))
2276 key = Fevent_convert_list (key);
2277
2278 if (CONSP (key) && INTEGERP (XCAR (key)) && INTEGERP (XCDR (key)))
2279 /* An interval from a map-char-table. */
2280 return concat3 (Fsingle_key_description (XCAR (key), no_angles),
2281 build_string (".."),
2282 Fsingle_key_description (XCDR (key), no_angles));
2283
2284 key = EVENT_HEAD (key);
2285
2286 if (INTEGERP (key)) /* Normal character. */
2287 {
2288 char tem[KEY_DESCRIPTION_SIZE];
2289 char *p = push_key_description (XINT (key), tem);
2290 *p = 0;
2291 return make_specified_string (tem, -1, p - tem, 1);
2292 }
2293 else if (SYMBOLP (key)) /* Function key or event-symbol. */
2294 {
2295 if (NILP (no_angles))
2296 {
2297 Lisp_Object result;
2298 USE_SAFE_ALLOCA;
2299 char *buffer = SAFE_ALLOCA (sizeof "<>"
2300 + SBYTES (SYMBOL_NAME (key)));
2301 esprintf (buffer, "<%s>", SDATA (SYMBOL_NAME (key)));
2302 result = build_string (buffer);
2303 SAFE_FREE ();
2304 return result;
2305 }
2306 else
2307 return Fsymbol_name (key);
2308 }
2309 else if (STRINGP (key)) /* Buffer names in the menubar. */
2310 return Fcopy_sequence (key);
2311 else
2312 error ("KEY must be an integer, cons, symbol, or string");
2313 return Qnil;
2314 }
2315
2316 static char *
2317 push_text_char_description (register unsigned int c, register char *p)
2318 {
2319 if (c >= 0200)
2320 {
2321 *p++ = 'M';
2322 *p++ = '-';
2323 c -= 0200;
2324 }
2325 if (c < 040)
2326 {
2327 *p++ = '^';
2328 *p++ = c + 64; /* 'A' - 1 */
2329 }
2330 else if (c == 0177)
2331 {
2332 *p++ = '^';
2333 *p++ = '?';
2334 }
2335 else
2336 *p++ = c;
2337 return p;
2338 }
2339
2340 /* This function cannot GC. */
2341
2342 DEFUN ("text-char-description", Ftext_char_description, Stext_char_description, 1, 1, 0,
2343 doc: /* Return a pretty description of file-character CHARACTER.
2344 Control characters turn into "^char", etc. This differs from
2345 `single-key-description' which turns them into "C-char".
2346 Also, this function recognizes the 2**7 bit as the Meta character,
2347 whereas `single-key-description' uses the 2**27 bit for Meta.
2348 See Info node `(elisp)Describing Characters' for examples. */)
2349 (Lisp_Object character)
2350 {
2351 /* Currently MAX_MULTIBYTE_LENGTH is 4 (< 6). */
2352 char str[6];
2353 int c;
2354
2355 CHECK_CHARACTER (character);
2356
2357 c = XINT (character);
2358 if (!ASCII_CHAR_P (c))
2359 {
2360 int len = CHAR_STRING (c, (unsigned char *) str);
2361
2362 return make_multibyte_string (str, 1, len);
2363 }
2364
2365 *push_text_char_description (c & 0377, str) = 0;
2366
2367 return build_string (str);
2368 }
2369
2370 static int where_is_preferred_modifier;
2371
2372 /* Return 0 if SEQ uses non-preferred modifiers or non-char events.
2373 Else, return 2 if SEQ uses the where_is_preferred_modifier,
2374 and 1 otherwise. */
2375 static int
2376 preferred_sequence_p (Lisp_Object seq)
2377 {
2378 EMACS_INT i;
2379 EMACS_INT len = XFASTINT (Flength (seq));
2380 int result = 1;
2381
2382 for (i = 0; i < len; i++)
2383 {
2384 Lisp_Object ii, elt;
2385
2386 XSETFASTINT (ii, i);
2387 elt = Faref (seq, ii);
2388
2389 if (!INTEGERP (elt))
2390 return 0;
2391 else
2392 {
2393 int modifiers = XINT (elt) & (CHAR_MODIFIER_MASK & ~CHAR_META);
2394 if (modifiers == where_is_preferred_modifier)
2395 result = 2;
2396 else if (modifiers)
2397 return 0;
2398 }
2399 }
2400
2401 return result;
2402 }
2403
2404 \f
2405 /* where-is - finding a command in a set of keymaps. */
2406
2407 static void where_is_internal_1 (Lisp_Object key, Lisp_Object binding,
2408 Lisp_Object args, void *data);
2409
2410 /* Like Flookup_key, but uses a list of keymaps SHADOW instead of a single map.
2411 Returns the first non-nil binding found in any of those maps.
2412 If REMAP is true, pass the result of the lookup through command
2413 remapping before returning it. */
2414
2415 static Lisp_Object
2416 shadow_lookup (Lisp_Object shadow, Lisp_Object key, Lisp_Object flag,
2417 bool remap)
2418 {
2419 Lisp_Object tail, value;
2420
2421 for (tail = shadow; CONSP (tail); tail = XCDR (tail))
2422 {
2423 value = Flookup_key (XCAR (tail), key, flag);
2424 if (NATNUMP (value))
2425 {
2426 value = Flookup_key (XCAR (tail),
2427 Fsubstring (key, make_number (0), value), flag);
2428 if (!NILP (value))
2429 return Qnil;
2430 }
2431 else if (!NILP (value))
2432 {
2433 Lisp_Object remapping;
2434 if (remap && SYMBOLP (value)
2435 && (remapping = Fcommand_remapping (value, Qnil, shadow),
2436 !NILP (remapping)))
2437 return remapping;
2438 else
2439 return value;
2440 }
2441 }
2442 return Qnil;
2443 }
2444
2445 static Lisp_Object Vmouse_events;
2446
2447 struct where_is_internal_data {
2448 Lisp_Object definition, this, last;
2449 bool last_is_meta, noindirect;
2450 Lisp_Object sequences;
2451 };
2452
2453 /* This function can't GC, AFAIK. */
2454 /* Return the list of bindings found. This list is ordered "longest
2455 to shortest". It may include bindings that are actually shadowed
2456 by others, as well as duplicate bindings and remapping bindings.
2457 The list returned is potentially shared with where_is_cache, so
2458 be careful not to modify it via side-effects. */
2459
2460 static Lisp_Object
2461 where_is_internal (Lisp_Object definition, Lisp_Object keymaps,
2462 bool noindirect, bool nomenus)
2463 {
2464 Lisp_Object maps = Qnil;
2465 Lisp_Object found;
2466 struct where_is_internal_data data;
2467
2468 /* Only important use of caching is for the menubar
2469 (i.e. where-is-internal called with (def nil t nil nil)). */
2470 if (nomenus && !noindirect)
2471 {
2472 /* Check heuristic-consistency of the cache. */
2473 if (NILP (Fequal (keymaps, where_is_cache_keymaps)))
2474 where_is_cache = Qnil;
2475
2476 if (NILP (where_is_cache))
2477 {
2478 /* We need to create the cache. */
2479 Lisp_Object args[2];
2480 where_is_cache = Fmake_hash_table (0, args);
2481 where_is_cache_keymaps = Qt;
2482 }
2483 else
2484 /* We can reuse the cache. */
2485 return Fgethash (definition, where_is_cache, Qnil);
2486 }
2487 else
2488 /* Kill the cache so that where_is_internal_1 doesn't think
2489 we're filling it up. */
2490 where_is_cache = Qnil;
2491
2492 found = keymaps;
2493 while (CONSP (found))
2494 {
2495 maps =
2496 nconc2 (maps,
2497 Faccessible_keymaps (get_keymap (XCAR (found), 1, 0), Qnil));
2498 found = XCDR (found);
2499 }
2500
2501 data.sequences = Qnil;
2502 for (; CONSP (maps); maps = XCDR (maps))
2503 {
2504 /* Key sequence to reach map, and the map that it reaches */
2505 register Lisp_Object this, map, tem;
2506
2507 /* In order to fold [META-PREFIX-CHAR CHAR] sequences into
2508 [M-CHAR] sequences, check if last character of the sequence
2509 is the meta-prefix char. */
2510 Lisp_Object last;
2511 bool last_is_meta;
2512
2513 this = Fcar (XCAR (maps));
2514 map = Fcdr (XCAR (maps));
2515 last = make_number (XINT (Flength (this)) - 1);
2516 last_is_meta = (XINT (last) >= 0
2517 && EQ (Faref (this, last), meta_prefix_char));
2518
2519 /* if (nomenus && !preferred_sequence_p (this)) */
2520 if (nomenus && XINT (last) >= 0
2521 && SYMBOLP (tem = Faref (this, make_number (0)))
2522 && !NILP (Fmemq (XCAR (parse_modifiers (tem)), Vmouse_events)))
2523 /* If no menu entries should be returned, skip over the
2524 keymaps bound to `menu-bar' and `tool-bar' and other
2525 non-ascii prefixes like `C-down-mouse-2'. */
2526 continue;
2527
2528 QUIT;
2529
2530 data.definition = definition;
2531 data.noindirect = noindirect;
2532 data.this = this;
2533 data.last = last;
2534 data.last_is_meta = last_is_meta;
2535
2536 if (CONSP (map))
2537 map_keymap (map, where_is_internal_1, Qnil, &data, 0);
2538 }
2539
2540 if (nomenus && !noindirect)
2541 { /* Remember for which keymaps this cache was built.
2542 We do it here (late) because we want to keep where_is_cache_keymaps
2543 set to t while the cache isn't fully filled. */
2544 where_is_cache_keymaps = keymaps;
2545 /* During cache-filling, data.sequences is not filled by
2546 where_is_internal_1. */
2547 return Fgethash (definition, where_is_cache, Qnil);
2548 }
2549 else
2550 return data.sequences;
2551 }
2552
2553 /* This function can GC if Flookup_key autoloads any keymaps. */
2554
2555 DEFUN ("where-is-internal", Fwhere_is_internal, Swhere_is_internal, 1, 5, 0,
2556 doc: /* Return list of keys that invoke DEFINITION.
2557 If KEYMAP is a keymap, search only KEYMAP and the global keymap.
2558 If KEYMAP is nil, search all the currently active keymaps, except
2559 for `overriding-local-map' (which is ignored).
2560 If KEYMAP is a list of keymaps, search only those keymaps.
2561
2562 If optional 3rd arg FIRSTONLY is non-nil, return the first key sequence found,
2563 rather than a list of all possible key sequences.
2564 If FIRSTONLY is the symbol `non-ascii', return the first binding found,
2565 no matter what it is.
2566 If FIRSTONLY has another non-nil value, prefer bindings
2567 that use the modifier key specified in `where-is-preferred-modifier'
2568 \(or their meta variants) and entirely reject menu bindings.
2569
2570 If optional 4th arg NOINDIRECT is non-nil, don't follow indirections
2571 to other keymaps or slots. This makes it possible to search for an
2572 indirect definition itself.
2573
2574 The optional 5th arg NO-REMAP alters how command remapping is handled:
2575
2576 - If another command OTHER-COMMAND is remapped to DEFINITION, normally
2577 search for the bindings of OTHER-COMMAND and include them in the
2578 returned list. But if NO-REMAP is non-nil, include the vector
2579 [remap OTHER-COMMAND] in the returned list instead, without
2580 searching for those other bindings.
2581
2582 - If DEFINITION is remapped to OTHER-COMMAND, normally return the
2583 bindings for OTHER-COMMAND. But if NO-REMAP is non-nil, return the
2584 bindings for DEFINITION instead, ignoring its remapping. */)
2585 (Lisp_Object definition, Lisp_Object keymap, Lisp_Object firstonly, Lisp_Object noindirect, Lisp_Object no_remap)
2586 {
2587 /* The keymaps in which to search. */
2588 Lisp_Object keymaps;
2589 /* Potentially relevant bindings in "shortest to longest" order. */
2590 Lisp_Object sequences = Qnil;
2591 /* Actually relevant bindings. */
2592 Lisp_Object found = Qnil;
2593 /* 1 means ignore all menu bindings entirely. */
2594 bool nomenus = !NILP (firstonly) && !EQ (firstonly, Qnon_ascii);
2595 struct gcpro gcpro1, gcpro2, gcpro3, gcpro4, gcpro5, gcpro6;
2596 /* List of sequences found via remapping. Keep them in a separate
2597 variable, so as to push them later, since we prefer
2598 non-remapped binding. */
2599 Lisp_Object remapped_sequences = Qnil;
2600 /* Whether or not we're handling remapped sequences. This is needed
2601 because remapping is not done recursively by Fcommand_remapping: you
2602 can't remap a remapped command. */
2603 bool remapped = 0;
2604 Lisp_Object tem = Qnil;
2605
2606 /* Refresh the C version of the modifier preference. */
2607 where_is_preferred_modifier
2608 = parse_solitary_modifier (Vwhere_is_preferred_modifier);
2609
2610 /* Find the relevant keymaps. */
2611 if (CONSP (keymap) && KEYMAPP (XCAR (keymap)))
2612 keymaps = keymap;
2613 else if (!NILP (keymap))
2614 keymaps = Fcons (keymap, Fcons (current_global_map, Qnil));
2615 else
2616 keymaps = Fcurrent_active_maps (Qnil, Qnil);
2617
2618 GCPRO6 (definition, keymaps, found, sequences, remapped_sequences, tem);
2619
2620 tem = Fcommand_remapping (definition, Qnil, keymaps);
2621 /* If `definition' is remapped to tem', then OT1H no key will run
2622 that command (since they will run `tem' instead), so we should
2623 return nil; but OTOH all keys bound to `definition' (or to `tem')
2624 will run the same command.
2625 So for menu-shortcut purposes, we want to find all the keys bound (maybe
2626 via remapping) to `tem'. But for the purpose of finding the keys that
2627 run `definition', then we'd want to just return nil.
2628 We choose to make it work right for menu-shortcuts, since it's the most
2629 common use.
2630 Known bugs: if you remap switch-to-buffer to toto, C-h f switch-to-buffer
2631 will tell you that switch-to-buffer is bound to C-x b even though C-x b
2632 will run toto instead. And if `toto' is itself remapped to forward-char,
2633 then C-h f toto will tell you that it's bound to C-f even though C-f does
2634 not run toto and it won't tell you that C-x b does run toto. */
2635 if (NILP (no_remap) && !NILP (tem))
2636 definition = tem;
2637
2638 if (SYMBOLP (definition)
2639 && !NILP (firstonly)
2640 && !NILP (tem = Fget (definition, QCadvertised_binding)))
2641 {
2642 /* We have a list of advertised bindings. */
2643 while (CONSP (tem))
2644 if (EQ (shadow_lookup (keymaps, XCAR (tem), Qnil, 0), definition))
2645 RETURN_UNGCPRO (XCAR (tem));
2646 else
2647 tem = XCDR (tem);
2648 if (EQ (shadow_lookup (keymaps, tem, Qnil, 0), definition))
2649 RETURN_UNGCPRO (tem);
2650 }
2651
2652 sequences = Freverse (where_is_internal (definition, keymaps,
2653 !NILP (noindirect), nomenus));
2654
2655 while (CONSP (sequences)
2656 /* If we're at the end of the `sequences' list and we haven't
2657 considered remapped sequences yet, copy them over and
2658 process them. */
2659 || (!remapped && (sequences = remapped_sequences,
2660 remapped = 1,
2661 CONSP (sequences))))
2662 {
2663 Lisp_Object sequence, function;
2664
2665 sequence = XCAR (sequences);
2666 sequences = XCDR (sequences);
2667
2668 /* Verify that this key binding is not shadowed by another
2669 binding for the same key, before we say it exists.
2670
2671 Mechanism: look for local definition of this key and if
2672 it is defined and does not match what we found then
2673 ignore this key.
2674
2675 Either nil or number as value from Flookup_key
2676 means undefined. */
2677 if (NILP (Fequal (shadow_lookup (keymaps, sequence, Qnil, remapped),
2678 definition)))
2679 continue;
2680
2681 /* If the current sequence is a command remapping with
2682 format [remap COMMAND], find the key sequences
2683 which run COMMAND, and use those sequences instead. */
2684 if (NILP (no_remap) && !remapped
2685 && VECTORP (sequence) && ASIZE (sequence) == 2
2686 && EQ (AREF (sequence, 0), Qremap)
2687 && (function = AREF (sequence, 1), SYMBOLP (function)))
2688 {
2689 Lisp_Object seqs = where_is_internal (function, keymaps,
2690 !NILP (noindirect), nomenus);
2691 remapped_sequences = nconc2 (Freverse (seqs), remapped_sequences);
2692 continue;
2693 }
2694
2695 /* Don't annoy user with strings from a menu such as the
2696 entries from the "Edit => Paste from Kill Menu".
2697 Change them all to "(any string)", so that there
2698 seems to be only one menu item to report. */
2699 if (! NILP (sequence))
2700 {
2701 Lisp_Object tem1;
2702 tem1 = Faref (sequence, make_number (ASIZE (sequence) - 1));
2703 if (STRINGP (tem1))
2704 Faset (sequence, make_number (ASIZE (sequence) - 1),
2705 build_string ("(any string)"));
2706 }
2707
2708 /* It is a true unshadowed match. Record it, unless it's already
2709 been seen (as could happen when inheriting keymaps). */
2710 if (NILP (Fmember (sequence, found)))
2711 found = Fcons (sequence, found);
2712
2713 /* If firstonly is Qnon_ascii, then we can return the first
2714 binding we find. If firstonly is not Qnon_ascii but not
2715 nil, then we should return the first ascii-only binding
2716 we find. */
2717 if (EQ (firstonly, Qnon_ascii))
2718 RETURN_UNGCPRO (sequence);
2719 else if (!NILP (firstonly)
2720 && 2 == preferred_sequence_p (sequence))
2721 RETURN_UNGCPRO (sequence);
2722 }
2723
2724 UNGCPRO;
2725
2726 found = Fnreverse (found);
2727
2728 /* firstonly may have been t, but we may have gone all the way through
2729 the keymaps without finding an all-ASCII key sequence. So just
2730 return the best we could find. */
2731 if (NILP (firstonly))
2732 return found;
2733 else if (where_is_preferred_modifier == 0)
2734 return Fcar (found);
2735 else
2736 { /* Maybe we did not find a preferred_modifier binding, but we did find
2737 some ASCII binding. */
2738 Lisp_Object bindings = found;
2739 while (CONSP (bindings))
2740 if (preferred_sequence_p (XCAR (bindings)))
2741 return XCAR (bindings);
2742 else
2743 bindings = XCDR (bindings);
2744 return Fcar (found);
2745 }
2746 }
2747
2748 /* This function can GC because get_keyelt can. */
2749
2750 static void
2751 where_is_internal_1 (Lisp_Object key, Lisp_Object binding, Lisp_Object args, void *data)
2752 {
2753 struct where_is_internal_data *d = data; /* Cast! */
2754 Lisp_Object definition = d->definition;
2755 bool noindirect = d->noindirect;
2756 Lisp_Object this = d->this;
2757 Lisp_Object last = d->last;
2758 bool last_is_meta = d->last_is_meta;
2759 Lisp_Object sequence;
2760
2761 /* Search through indirections unless that's not wanted. */
2762 if (!noindirect)
2763 binding = get_keyelt (binding, 0);
2764
2765 /* End this iteration if this element does not match
2766 the target. */
2767
2768 if (!(!NILP (where_is_cache) /* everything "matches" during cache-fill. */
2769 || EQ (binding, definition)
2770 || (CONSP (definition) && !NILP (Fequal (binding, definition)))))
2771 /* Doesn't match. */
2772 return;
2773
2774 /* We have found a match. Construct the key sequence where we found it. */
2775 if (INTEGERP (key) && last_is_meta)
2776 {
2777 sequence = Fcopy_sequence (this);
2778 Faset (sequence, last, make_number (XINT (key) | meta_modifier));
2779 }
2780 else
2781 {
2782 if (CONSP (key))
2783 key = Fcons (XCAR (key), XCDR (key));
2784 sequence = append_key (this, key);
2785 }
2786
2787 if (!NILP (where_is_cache))
2788 {
2789 Lisp_Object sequences = Fgethash (binding, where_is_cache, Qnil);
2790 Fputhash (binding, Fcons (sequence, sequences), where_is_cache);
2791 }
2792 else
2793 d->sequences = Fcons (sequence, d->sequences);
2794 }
2795 \f
2796 /* describe-bindings - summarizing all the bindings in a set of keymaps. */
2797
2798 DEFUN ("describe-buffer-bindings", Fdescribe_buffer_bindings, Sdescribe_buffer_bindings, 1, 3, 0,
2799 doc: /* Insert the list of all defined keys and their definitions.
2800 The list is inserted in the current buffer, while the bindings are
2801 looked up in BUFFER.
2802 The optional argument PREFIX, if non-nil, should be a key sequence;
2803 then we display only bindings that start with that prefix.
2804 The optional argument MENUS, if non-nil, says to mention menu bindings.
2805 \(Ordinarily these are omitted from the output.) */)
2806 (Lisp_Object buffer, Lisp_Object prefix, Lisp_Object menus)
2807 {
2808 Lisp_Object outbuf, shadow;
2809 bool nomenu = NILP (menus);
2810 Lisp_Object start1;
2811 struct gcpro gcpro1;
2812
2813 const char *alternate_heading
2814 = "\
2815 Keyboard translations:\n\n\
2816 You type Translation\n\
2817 -------- -----------\n";
2818
2819 CHECK_BUFFER (buffer);
2820
2821 shadow = Qnil;
2822 GCPRO1 (shadow);
2823
2824 outbuf = Fcurrent_buffer ();
2825
2826 /* Report on alternates for keys. */
2827 if (STRINGP (KVAR (current_kboard, Vkeyboard_translate_table)) && !NILP (prefix))
2828 {
2829 int c;
2830 const unsigned char *translate = SDATA (KVAR (current_kboard, Vkeyboard_translate_table));
2831 int translate_len = SCHARS (KVAR (current_kboard, Vkeyboard_translate_table));
2832
2833 for (c = 0; c < translate_len; c++)
2834 if (translate[c] != c)
2835 {
2836 char buf[KEY_DESCRIPTION_SIZE];
2837 char *bufend;
2838
2839 if (alternate_heading)
2840 {
2841 insert_string (alternate_heading);
2842 alternate_heading = 0;
2843 }
2844
2845 bufend = push_key_description (translate[c], buf);
2846 insert (buf, bufend - buf);
2847 Findent_to (make_number (16), make_number (1));
2848 bufend = push_key_description (c, buf);
2849 insert (buf, bufend - buf);
2850
2851 insert ("\n", 1);
2852
2853 /* Insert calls signal_after_change which may GC. */
2854 translate = SDATA (KVAR (current_kboard, Vkeyboard_translate_table));
2855 }
2856
2857 insert ("\n", 1);
2858 }
2859
2860 if (!NILP (Vkey_translation_map))
2861 describe_map_tree (Vkey_translation_map, 0, Qnil, prefix,
2862 "Key translations", nomenu, 1, 0, 0);
2863
2864
2865 /* Print the (major mode) local map. */
2866 start1 = Qnil;
2867 if (!NILP (KVAR (current_kboard, Voverriding_terminal_local_map)))
2868 start1 = KVAR (current_kboard, Voverriding_terminal_local_map);
2869 else if (!NILP (Voverriding_local_map))
2870 start1 = Voverriding_local_map;
2871
2872 if (!NILP (start1))
2873 {
2874 describe_map_tree (start1, 1, shadow, prefix,
2875 "\f\nOverriding Bindings", nomenu, 0, 0, 0);
2876 shadow = Fcons (start1, shadow);
2877 }
2878 else
2879 {
2880 /* Print the minor mode and major mode keymaps. */
2881 int i, nmaps;
2882 Lisp_Object *modes, *maps;
2883
2884 /* Temporarily switch to `buffer', so that we can get that buffer's
2885 minor modes correctly. */
2886 Fset_buffer (buffer);
2887
2888 nmaps = current_minor_maps (&modes, &maps);
2889 Fset_buffer (outbuf);
2890
2891 start1 = get_local_map (BUF_PT (XBUFFER (buffer)),
2892 XBUFFER (buffer), Qkeymap);
2893 if (!NILP (start1))
2894 {
2895 describe_map_tree (start1, 1, shadow, prefix,
2896 "\f\n`keymap' Property Bindings", nomenu,
2897 0, 0, 0);
2898 shadow = Fcons (start1, shadow);
2899 }
2900
2901 /* Print the minor mode maps. */
2902 for (i = 0; i < nmaps; i++)
2903 {
2904 /* The title for a minor mode keymap
2905 is constructed at run time.
2906 We let describe_map_tree do the actual insertion
2907 because it takes care of other features when doing so. */
2908 char *title, *p;
2909
2910 if (!SYMBOLP (modes[i]))
2911 emacs_abort ();
2912
2913 p = title = alloca (42 + SCHARS (SYMBOL_NAME (modes[i])));
2914 *p++ = '\f';
2915 *p++ = '\n';
2916 *p++ = '`';
2917 memcpy (p, SDATA (SYMBOL_NAME (modes[i])),
2918 SCHARS (SYMBOL_NAME (modes[i])));
2919 p += SCHARS (SYMBOL_NAME (modes[i]));
2920 *p++ = '\'';
2921 memcpy (p, " Minor Mode Bindings", strlen (" Minor Mode Bindings"));
2922 p += strlen (" Minor Mode Bindings");
2923 *p = 0;
2924
2925 describe_map_tree (maps[i], 1, shadow, prefix,
2926 title, nomenu, 0, 0, 0);
2927 shadow = Fcons (maps[i], shadow);
2928 }
2929
2930 start1 = get_local_map (BUF_PT (XBUFFER (buffer)),
2931 XBUFFER (buffer), Qlocal_map);
2932 if (!NILP (start1))
2933 {
2934 if (EQ (start1, BVAR (XBUFFER (buffer), keymap)))
2935 describe_map_tree (start1, 1, shadow, prefix,
2936 "\f\nMajor Mode Bindings", nomenu, 0, 0, 0);
2937 else
2938 describe_map_tree (start1, 1, shadow, prefix,
2939 "\f\n`local-map' Property Bindings",
2940 nomenu, 0, 0, 0);
2941
2942 shadow = Fcons (start1, shadow);
2943 }
2944 }
2945
2946 describe_map_tree (current_global_map, 1, shadow, prefix,
2947 "\f\nGlobal Bindings", nomenu, 0, 1, 0);
2948
2949 /* Print the function-key-map translations under this prefix. */
2950 if (!NILP (KVAR (current_kboard, Vlocal_function_key_map)))
2951 describe_map_tree (KVAR (current_kboard, Vlocal_function_key_map), 0, Qnil, prefix,
2952 "\f\nFunction key map translations", nomenu, 1, 0, 0);
2953
2954 /* Print the input-decode-map translations under this prefix. */
2955 if (!NILP (KVAR (current_kboard, Vinput_decode_map)))
2956 describe_map_tree (KVAR (current_kboard, Vinput_decode_map), 0, Qnil, prefix,
2957 "\f\nInput decoding map translations", nomenu, 1, 0, 0);
2958
2959 UNGCPRO;
2960 return Qnil;
2961 }
2962
2963 /* Insert a description of the key bindings in STARTMAP,
2964 followed by those of all maps reachable through STARTMAP.
2965 If PARTIAL, omit certain "uninteresting" commands
2966 (such as `undefined').
2967 If SHADOW is non-nil, it is a list of maps;
2968 don't mention keys which would be shadowed by any of them.
2969 PREFIX, if non-nil, says mention only keys that start with PREFIX.
2970 TITLE, if not 0, is a string to insert at the beginning.
2971 TITLE should not end with a colon or a newline; we supply that.
2972 If NOMENU, then omit menu-bar commands.
2973
2974 If TRANSL, the definitions are actually key translations
2975 so print strings and vectors differently.
2976
2977 If ALWAYS_TITLE, print the title even if there are no maps
2978 to look through.
2979
2980 If MENTION_SHADOW, then when something is shadowed by SHADOW,
2981 don't omit it; instead, mention it but say it is shadowed.
2982
2983 Any inserted text ends in two newlines (used by `help-make-xrefs'). */
2984
2985 void
2986 describe_map_tree (Lisp_Object startmap, bool partial, Lisp_Object shadow,
2987 Lisp_Object prefix, const char *title, bool nomenu,
2988 bool transl, bool always_title, bool mention_shadow)
2989 {
2990 Lisp_Object maps, orig_maps, seen, sub_shadows;
2991 struct gcpro gcpro1, gcpro2, gcpro3;
2992 bool something = 0;
2993 const char *key_heading
2994 = "\
2995 key binding\n\
2996 --- -------\n";
2997
2998 orig_maps = maps = Faccessible_keymaps (startmap, prefix);
2999 seen = Qnil;
3000 sub_shadows = Qnil;
3001 GCPRO3 (maps, seen, sub_shadows);
3002
3003 if (nomenu)
3004 {
3005 Lisp_Object list;
3006
3007 /* Delete from MAPS each element that is for the menu bar. */
3008 for (list = maps; CONSP (list); list = XCDR (list))
3009 {
3010 Lisp_Object elt, elt_prefix, tem;
3011
3012 elt = XCAR (list);
3013 elt_prefix = Fcar (elt);
3014 if (ASIZE (elt_prefix) >= 1)
3015 {
3016 tem = Faref (elt_prefix, make_number (0));
3017 if (EQ (tem, Qmenu_bar))
3018 maps = Fdelq (elt, maps);
3019 }
3020 }
3021 }
3022
3023 if (!NILP (maps) || always_title)
3024 {
3025 if (title)
3026 {
3027 insert_string (title);
3028 if (!NILP (prefix))
3029 {
3030 insert_string (" Starting With ");
3031 insert1 (Fkey_description (prefix, Qnil));
3032 }
3033 insert_string (":\n");
3034 }
3035 insert_string (key_heading);
3036 something = 1;
3037 }
3038
3039 for (; CONSP (maps); maps = XCDR (maps))
3040 {
3041 register Lisp_Object elt, elt_prefix, tail;
3042
3043 elt = XCAR (maps);
3044 elt_prefix = Fcar (elt);
3045
3046 sub_shadows = Qnil;
3047
3048 for (tail = shadow; CONSP (tail); tail = XCDR (tail))
3049 {
3050 Lisp_Object shmap;
3051
3052 shmap = XCAR (tail);
3053
3054 /* If the sequence by which we reach this keymap is zero-length,
3055 then the shadow map for this keymap is just SHADOW. */
3056 if ((STRINGP (elt_prefix) && SCHARS (elt_prefix) == 0)
3057 || (VECTORP (elt_prefix) && ASIZE (elt_prefix) == 0))
3058 ;
3059 /* If the sequence by which we reach this keymap actually has
3060 some elements, then the sequence's definition in SHADOW is
3061 what we should use. */
3062 else
3063 {
3064 shmap = Flookup_key (shmap, Fcar (elt), Qt);
3065 if (INTEGERP (shmap))
3066 shmap = Qnil;
3067 }
3068
3069 /* If shmap is not nil and not a keymap,
3070 it completely shadows this map, so don't
3071 describe this map at all. */
3072 if (!NILP (shmap) && !KEYMAPP (shmap))
3073 goto skip;
3074
3075 if (!NILP (shmap))
3076 sub_shadows = Fcons (shmap, sub_shadows);
3077 }
3078
3079 /* Maps we have already listed in this loop shadow this map. */
3080 for (tail = orig_maps; !EQ (tail, maps); tail = XCDR (tail))
3081 {
3082 Lisp_Object tem;
3083 tem = Fequal (Fcar (XCAR (tail)), elt_prefix);
3084 if (!NILP (tem))
3085 sub_shadows = Fcons (XCDR (XCAR (tail)), sub_shadows);
3086 }
3087
3088 describe_map (Fcdr (elt), elt_prefix,
3089 transl ? describe_translation : describe_command,
3090 partial, sub_shadows, &seen, nomenu, mention_shadow);
3091
3092 skip: ;
3093 }
3094
3095 if (something)
3096 insert_string ("\n");
3097
3098 UNGCPRO;
3099 }
3100
3101 static int previous_description_column;
3102
3103 static void
3104 describe_command (Lisp_Object definition, Lisp_Object args)
3105 {
3106 register Lisp_Object tem1;
3107 ptrdiff_t column = current_column ();
3108 int description_column;
3109
3110 /* If column 16 is no good, go to col 32;
3111 but don't push beyond that--go to next line instead. */
3112 if (column > 30)
3113 {
3114 insert_char ('\n');
3115 description_column = 32;
3116 }
3117 else if (column > 14 || (column > 10 && previous_description_column == 32))
3118 description_column = 32;
3119 else
3120 description_column = 16;
3121
3122 Findent_to (make_number (description_column), make_number (1));
3123 previous_description_column = description_column;
3124
3125 if (SYMBOLP (definition))
3126 {
3127 tem1 = SYMBOL_NAME (definition);
3128 insert1 (tem1);
3129 insert_string ("\n");
3130 }
3131 else if (STRINGP (definition) || VECTORP (definition))
3132 insert_string ("Keyboard Macro\n");
3133 else if (KEYMAPP (definition))
3134 insert_string ("Prefix Command\n");
3135 else
3136 insert_string ("??\n");
3137 }
3138
3139 static void
3140 describe_translation (Lisp_Object definition, Lisp_Object args)
3141 {
3142 register Lisp_Object tem1;
3143
3144 Findent_to (make_number (16), make_number (1));
3145
3146 if (SYMBOLP (definition))
3147 {
3148 tem1 = SYMBOL_NAME (definition);
3149 insert1 (tem1);
3150 insert_string ("\n");
3151 }
3152 else if (STRINGP (definition) || VECTORP (definition))
3153 {
3154 insert1 (Fkey_description (definition, Qnil));
3155 insert_string ("\n");
3156 }
3157 else if (KEYMAPP (definition))
3158 insert_string ("Prefix Command\n");
3159 else
3160 insert_string ("??\n");
3161 }
3162
3163 /* describe_map puts all the usable elements of a sparse keymap
3164 into an array of `struct describe_map_elt',
3165 then sorts them by the events. */
3166
3167 struct describe_map_elt
3168 {
3169 Lisp_Object event;
3170 Lisp_Object definition;
3171 bool shadowed;
3172 };
3173
3174 /* qsort comparison function for sorting `struct describe_map_elt' by
3175 the event field. */
3176
3177 static int
3178 describe_map_compare (const void *aa, const void *bb)
3179 {
3180 const struct describe_map_elt *a = aa, *b = bb;
3181 if (INTEGERP (a->event) && INTEGERP (b->event))
3182 return ((XINT (a->event) > XINT (b->event))
3183 - (XINT (a->event) < XINT (b->event)));
3184 if (!INTEGERP (a->event) && INTEGERP (b->event))
3185 return 1;
3186 if (INTEGERP (a->event) && !INTEGERP (b->event))
3187 return -1;
3188 if (SYMBOLP (a->event) && SYMBOLP (b->event))
3189 return (!NILP (Fstring_lessp (a->event, b->event)) ? -1
3190 : !NILP (Fstring_lessp (b->event, a->event)) ? 1
3191 : 0);
3192 return 0;
3193 }
3194
3195 /* Describe the contents of map MAP, assuming that this map itself is
3196 reached by the sequence of prefix keys PREFIX (a string or vector).
3197 PARTIAL, SHADOW, NOMENU are as in `describe_map_tree' above. */
3198
3199 static void
3200 describe_map (Lisp_Object map, Lisp_Object prefix,
3201 void (*elt_describer) (Lisp_Object, Lisp_Object),
3202 bool partial, Lisp_Object shadow,
3203 Lisp_Object *seen, bool nomenu, bool mention_shadow)
3204 {
3205 Lisp_Object tail, definition, event;
3206 Lisp_Object tem;
3207 Lisp_Object suppress;
3208 Lisp_Object kludge;
3209 bool first = 1;
3210 struct gcpro gcpro1, gcpro2, gcpro3;
3211
3212 /* These accumulate the values from sparse keymap bindings,
3213 so we can sort them and handle them in order. */
3214 int length_needed = 0;
3215 struct describe_map_elt *vect;
3216 int slots_used = 0;
3217 int i;
3218
3219 suppress = Qnil;
3220
3221 if (partial)
3222 suppress = intern ("suppress-keymap");
3223
3224 /* This vector gets used to present single keys to Flookup_key. Since
3225 that is done once per keymap element, we don't want to cons up a
3226 fresh vector every time. */
3227 kludge = Fmake_vector (make_number (1), Qnil);
3228 definition = Qnil;
3229
3230 GCPRO3 (prefix, definition, kludge);
3231
3232 map = call1 (Qkeymap_canonicalize, map);
3233
3234 for (tail = map; CONSP (tail); tail = XCDR (tail))
3235 length_needed++;
3236
3237 vect = ((struct describe_map_elt *)
3238 alloca (sizeof (struct describe_map_elt) * length_needed));
3239
3240 for (tail = map; CONSP (tail); tail = XCDR (tail))
3241 {
3242 QUIT;
3243
3244 if (VECTORP (XCAR (tail))
3245 || CHAR_TABLE_P (XCAR (tail)))
3246 describe_vector (XCAR (tail),
3247 prefix, Qnil, elt_describer, partial, shadow, map,
3248 1, mention_shadow);
3249 else if (CONSP (XCAR (tail)))
3250 {
3251 bool this_shadowed = 0;
3252
3253 event = XCAR (XCAR (tail));
3254
3255 /* Ignore bindings whose "prefix" are not really valid events.
3256 (We get these in the frames and buffers menu.) */
3257 if (!(SYMBOLP (event) || INTEGERP (event)))
3258 continue;
3259
3260 if (nomenu && EQ (event, Qmenu_bar))
3261 continue;
3262
3263 definition = get_keyelt (XCDR (XCAR (tail)), 0);
3264
3265 /* Don't show undefined commands or suppressed commands. */
3266 if (NILP (definition)) continue;
3267 if (SYMBOLP (definition) && partial)
3268 {
3269 tem = Fget (definition, suppress);
3270 if (!NILP (tem))
3271 continue;
3272 }
3273
3274 /* Don't show a command that isn't really visible
3275 because a local definition of the same key shadows it. */
3276
3277 ASET (kludge, 0, event);
3278 if (!NILP (shadow))
3279 {
3280 tem = shadow_lookup (shadow, kludge, Qt, 0);
3281 if (!NILP (tem))
3282 {
3283 /* If both bindings are keymaps, this key is a prefix key,
3284 so don't say it is shadowed. */
3285 if (KEYMAPP (definition) && KEYMAPP (tem))
3286 ;
3287 /* Avoid generating duplicate entries if the
3288 shadowed binding has the same definition. */
3289 else if (mention_shadow && !EQ (tem, definition))
3290 this_shadowed = 1;
3291 else
3292 continue;
3293 }
3294 }
3295
3296 tem = Flookup_key (map, kludge, Qt);
3297 if (!EQ (tem, definition)) continue;
3298
3299 vect[slots_used].event = event;
3300 vect[slots_used].definition = definition;
3301 vect[slots_used].shadowed = this_shadowed;
3302 slots_used++;
3303 }
3304 else if (EQ (XCAR (tail), Qkeymap))
3305 {
3306 /* The same keymap might be in the structure twice, if we're
3307 using an inherited keymap. So skip anything we've already
3308 encountered. */
3309 tem = Fassq (tail, *seen);
3310 if (CONSP (tem) && !NILP (Fequal (XCAR (tem), prefix)))
3311 break;
3312 *seen = Fcons (Fcons (tail, prefix), *seen);
3313 }
3314 }
3315
3316 /* If we found some sparse map events, sort them. */
3317
3318 qsort (vect, slots_used, sizeof (struct describe_map_elt),
3319 describe_map_compare);
3320
3321 /* Now output them in sorted order. */
3322
3323 for (i = 0; i < slots_used; i++)
3324 {
3325 Lisp_Object start, end;
3326
3327 if (first)
3328 {
3329 previous_description_column = 0;
3330 insert ("\n", 1);
3331 first = 0;
3332 }
3333
3334 ASET (kludge, 0, vect[i].event);
3335 start = vect[i].event;
3336 end = start;
3337
3338 definition = vect[i].definition;
3339
3340 /* Find consecutive chars that are identically defined. */
3341 if (INTEGERP (vect[i].event))
3342 {
3343 while (i + 1 < slots_used
3344 && EQ (vect[i+1].event, make_number (XINT (vect[i].event) + 1))
3345 && !NILP (Fequal (vect[i + 1].definition, definition))
3346 && vect[i].shadowed == vect[i + 1].shadowed)
3347 i++;
3348 end = vect[i].event;
3349 }
3350
3351 /* Now START .. END is the range to describe next. */
3352
3353 /* Insert the string to describe the event START. */
3354 insert1 (Fkey_description (kludge, prefix));
3355
3356 if (!EQ (start, end))
3357 {
3358 insert (" .. ", 4);
3359
3360 ASET (kludge, 0, end);
3361 /* Insert the string to describe the character END. */
3362 insert1 (Fkey_description (kludge, prefix));
3363 }
3364
3365 /* Print a description of the definition of this character.
3366 elt_describer will take care of spacing out far enough
3367 for alignment purposes. */
3368 (*elt_describer) (vect[i].definition, Qnil);
3369
3370 if (vect[i].shadowed)
3371 {
3372 SET_PT (PT - 1);
3373 insert_string ("\n (that binding is currently shadowed by another mode)");
3374 SET_PT (PT + 1);
3375 }
3376 }
3377
3378 UNGCPRO;
3379 }
3380
3381 static void
3382 describe_vector_princ (Lisp_Object elt, Lisp_Object fun)
3383 {
3384 Findent_to (make_number (16), make_number (1));
3385 call1 (fun, elt);
3386 Fterpri (Qnil);
3387 }
3388
3389 DEFUN ("describe-vector", Fdescribe_vector, Sdescribe_vector, 1, 2, 0,
3390 doc: /* Insert a description of contents of VECTOR.
3391 This is text showing the elements of vector matched against indices.
3392 DESCRIBER is the output function used; nil means use `princ'. */)
3393 (Lisp_Object vector, Lisp_Object describer)
3394 {
3395 ptrdiff_t count = SPECPDL_INDEX ();
3396 if (NILP (describer))
3397 describer = intern ("princ");
3398 specbind (Qstandard_output, Fcurrent_buffer ());
3399 CHECK_VECTOR_OR_CHAR_TABLE (vector);
3400 describe_vector (vector, Qnil, describer, describe_vector_princ, 0,
3401 Qnil, Qnil, 0, 0);
3402
3403 return unbind_to (count, Qnil);
3404 }
3405
3406 /* Insert in the current buffer a description of the contents of VECTOR.
3407 We call ELT_DESCRIBER to insert the description of one value found
3408 in VECTOR.
3409
3410 ELT_PREFIX describes what "comes before" the keys or indices defined
3411 by this vector. This is a human-readable string whose size
3412 is not necessarily related to the situation.
3413
3414 If the vector is in a keymap, ELT_PREFIX is a prefix key which
3415 leads to this keymap.
3416
3417 If the vector is a chartable, ELT_PREFIX is the vector
3418 of bytes that lead to the character set or portion of a character
3419 set described by this chartable.
3420
3421 If PARTIAL, it means do not mention suppressed commands
3422 (that assumes the vector is in a keymap).
3423
3424 SHADOW is a list of keymaps that shadow this map.
3425 If it is non-nil, then we look up the key in those maps
3426 and we don't mention it now if it is defined by any of them.
3427
3428 ENTIRE_MAP is the keymap in which this vector appears.
3429 If the definition in effect in the whole map does not match
3430 the one in this vector, we ignore this one.
3431
3432 ARGS is simply passed as the second argument to ELT_DESCRIBER.
3433
3434 KEYMAP_P is 1 if vector is known to be a keymap, so map ESC to M-.
3435
3436 ARGS is simply passed as the second argument to ELT_DESCRIBER. */
3437
3438 static void
3439 describe_vector (Lisp_Object vector, Lisp_Object prefix, Lisp_Object args,
3440 void (*elt_describer) (Lisp_Object, Lisp_Object),
3441 bool partial, Lisp_Object shadow, Lisp_Object entire_map,
3442 bool keymap_p, bool mention_shadow)
3443 {
3444 Lisp_Object definition;
3445 Lisp_Object tem2;
3446 Lisp_Object elt_prefix = Qnil;
3447 int i;
3448 Lisp_Object suppress;
3449 Lisp_Object kludge;
3450 bool first = 1;
3451 struct gcpro gcpro1, gcpro2, gcpro3, gcpro4;
3452 /* Range of elements to be handled. */
3453 int from, to, stop;
3454 Lisp_Object character;
3455 int starting_i;
3456
3457 suppress = Qnil;
3458
3459 definition = Qnil;
3460
3461 if (!keymap_p)
3462 {
3463 /* Call Fkey_description first, to avoid GC bug for the other string. */
3464 if (!NILP (prefix) && XFASTINT (Flength (prefix)) > 0)
3465 {
3466 Lisp_Object tem;
3467 tem = Fkey_description (prefix, Qnil);
3468 elt_prefix = concat2 (tem, build_string (" "));
3469 }
3470 prefix = Qnil;
3471 }
3472
3473 /* This vector gets used to present single keys to Flookup_key. Since
3474 that is done once per vector element, we don't want to cons up a
3475 fresh vector every time. */
3476 kludge = Fmake_vector (make_number (1), Qnil);
3477 GCPRO4 (elt_prefix, prefix, definition, kludge);
3478
3479 if (partial)
3480 suppress = intern ("suppress-keymap");
3481
3482 from = 0;
3483 if (CHAR_TABLE_P (vector))
3484 stop = MAX_5_BYTE_CHAR + 1, to = MAX_CHAR + 1;
3485 else
3486 stop = to = ASIZE (vector);
3487
3488 for (i = from; ; i++)
3489 {
3490 bool this_shadowed = 0;
3491 int range_beg, range_end;
3492 Lisp_Object val;
3493
3494 QUIT;
3495
3496 if (i == stop)
3497 {
3498 if (i == to)
3499 break;
3500 stop = to;
3501 }
3502
3503 starting_i = i;
3504
3505 if (CHAR_TABLE_P (vector))
3506 {
3507 range_beg = i;
3508 i = stop - 1;
3509 val = char_table_ref_and_range (vector, range_beg, &range_beg, &i);
3510 }
3511 else
3512 val = AREF (vector, i);
3513 definition = get_keyelt (val, 0);
3514
3515 if (NILP (definition)) continue;
3516
3517 /* Don't mention suppressed commands. */
3518 if (SYMBOLP (definition) && partial)
3519 {
3520 Lisp_Object tem;
3521
3522 tem = Fget (definition, suppress);
3523
3524 if (!NILP (tem)) continue;
3525 }
3526
3527 character = make_number (starting_i);
3528 ASET (kludge, 0, character);
3529
3530 /* If this binding is shadowed by some other map, ignore it. */
3531 if (!NILP (shadow))
3532 {
3533 Lisp_Object tem;
3534
3535 tem = shadow_lookup (shadow, kludge, Qt, 0);
3536
3537 if (!NILP (tem))
3538 {
3539 if (mention_shadow)
3540 this_shadowed = 1;
3541 else
3542 continue;
3543 }
3544 }
3545
3546 /* Ignore this definition if it is shadowed by an earlier
3547 one in the same keymap. */
3548 if (!NILP (entire_map))
3549 {
3550 Lisp_Object tem;
3551
3552 tem = Flookup_key (entire_map, kludge, Qt);
3553
3554 if (!EQ (tem, definition))
3555 continue;
3556 }
3557
3558 if (first)
3559 {
3560 insert ("\n", 1);
3561 first = 0;
3562 }
3563
3564 /* Output the prefix that applies to every entry in this map. */
3565 if (!NILP (elt_prefix))
3566 insert1 (elt_prefix);
3567
3568 insert1 (Fkey_description (kludge, prefix));
3569
3570 /* Find all consecutive characters or rows that have the same
3571 definition. But, VECTOR is a char-table, we had better put a
3572 boundary between normal characters (-#x3FFF7F) and 8-bit
3573 characters (#x3FFF80-). */
3574 if (CHAR_TABLE_P (vector))
3575 {
3576 while (i + 1 < stop
3577 && (range_beg = i + 1, range_end = stop - 1,
3578 val = char_table_ref_and_range (vector, range_beg,
3579 &range_beg, &range_end),
3580 tem2 = get_keyelt (val, 0),
3581 !NILP (tem2))
3582 && !NILP (Fequal (tem2, definition)))
3583 i = range_end;
3584 }
3585 else
3586 while (i + 1 < stop
3587 && (tem2 = get_keyelt (AREF (vector, i + 1), 0),
3588 !NILP (tem2))
3589 && !NILP (Fequal (tem2, definition)))
3590 i++;
3591
3592 /* If we have a range of more than one character,
3593 print where the range reaches to. */
3594
3595 if (i != starting_i)
3596 {
3597 insert (" .. ", 4);
3598
3599 ASET (kludge, 0, make_number (i));
3600
3601 if (!NILP (elt_prefix))
3602 insert1 (elt_prefix);
3603
3604 insert1 (Fkey_description (kludge, prefix));
3605 }
3606
3607 /* Print a description of the definition of this character.
3608 elt_describer will take care of spacing out far enough
3609 for alignment purposes. */
3610 (*elt_describer) (definition, args);
3611
3612 if (this_shadowed)
3613 {
3614 SET_PT (PT - 1);
3615 insert_string (" (binding currently shadowed)");
3616 SET_PT (PT + 1);
3617 }
3618 }
3619
3620 if (CHAR_TABLE_P (vector) && ! NILP (XCHAR_TABLE (vector)->defalt))
3621 {
3622 if (!NILP (elt_prefix))
3623 insert1 (elt_prefix);
3624 insert ("default", 7);
3625 (*elt_describer) (XCHAR_TABLE (vector)->defalt, args);
3626 }
3627
3628 UNGCPRO;
3629 }
3630 \f
3631 /* Apropos - finding all symbols whose names match a regexp. */
3632 static Lisp_Object apropos_predicate;
3633 static Lisp_Object apropos_accumulate;
3634
3635 static void
3636 apropos_accum (Lisp_Object symbol, Lisp_Object string)
3637 {
3638 register Lisp_Object tem;
3639
3640 tem = Fstring_match (string, Fsymbol_name (symbol), Qnil);
3641 if (!NILP (tem) && !NILP (apropos_predicate))
3642 tem = call1 (apropos_predicate, symbol);
3643 if (!NILP (tem))
3644 apropos_accumulate = Fcons (symbol, apropos_accumulate);
3645 }
3646
3647 DEFUN ("apropos-internal", Fapropos_internal, Sapropos_internal, 1, 2, 0,
3648 doc: /* Show all symbols whose names contain match for REGEXP.
3649 If optional 2nd arg PREDICATE is non-nil, (funcall PREDICATE SYMBOL) is done
3650 for each symbol and a symbol is mentioned only if that returns non-nil.
3651 Return list of symbols found. */)
3652 (Lisp_Object regexp, Lisp_Object predicate)
3653 {
3654 Lisp_Object tem;
3655 CHECK_STRING (regexp);
3656 apropos_predicate = predicate;
3657 apropos_accumulate = Qnil;
3658 map_obarray (Vobarray, apropos_accum, regexp);
3659 tem = Fsort (apropos_accumulate, Qstring_lessp);
3660 apropos_accumulate = Qnil;
3661 apropos_predicate = Qnil;
3662 return tem;
3663 }
3664 \f
3665 void
3666 syms_of_keymap (void)
3667 {
3668 DEFSYM (Qkeymap, "keymap");
3669 staticpro (&apropos_predicate);
3670 staticpro (&apropos_accumulate);
3671 apropos_predicate = Qnil;
3672 apropos_accumulate = Qnil;
3673
3674 DEFSYM (Qkeymap_canonicalize, "keymap-canonicalize");
3675
3676 /* Now we are ready to set up this property, so we can
3677 create char tables. */
3678 Fput (Qkeymap, Qchar_table_extra_slots, make_number (0));
3679
3680 /* Initialize the keymaps standardly used.
3681 Each one is the value of a Lisp variable, and is also
3682 pointed to by a C variable */
3683
3684 global_map = Fmake_keymap (Qnil);
3685 Fset (intern_c_string ("global-map"), global_map);
3686
3687 current_global_map = global_map;
3688 staticpro (&global_map);
3689 staticpro (&current_global_map);
3690
3691 meta_map = Fmake_keymap (Qnil);
3692 Fset (intern_c_string ("esc-map"), meta_map);
3693 Ffset (intern_c_string ("ESC-prefix"), meta_map);
3694
3695 control_x_map = Fmake_keymap (Qnil);
3696 Fset (intern_c_string ("ctl-x-map"), control_x_map);
3697 Ffset (intern_c_string ("Control-X-prefix"), control_x_map);
3698
3699 exclude_keys = listn (CONSTYPE_PURE, 5,
3700 pure_cons (build_pure_c_string ("DEL"), build_pure_c_string ("\\d")),
3701 pure_cons (build_pure_c_string ("TAB"), build_pure_c_string ("\\t")),
3702 pure_cons (build_pure_c_string ("RET"), build_pure_c_string ("\\r")),
3703 pure_cons (build_pure_c_string ("ESC"), build_pure_c_string ("\\e")),
3704 pure_cons (build_pure_c_string ("SPC"), build_pure_c_string (" ")));
3705 staticpro (&exclude_keys);
3706
3707 DEFVAR_LISP ("define-key-rebound-commands", Vdefine_key_rebound_commands,
3708 doc: /* List of commands given new key bindings recently.
3709 This is used for internal purposes during Emacs startup;
3710 don't alter it yourself. */);
3711 Vdefine_key_rebound_commands = Qt;
3712
3713 DEFVAR_LISP ("minibuffer-local-map", Vminibuffer_local_map,
3714 doc: /* Default keymap to use when reading from the minibuffer. */);
3715 Vminibuffer_local_map = Fmake_sparse_keymap (Qnil);
3716
3717 DEFVAR_LISP ("minibuffer-local-ns-map", Vminibuffer_local_ns_map,
3718 doc: /* Local keymap for the minibuffer when spaces are not allowed. */);
3719 Vminibuffer_local_ns_map = Fmake_sparse_keymap (Qnil);
3720 Fset_keymap_parent (Vminibuffer_local_ns_map, Vminibuffer_local_map);
3721
3722
3723 DEFVAR_LISP ("minor-mode-map-alist", Vminor_mode_map_alist,
3724 doc: /* Alist of keymaps to use for minor modes.
3725 Each element looks like (VARIABLE . KEYMAP); KEYMAP is used to read
3726 key sequences and look up bindings if VARIABLE's value is non-nil.
3727 If two active keymaps bind the same key, the keymap appearing earlier
3728 in the list takes precedence. */);
3729 Vminor_mode_map_alist = Qnil;
3730
3731 DEFVAR_LISP ("minor-mode-overriding-map-alist", Vminor_mode_overriding_map_alist,
3732 doc: /* Alist of keymaps to use for minor modes, in current major mode.
3733 This variable is an alist just like `minor-mode-map-alist', and it is
3734 used the same way (and before `minor-mode-map-alist'); however,
3735 it is provided for major modes to bind locally. */);
3736 Vminor_mode_overriding_map_alist = Qnil;
3737
3738 DEFVAR_LISP ("emulation-mode-map-alists", Vemulation_mode_map_alists,
3739 doc: /* List of keymap alists to use for emulations modes.
3740 It is intended for modes or packages using multiple minor-mode keymaps.
3741 Each element is a keymap alist just like `minor-mode-map-alist', or a
3742 symbol with a variable binding which is a keymap alist, and it is used
3743 the same way. The "active" keymaps in each alist are used before
3744 `minor-mode-map-alist' and `minor-mode-overriding-map-alist'. */);
3745 Vemulation_mode_map_alists = Qnil;
3746
3747 DEFVAR_LISP ("where-is-preferred-modifier", Vwhere_is_preferred_modifier,
3748 doc: /* Preferred modifier key to use for `where-is'.
3749 When a single binding is requested, `where-is' will return one that
3750 uses this modifier key if possible. If nil, or if no such binding
3751 exists, bindings using keys without modifiers (or only with meta) will
3752 be preferred. */);
3753 Vwhere_is_preferred_modifier = Qnil;
3754 where_is_preferred_modifier = 0;
3755
3756 staticpro (&Vmouse_events);
3757 Vmouse_events = listn (CONSTYPE_PURE, 9,
3758 intern_c_string ("menu-bar"),
3759 intern_c_string ("tool-bar"),
3760 intern_c_string ("header-line"),
3761 intern_c_string ("mode-line"),
3762 intern_c_string ("mouse-1"),
3763 intern_c_string ("mouse-2"),
3764 intern_c_string ("mouse-3"),
3765 intern_c_string ("mouse-4"),
3766 intern_c_string ("mouse-5"));
3767
3768 DEFSYM (Qsingle_key_description, "single-key-description");
3769 DEFSYM (Qkey_description, "key-description");
3770 DEFSYM (Qkeymapp, "keymapp");
3771 DEFSYM (Qnon_ascii, "non-ascii");
3772 DEFSYM (Qmenu_item, "menu-item");
3773 DEFSYM (Qremap, "remap");
3774 DEFSYM (QCadvertised_binding, ":advertised-binding");
3775
3776 command_remapping_vector = Fmake_vector (make_number (2), Qremap);
3777 staticpro (&command_remapping_vector);
3778
3779 where_is_cache_keymaps = Qt;
3780 where_is_cache = Qnil;
3781 staticpro (&where_is_cache);
3782 staticpro (&where_is_cache_keymaps);
3783
3784 defsubr (&Skeymapp);
3785 defsubr (&Skeymap_parent);
3786 defsubr (&Skeymap_prompt);
3787 defsubr (&Sset_keymap_parent);
3788 defsubr (&Smake_keymap);
3789 defsubr (&Smake_sparse_keymap);
3790 defsubr (&Smap_keymap_internal);
3791 defsubr (&Smap_keymap);
3792 defsubr (&Scopy_keymap);
3793 defsubr (&Scommand_remapping);
3794 defsubr (&Skey_binding);
3795 defsubr (&Slocal_key_binding);
3796 defsubr (&Sglobal_key_binding);
3797 defsubr (&Sminor_mode_key_binding);
3798 defsubr (&Sdefine_key);
3799 defsubr (&Slookup_key);
3800 defsubr (&Sdefine_prefix_command);
3801 defsubr (&Suse_global_map);
3802 defsubr (&Suse_local_map);
3803 defsubr (&Scurrent_local_map);
3804 defsubr (&Scurrent_global_map);
3805 defsubr (&Scurrent_minor_mode_maps);
3806 defsubr (&Scurrent_active_maps);
3807 defsubr (&Saccessible_keymaps);
3808 defsubr (&Skey_description);
3809 defsubr (&Sdescribe_vector);
3810 defsubr (&Ssingle_key_description);
3811 defsubr (&Stext_char_description);
3812 defsubr (&Swhere_is_internal);
3813 defsubr (&Sdescribe_buffer_bindings);
3814 defsubr (&Sapropos_internal);
3815 }
3816
3817 void
3818 keys_of_keymap (void)
3819 {
3820 initial_define_key (global_map, 033, "ESC-prefix");
3821 initial_define_key (global_map, Ctl ('X'), "Control-X-prefix");
3822 }