keymap.c 111 KB
Newer Older
Jim Blandy's avatar
Jim Blandy committed
1
/* Manipulation of keymaps
Paul Eggert's avatar
Paul Eggert committed
2
   Copyright (C) 1985-1988, 1993-1995, 1998-2020 Free Software
3
   Foundation, Inc.
Jim Blandy's avatar
Jim Blandy committed
4 5 6

This file is part of GNU Emacs.

7
GNU Emacs is free software: you can redistribute it and/or modify
Jim Blandy's avatar
Jim Blandy committed
8
it under the terms of the GNU General Public License as published by
9 10
the Free Software Foundation, either version 3 of the License, or (at
your option) any later version.
Jim Blandy's avatar
Jim Blandy committed
11 12 13 14 15 16 17

GNU Emacs is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
GNU General Public License for more details.

You should have received a copy of the GNU General Public License
18
along with GNU Emacs.  If not, see <https://www.gnu.org/licenses/>.  */
Jim Blandy's avatar
Jim Blandy committed
19

20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40
/* Old BUGS:
   - [M-C-a] != [?\M-\C-a]
   - [M-f2] != [?\e f2].
   - (define-key map [menu-bar foo] <bla>) does not always place <bla>
     at the head of the menu (if `foo' was already bound earlier and
     then unbound, for example).
   TODO:
   - allow many more Meta -> ESC mappings (like Hyper -> C-e for Emacspeak)
   - Think about the various defaulting that's currently hard-coded in
     keyboard.c (uppercase->lowercase, char->charset, button-events, ...)
     and make it more generic.  Maybe we should allow mappings of the
     form (PREDICATE . BINDING) as generalization of the default binding,
     tho probably a cleaner way to attack this is to allow functional
     keymaps (i.e. keymaps that are implemented as functions that implement
     a few different methods like `lookup', `map', ...).
   - Make [a] equivalent to [?a].
   BEWARE:
   - map-keymap should work meaningfully even if entries are added/removed
     to the keymap while iterating through it:
       start - removed <= visited <= start + added
 */
Jim Blandy's avatar
Jim Blandy committed
41

42
#include <config.h>
Jim Blandy's avatar
Jim Blandy committed
43
#include <stdio.h>
Paul Eggert's avatar
Paul Eggert committed
44
#include <stdlib.h>
45

Jim Blandy's avatar
Jim Blandy committed
46 47
#include "lisp.h"
#include "commands.h"
Kenichi Handa's avatar
Kenichi Handa committed
48
#include "character.h"
49
#include "buffer.h"
Jim Blandy's avatar
Jim Blandy committed
50
#include "keyboard.h"
Richard M. Stallman's avatar
Richard M. Stallman committed
51
#include "termhooks.h"
52
#include "blockinput.h"
53
#include "puresize.h"
Dave Love's avatar
Dave Love committed
54
#include "intervals.h"
Stefan Monnier's avatar
Stefan Monnier committed
55
#include "keymap.h"
56
#include "window.h"
Jim Blandy's avatar
Jim Blandy committed
57

58
/* Actually allocate storage for these variables.  */
Jim Blandy's avatar
Jim Blandy committed
59

60
Lisp_Object current_global_map;	/* Current global keymap.  */
Jim Blandy's avatar
Jim Blandy committed
61

62
Lisp_Object global_map;		/* Default global key bindings.  */
Jim Blandy's avatar
Jim Blandy committed
63 64

Lisp_Object meta_map;		/* The keymap used for globally bound
65
				   ESC-prefixed default commands.  */
Jim Blandy's avatar
Jim Blandy committed
66 67

Lisp_Object control_x_map;	/* The keymap used for globally bound
68
				   C-x-prefixed default commands.  */
Jim Blandy's avatar
Jim Blandy committed
69 70 71

				/* The keymap used by the minibuf for local
				   bindings when spaces are allowed in the
72
				   minibuf.  */
Jim Blandy's avatar
Jim Blandy committed
73 74 75

				/* The keymap used by the minibuf for local
				   bindings when spaces are not encouraged
76
				   in the minibuf.  */
Jim Blandy's avatar
Jim Blandy committed
77

78 79 80
/* Alist of elements like (DEL . "\d").  */
static Lisp_Object exclude_keys;

81 82
/* Pre-allocated 2-element vector for Fcommand_remapping to use.  */
static Lisp_Object command_remapping_vector;
83

84 85 86 87 88
/* Hash table used to cache a reverse-map to speed up calls to where-is.  */
static Lisp_Object where_is_cache;
/* Which keymaps are reverse-stored in the cache.  */
static Lisp_Object where_is_cache_keymaps;

89 90 91 92 93 94 95
static Lisp_Object store_in_keymap (Lisp_Object, Lisp_Object, Lisp_Object);

static Lisp_Object define_as_prefix (Lisp_Object, Lisp_Object);
static void describe_command (Lisp_Object, Lisp_Object);
static void describe_translation (Lisp_Object, Lisp_Object);
static void describe_map (Lisp_Object, Lisp_Object,
                          void (*) (Lisp_Object, Lisp_Object),
96
			  bool, Lisp_Object, Lisp_Object *, bool, bool);
97
static void describe_vector (Lisp_Object, Lisp_Object, Lisp_Object,
98 99
                             void (*) (Lisp_Object, Lisp_Object), bool,
                             Lisp_Object, Lisp_Object, bool, bool);
100
static void silly_event_symbol_error (Lisp_Object);
101
static Lisp_Object get_keyelt (Lisp_Object, bool);
102 103 104 105 106 107

static void
CHECK_VECTOR_OR_CHAR_TABLE (Lisp_Object x)
{
  CHECK_TYPE (VECTORP (x) || CHAR_TABLE_P (x), Qvector_or_char_table_p, x);
}
Jim Blandy's avatar
Jim Blandy committed
108

Jim Blandy's avatar
Jim Blandy committed
109 110
/* Keymap object support - constructors and predicates.			*/

111
DEFUN ("make-keymap", Fmake_keymap, Smake_keymap, 0, 1, 0,
112
       doc: /* Construct and return a new keymap, of the form (keymap CHARTABLE . ALIST).
113 114 115 116 117
CHARTABLE is a char-table that holds the bindings for all characters
without modifiers.  All entries in it are initially nil, meaning
"command undefined".  ALIST is an assoc-list which holds bindings for
function keys, mouse events, and any other things that appear in the
input stream.  Initially, ALIST is nil.
118 119 120

The optional arg STRING supplies a menu name for the keymap
in case you use it as a menu with `x-popup-menu'.  */)
Dan Nicolaescu's avatar
Dan Nicolaescu committed
121
  (Lisp_Object string)
Jim Blandy's avatar
Jim Blandy committed
122
{
Paul Eggert's avatar
Paul Eggert committed
123
  Lisp_Object tail = !NILP (string) ? list1 (string) : Qnil;
Jim Blandy's avatar
Jim Blandy committed
124
  return Fcons (Qkeymap,
125
		Fcons (Fmake_char_table (Qkeymap, Qnil), tail));
Jim Blandy's avatar
Jim Blandy committed
126 127
}

Paul Eggert's avatar
Paul Eggert committed
128
DEFUN ("make-sparse-keymap", Fmake_sparse_keymap, Smake_sparse_keymap, 0, 1, 0,
129 130 131 132 133 134 135 136
       doc: /* Construct and return a new sparse keymap.
Its car is `keymap' and its cdr is an alist of (CHAR . DEFINITION),
which binds the character CHAR to DEFINITION, or (SYMBOL . DEFINITION),
which binds the function key or mouse event SYMBOL to DEFINITION.
Initially the alist is nil.

The optional arg STRING supplies a menu name for the keymap
in case you use it as a menu with `x-popup-menu'.  */)
Dan Nicolaescu's avatar
Dan Nicolaescu committed
137
  (Lisp_Object string)
Jim Blandy's avatar
Jim Blandy committed
138
{
139
  if (!NILP (string))
140 141 142
    {
      if (!NILP (Vpurify_flag))
	string = Fpurecopy (string);
143
      return list2 (Qkeymap, string);
144
    }
145
  return list1 (Qkeymap);
Jim Blandy's avatar
Jim Blandy committed
146 147 148 149 150 151 152
}

/* This function is used for installing the standard key bindings
   at initialization time.

   For example:

153
   initial_define_key (control_x_map, Ctl('X'), "exchange-point-and-mark");  */
Jim Blandy's avatar
Jim Blandy committed
154 155

void
156
initial_define_key (Lisp_Object keymap, int key, const char *defname)
Jim Blandy's avatar
Jim Blandy committed
157
{
158
  store_in_keymap (keymap, make_fixnum (key), intern_c_string (defname));
Jim Blandy's avatar
Jim Blandy committed
159 160
}

161
void
162
initial_define_lispy_key (Lisp_Object keymap, const char *keyname, const char *defname)
163
{
Dan Nicolaescu's avatar
Dan Nicolaescu committed
164
  store_in_keymap (keymap, intern_c_string (keyname), intern_c_string (defname));
165 166
}

Jim Blandy's avatar
Jim Blandy committed
167
DEFUN ("keymapp", Fkeymapp, Skeymapp, 1, 1, 0,
168 169 170 171 172 173 174
       doc: /* Return t if OBJECT is a keymap.

A keymap is a list (keymap . ALIST),
or a symbol whose function definition is itself a keymap.
ALIST elements look like (CHAR . DEFN) or (SYMBOL . DEFN);
a vector of densely packed bindings for small character codes
is also allowed as an element.  */)
Dan Nicolaescu's avatar
Dan Nicolaescu committed
175
  (Lisp_Object object)
Jim Blandy's avatar
Jim Blandy committed
176
{
177
  return (KEYMAPP (object) ? Qt : Qnil);
Jim Blandy's avatar
Jim Blandy committed
178 179
}

Paul Eggert's avatar
Paul Eggert committed
180
DEFUN ("keymap-prompt", Fkeymap_prompt, Skeymap_prompt, 1, 1, 0,
181 182 183
       doc: /* Return the prompt-string of a keymap MAP.
If non-nil, the prompt is shown in the echo-area
when reading a key-sequence to be looked-up in this keymap.  */)
Dan Nicolaescu's avatar
Dan Nicolaescu committed
184
  (Lisp_Object map)
185
{
186
  map = get_keymap (map, 0, 0);
187 188
  while (CONSP (map))
    {
189
      Lisp_Object tem = XCAR (map);
190 191
      if (STRINGP (tem))
	return tem;
192 193 194 195 196 197
      else if (KEYMAPP (tem))
	{
	  tem = Fkeymap_prompt (tem);
	  if (!NILP (tem))
	    return tem;
	}
198
      map = XCDR (map);
199 200 201 202
    }
  return Qnil;
}

Jim Blandy's avatar
Jim Blandy committed
203
/* Check that OBJECT is a keymap (after dereferencing through any
204 205
   symbols).  If it is, return it.

206
   If AUTOLOAD and if OBJECT is a symbol whose function value
207
   is an autoload form, do the autoload and try again.
208
   If AUTOLOAD, callers must assume GC is possible.
209

210
   ERROR_IF_NOT_KEYMAP controls how we respond if OBJECT isn't a keymap.
211
   If ERROR_IF_NOT_KEYMAP, signal an error; otherwise,
212
   just return Qnil.
213 214 215 216 217

   Note that most of the time, we don't want to pursue autoloads.
   Functions like Faccessible_keymaps which scan entire keymap trees
   shouldn't load every autoloaded keymap.  I'm not sure about this,
   but it seems to me that only read_key_sequence, Flookup_key, and
218 219
   Fdefine_key should cause keymaps to be autoloaded.

220
   This function can GC when AUTOLOAD is true, because it calls
221
   Fautoload_do_load which can GC.  */
222

Jim Blandy's avatar
Jim Blandy committed
223
Lisp_Object
224
get_keymap (Lisp_Object object, bool error_if_not_keymap, bool autoload)
Jim Blandy's avatar
Jim Blandy committed
225
{
226
  Lisp_Object tem;
Jim Blandy's avatar
Jim Blandy committed
227

228
 autoload_retry:
229 230 231 232
  if (NILP (object))
    goto end;
  if (CONSP (object) && EQ (XCAR (object), Qkeymap))
    return object;
233

234 235
  tem = indirect_function (object);
  if (CONSP (tem))
236
    {
237 238
      if (EQ (XCAR (tem), Qkeymap))
	return tem;
239

240 241
      /* Should we do an autoload?  Autoload forms for keymaps have
	 Qkeymap as their fifth element.  */
242
      if ((autoload || !error_if_not_keymap) && EQ (XCAR (tem), Qautoload)
243
	  && SYMBOLP (object))
244
	{
245
	  Lisp_Object tail;
246

247
	  tail = Fnth (make_fixnum (4), tem);
248 249 250 251
	  if (EQ (tail, Qkeymap))
	    {
	      if (autoload)
		{
252
		  Fautoload_do_load (tem, object, Qnil);
253 254 255
		  goto autoload_retry;
		}
	      else
256
	      	return object;
257
	    }
258
	}
259 260
    }

261
 end:
262
  if (error_if_not_keymap)
Jim Blandy's avatar
Jim Blandy committed
263
    wrong_type_argument (Qkeymapp, object);
264
  return Qnil;
Jim Blandy's avatar
Jim Blandy committed
265
}
266

267 268
/* Return the parent map of KEYMAP, or nil if it has none.
   We assume that KEYMAP is a valid keymap.  */
269

270
static Lisp_Object
271
keymap_parent (Lisp_Object keymap, bool autoload)
272 273 274
{
  Lisp_Object list;

275
  keymap = get_keymap (keymap, 1, autoload);
276 277

  /* Skip past the initial element `keymap'.  */
278 279
  list = XCDR (keymap);
  for (; CONSP (list); list = XCDR (list))
280 281
    {
      /* See if there is another `keymap'.  */
282
      if (KEYMAPP (list))
283 284 285
	return list;
    }

286
  return get_keymap (list, 0, autoload);
287 288
}

289
DEFUN ("keymap-parent", Fkeymap_parent, Skeymap_parent, 1, 1, 0,
290 291
       doc: /* Return the parent keymap of KEYMAP.
If KEYMAP has no parent, return nil.  */)
Dan Nicolaescu's avatar
Dan Nicolaescu committed
292
  (Lisp_Object keymap)
293 294 295
{
  return keymap_parent (keymap, 1);
}
296

297
/* Check whether MAP is one of MAPS parents.  */
298
static bool
299
keymap_memberp (Lisp_Object map, Lisp_Object maps)
300
{
301
  if (NILP (map)) return 0;
302
  while (KEYMAPP (maps) && !EQ (map, maps))
303
    maps = keymap_parent (maps, 0);
304 305 306
  return (EQ (map, maps));
}

307 308
/* Set the parent keymap of MAP to PARENT.  */

Paul Eggert's avatar
Paul Eggert committed
309
DEFUN ("set-keymap-parent", Fset_keymap_parent, Sset_keymap_parent, 2, 2, 0,
310
       doc: /* Modify KEYMAP to set its parent map to PARENT.
311
Return PARENT.  PARENT should be nil or another keymap.  */)
Dan Nicolaescu's avatar
Dan Nicolaescu committed
312
  (Lisp_Object keymap, Lisp_Object parent)
313 314
{
  Lisp_Object list, prev;
Jim Blandy's avatar
Jim Blandy committed
315

316 317
  /* Flush any reverse-map cache.  */
  where_is_cache = Qnil; where_is_cache_keymaps = Qt;
318

319
  keymap = get_keymap (keymap, 1, 1);
320

321
  if (!NILP (parent))
322
    {
323
      parent = get_keymap (parent, 1, 0);
324 325

      /* Check for cycles.  */
326
      if (keymap_memberp (keymap, parent))
327 328
	error ("Cyclic keymap inheritance");
    }
Jim Blandy's avatar
Jim Blandy committed
329

330 331 332 333
  /* Skip past the initial element `keymap'.  */
  prev = keymap;
  while (1)
    {
334
      list = XCDR (prev);
335 336
      /* If there is a parent keymap here, replace it.
	 If we came to the end, add the parent in PREV.  */
337
      if (!CONSP (list) || KEYMAPP (list))
338
	{
Paul Eggert's avatar
Paul Eggert committed
339
	  CHECK_IMPURE (prev, XCONS (prev));
340
	  XSETCDR (prev, parent);
341
	  return parent;
342 343 344 345 346
	}
      prev = list;
    }
}

347

Jim Blandy's avatar
Jim Blandy committed
348
/* Look up IDX in MAP.  IDX may be any sort of event.
349
   Note that this does only one level of lookup; IDX must be a single
350
   event, not a sequence.
351

352 353
   MAP must be a keymap or a list of keymaps.

354
   If T_OK, bindings for Qt are treated as default
355
   bindings; any key left unmentioned by other tables and bindings is
356
   given the binding of Qt.
357

358
   If not T_OK, bindings for Qt are not treated specially.
359

360 361
   If NOINHERIT, don't accept a subkeymap found in an inherited keymap.

362
   Return Qunbound if no binding was found (and return Qnil if a nil
363
   binding was found).  */
Jim Blandy's avatar
Jim Blandy committed
364

365
static Lisp_Object
366 367
access_keymap_1 (Lisp_Object map, Lisp_Object idx,
		 bool t_ok, bool noinherit, bool autoload)
Jim Blandy's avatar
Jim Blandy committed
368 369 370 371
{
  /* If idx is a list (some sort of mouse click, perhaps?),
     the index we want to use is the car of the list, which
     ought to be a symbol.  */
372
  idx = EVENT_HEAD (idx);
Jim Blandy's avatar
Jim Blandy committed
373

374 375
  /* If idx is a symbol, it might have modifiers, which need to
     be put in the canonical order.  */
376
  if (SYMBOLP (idx))
377
    idx = reorder_modifiers (idx);
378
  else if (FIXNUMP (idx))
379 380
    /* Clobber the high bits that can be present on a machine
       with more than 24 bits of integer.  */
Tom Tromey's avatar
Tom Tromey committed
381
    XSETFASTINT (idx, XFIXNUM (idx) & (CHAR_META | (CHAR_META - 1)));
Jim Blandy's avatar
Jim Blandy committed
382

383
  /* Handle the special meta -> esc mapping.  */
Tom Tromey's avatar
Tom Tromey committed
384
  if (FIXNUMP (idx) && XFIXNAT (idx) & meta_modifier)
385
    {
386 387
      /* See if there is a meta-map.  If there's none, there is
         no binding for IDX, unless a default binding exists in MAP.  */
388
      Lisp_Object event_meta_binding, event_meta_map;
389 390
      /* A strange value in which Meta is set would cause
	 infinite recursion.  Protect against that.  */
Tom Tromey's avatar
Tom Tromey committed
391
      if (XFIXNUM (meta_prefix_char) & CHAR_META)
392
	meta_prefix_char = make_fixnum (27);
393 394 395
      event_meta_binding = access_keymap_1 (map, meta_prefix_char, t_ok,
					    noinherit, autoload);
      event_meta_map = get_keymap (event_meta_binding, 0, autoload);
396
      if (CONSP (event_meta_map))
397
	{
398
	  map = event_meta_map;
Tom Tromey's avatar
Tom Tromey committed
399
	  idx = make_fixnum (XFIXNAT (idx) & ~meta_modifier);
400 401 402 403 404
	}
      else if (t_ok)
	/* Set IDX to t, so that we only find a default binding.  */
	idx = Qt;
      else
405 406
	/* An explicit nil binding, or no binding at all.  */
	return NILP (event_meta_binding) ? Qnil : Qunbound;
407 408
    }

409 410 411
  /* t_binding is where we put a default binding that applies,
     to use in case we do not find a binding specifically
     for this key sequence.  */
412 413
  {
    Lisp_Object tail;
414 415 416
    Lisp_Object t_binding = Qunbound;
    Lisp_Object retval = Qunbound;
    Lisp_Object retval_tail = Qnil;
417

418
    for (tail = (CONSP (map) && EQ (Qkeymap, XCAR (map))) ? XCDR (map) : map;
419
	 (CONSP (tail)
420
	  || (tail = get_keymap (tail, 0, autoload), CONSP (tail)));
421
	 tail = XCDR (tail))
Jim Blandy's avatar
Jim Blandy committed
422
      {
423 424 425 426
	/* Qunbound in VAL means we have found no binding.  */
	Lisp_Object val = Qunbound;
	Lisp_Object binding = XCAR (tail);
	Lisp_Object submap = get_keymap (binding, 0, autoload);
427

428
	if (EQ (binding, Qkeymap))
429
	  {
430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456
	    if (noinherit || NILP (retval))
	      /* If NOINHERIT, stop here, the rest is inherited.  */
	      break;
	    else if (!EQ (retval, Qunbound))
	      {
		Lisp_Object parent_entry;
		eassert (KEYMAPP (retval));
		parent_entry
		  = get_keymap (access_keymap_1 (tail, idx,
						 t_ok, 0, autoload),
				0, autoload);
		if (KEYMAPP (parent_entry))
		  {
		    if (CONSP (retval_tail))
		      XSETCDR (retval_tail, parent_entry);
		    else
		      {
			retval_tail = Fcons (retval, parent_entry);
			retval = Fcons (Qkeymap, retval_tail);
		      }
		  }
		break;
	      }
	  }
	else if (CONSP (submap))
	  {
	    val = access_keymap_1 (submap, idx, t_ok, noinherit, autoload);
457 458 459
	  }
	else if (CONSP (binding))
	  {
460
	    Lisp_Object key = XCAR (binding);
461

462
	    if (EQ (key, idx))
463
	      val = XCDR (binding);
464
	    else if (t_ok && EQ (key, Qt))
465 466
	      {
		t_binding = XCDR (binding);
467
		t_ok = 0;
468
	      }
469 470 471
	  }
	else if (VECTORP (binding))
	  {
Tom Tromey's avatar
Tom Tromey committed
472 473
	    if (FIXNUMP (idx) && XFIXNAT (idx) < ASIZE (binding))
	      val = AREF (binding, XFIXNAT (idx));
474
	  }
475 476
	else if (CHAR_TABLE_P (binding))
	  {
477 478 479
	    /* Character codes with modifiers
	       are not included in a char-table.
	       All character codes without modifiers are included.  */
Tom Tromey's avatar
Tom Tromey committed
480
	    if (FIXNUMP (idx) && (XFIXNAT (idx) & CHAR_MODIFIER_MASK) == 0)
481 482
	      {
		val = Faref (binding, idx);
483
		/* nil has a special meaning for char-tables, so
484 485 486 487 488
		   we use something else to record an explicitly
		   unbound entry.  */
		if (NILP (val))
		  val = Qunbound;
	      }
489
	  }
490

491 492 493
	/* If we found a binding, clean it up and return it.  */
	if (!EQ (val, Qunbound))
	  {
494 495 496 497 498
	    if (EQ (val, Qt))
	      /* A Qt binding is just like an explicit nil binding
		 (i.e. it shadows any parent binding but not bindings in
		 keymaps of lower precedence).  */
	      val = Qnil;
499

500
	    val = get_keyelt (val, autoload);
501 502 503 504 505 506 507 508 509 510 511 512

	    if (!KEYMAPP (val))
	      {
		if (NILP (retval) || EQ (retval, Qunbound))
		  retval = val;
		if (!NILP (val))
		  break;  /* Shadows everything that follows.  */
	      }
	    else if (NILP (retval) || EQ (retval, Qunbound))
	      retval = val;
	    else if (CONSP (retval_tail))
	      {
513
		XSETCDR (retval_tail, list1 (val));
514 515 516 517
		retval_tail = XCDR (retval_tail);
	      }
	    else
	      {
518
		retval_tail = list1 (val);
519 520
		retval = Fcons (Qkeymap, Fcons (retval, retval_tail));
	      }
521
	  }
Paul Eggert's avatar
Paul Eggert committed
522
	maybe_quit ();
Jim Blandy's avatar
Jim Blandy committed
523
      }
524

525
    return EQ (Qunbound, retval) ? get_keyelt (t_binding, autoload) : retval;
526
  }
Jim Blandy's avatar
Jim Blandy committed
527 528
}

529 530
Lisp_Object
access_keymap (Lisp_Object map, Lisp_Object idx,
531
	       bool t_ok, bool noinherit, bool autoload)
532 533 534 535 536
{
  Lisp_Object val = access_keymap_1 (map, idx, t_ok, noinherit, autoload);
  return EQ (val, Qunbound) ? Qnil : val;
}

537
static void
538
map_keymap_item (map_keymap_function_t fun, Lisp_Object args, Lisp_Object key, Lisp_Object val, void *data)
539 540 541 542 543 544
{
  if (EQ (val, Qt))
    val = Qnil;
  (*fun) (key, val, args, data);
}

545 546 547 548 549 550 551 552
union map_keymap
{
  struct
  {
    map_keymap_function_t fun;
    Lisp_Object args;
    void *data;
  } s;
Paul Eggert's avatar
Paul Eggert committed
553
  GCALIGNED_UNION_MEMBER
554
};
Paul Eggert's avatar
Paul Eggert committed
555
verify (GCALIGNED (union map_keymap));
556

557
static void
558
map_keymap_char_table_item (Lisp_Object args, Lisp_Object key, Lisp_Object val)
559 560 561
{
  if (!NILP (val))
    {
562 563 564 565
      /* If the key is a range, make a copy since map_char_table modifies
	 it in place.  */
      if (CONSP (key))
	key = Fcons (XCAR (key), XCDR (key));
Tom Tromey's avatar
Tom Tromey committed
566
      union map_keymap *md = XFIXNUMPTR (args);
567
      map_keymap_item (md->s.fun, md->s.args, key, val, md->s.data);
568 569 570
    }
}

571 572
/* Call FUN for every binding in MAP and stop at (and return) the parent.
   FUN is called with 4 arguments: FUN (KEY, BINDING, ARGS, DATA).  */
573
static Lisp_Object
574 575 576 577
map_keymap_internal (Lisp_Object map,
		     map_keymap_function_t fun,
		     Lisp_Object args,
		     void *data)
578
{
579 580
  Lisp_Object tail
    = (CONSP (map) && EQ (Qkeymap, XCAR (map))) ? XCDR (map) : map;
581

582
  for (; CONSP (tail) && !EQ (Qkeymap, XCAR (tail)); tail = XCDR (tail))
583 584
    {
      Lisp_Object binding = XCAR (tail);
Kenichi Handa's avatar
Kenichi Handa committed
585

586 587 588
      if (KEYMAPP (binding))	/* An embedded parent.  */
	break;
      else if (CONSP (binding))
589 590 591 592 593 594 595 596 597 598 599 600 601 602
	map_keymap_item (fun, args, XCAR (binding), XCDR (binding), data);
      else if (VECTORP (binding))
	{
	  /* Loop over the char values represented in the vector.  */
	  int len = ASIZE (binding);
	  int c;
	  for (c = 0; c < len; c++)
	    {
	      Lisp_Object character;
	      XSETFASTINT (character, c);
	      map_keymap_item (fun, args, character, AREF (binding, c), data);
	    }
	}
      else if (CHAR_TABLE_P (binding))
603 604 605 606 607
	{
	  union map_keymap mapdata = {{fun, args, data}};
	  map_char_table (map_keymap_char_table_item, Qnil, binding,
			  make_pointer_integer (&mapdata));
	}
608
    }
609

610
  return tail;
611 612 613
}

static void
614
map_keymap_call (Lisp_Object key, Lisp_Object val, Lisp_Object fun, void *dummy)
615 616 617 618
{
  call2 (fun, key, val);
}

619
/* Same as map_keymap_internal, but traverses parent keymaps as well.
620
   AUTOLOAD indicates that autoloaded keymaps should be loaded.  */
621
void
622 623
map_keymap (Lisp_Object map, map_keymap_function_t fun, Lisp_Object args,
	    void *data, bool autoload)
624 625 626 627
{
  map = get_keymap (map, 1, autoload);
  while (CONSP (map))
    {
628 629 630 631 632 633 634 635 636
      if (KEYMAPP (XCAR (map)))
	{
	  map_keymap (XCAR (map), fun, args, data, autoload);
	  map = XCDR (map);
	}
      else
	map = map_keymap_internal (map, fun, args, data);
      if (!CONSP (map))
	map = get_keymap (map, 0, autoload);
637 638 639
    }
}

640 641 642
/* Same as map_keymap, but does it right, properly eliminating duplicate
   bindings due to inheritance.   */
void
643
map_keymap_canonical (Lisp_Object map, map_keymap_function_t fun, Lisp_Object args, void *data)
644 645 646 647 648 649 650 651
{
  /* map_keymap_canonical may be used from redisplay (e.g. when building menus)
     so be careful to ignore errors and to inhibit redisplay.  */
  map = safe_call1 (Qkeymap_canonicalize, map);
  /* No need to use `map_keymap' here because canonical map has no parent.  */
  map_keymap_internal (map, fun, args, data);
}

652 653 654 655 656
DEFUN ("map-keymap-internal", Fmap_keymap_internal, Smap_keymap_internal, 2, 2, 0,
       doc: /* Call FUNCTION once for each event binding in KEYMAP.
FUNCTION is called with two arguments: the event that is bound, and
the definition it is bound to.  The event may be a character range.
If KEYMAP has a parent, this function returns it without processing it.  */)
Dan Nicolaescu's avatar
Dan Nicolaescu committed
657
  (Lisp_Object function, Lisp_Object keymap)
658 659 660 661 662 663
{
  keymap = get_keymap (keymap, 1, 1);
  keymap = map_keymap_internal (keymap, map_keymap_call, function, NULL);
  return keymap;
}

664
DEFUN ("map-keymap", Fmap_keymap, Smap_keymap, 2, 3, 0,
Richard M. Stallman's avatar
Richard M. Stallman committed
665
       doc: /* Call FUNCTION once for each event binding in KEYMAP.
Richard M. Stallman's avatar
Richard M. Stallman committed
666
FUNCTION is called with two arguments: the event that is bound, and
667
the definition it is bound to.  The event may be a character range.
Richard M. Stallman's avatar
Richard M. Stallman committed
668

669 670
If KEYMAP has a parent, the parent's bindings are included as well.
This works recursively: if the parent has itself a parent, then the
671 672
grandparent's bindings are also included and so on.
usage: (map-keymap FUNCTION KEYMAP)  */)
Dan Nicolaescu's avatar
Dan Nicolaescu committed
673
  (Lisp_Object function, Lisp_Object keymap, Lisp_Object sort_first)
674
{
675
  if (! NILP (sort_first))
676
    return call2 (intern ("map-keymap-sorted"), function, keymap);
677

678 679 680 681
  map_keymap (keymap, map_keymap_call, function, NULL, 1);
  return Qnil;
}

Jim Blandy's avatar
Jim Blandy committed
682 683 684 685 686 687 688
/* Given OBJECT which was found in a slot in a keymap,
   trace indirect definitions to get the actual definition of that slot.
   An indirect definition is a list of the form
   (KEYMAP . INDEX), where KEYMAP is a keymap or a symbol defined as one
   and INDEX is the object to look up in KEYMAP to yield the definition.

   Also if OBJECT has a menu string as the first element,
689 690
   remove that.  Also remove a menu help string as second element.

691
   If AUTOLOAD, load autoloadable keymaps
692 693 694
   that are referred to with indirection.

   This can GC because menu_item_eval_property calls Feval.  */
Jim Blandy's avatar
Jim Blandy committed
695

Andreas Schwab's avatar
Andreas Schwab committed
696
static Lisp_Object
697
get_keyelt (Lisp_Object object, bool autoload)
Jim Blandy's avatar
Jim Blandy committed
698 699 700
{
  while (1)
    {
701 702 703
      if (!(CONSP (object)))
	/* This is really the value.  */
	return object;
Jim Blandy's avatar
Jim Blandy committed
704

705 706
      /* If the keymap contents looks like (menu-item name . DEFN)
	 or (menu-item name DEFN ...) then use DEFN.
707
	 This is a new format menu item.  */
708
      else if (EQ (XCAR (object), Qmenu_item))
709
	{
710
	  if (CONSP (XCDR (object)))
711
	    {
712 713
	      Lisp_Object tem;

714
	      object = XCDR (XCDR (object));
715
	      tem = object;
716 717
	      if (CONSP (object))
		object = XCAR (object);
718 719 720

	      /* If there's a `:filter FILTER', apply FILTER to the
		 menu-item's definition to get the real definition to
721
		 use.  */
722
	      for (; CONSP (tem) && CONSP (XCDR (tem)); tem = XCDR (tem))
723
		if (EQ (XCAR (tem), QCfilter) && autoload)
724 725 726 727 728 729 730
		  {
		    Lisp_Object filter;
		    filter = XCAR (XCDR (tem));
		    filter = list2 (filter, list2 (Qquote, object));
		    object = menu_item_eval_property (filter);
		    break;
		  }
731 732
	    }
	  else
733
	    /* Invalid keymap.  */
734
	    return object;
735 736
	}

737
      /* If the keymap contents looks like (STRING . DEFN), use DEFN.
Jim Blandy's avatar
Jim Blandy committed
738 739
	 Keymap alist elements like (CHAR MENUSTRING . DEFN)
	 will be used by HierarKey menus.  */
740
      else if (STRINGP (XCAR (object)))
741
	object = XCDR (object);
Jim Blandy's avatar
Jim Blandy committed
742

743
      else
744
	return object;
Jim Blandy's avatar
Jim Blandy committed
745 746 747
    }
}

748
static Lisp_Object
749
store_in_keymap (Lisp_Object keymap, register Lisp_Object idx, Lisp_Object def)
Jim Blandy's avatar
Jim Blandy committed
750
{
751 752 753 754
  /* Flush any reverse-map cache.  */
  where_is_cache = Qnil;
  where_is_cache_keymaps = Qt;

755 756 757
  if (EQ (idx, Qkeymap))
    error ("`keymap' is reserved for embedded parent maps");

758
  /* If we are preparing to dump, and DEF is a menu element
759
     with a menu item indicator, copy it to ensure it is not pure.  */
Paul Eggert's avatar
Paul Eggert committed
760
  if (CONSP (def) && PURE_P (XCONS (def))
761 762
      && (EQ (XCAR (def), Qmenu_item) || STRINGP (XCAR (def))))
    def = Fcons (XCAR (def), XCDR (def));
763

764
  if (!CONSP (keymap) || !EQ (XCAR (keymap), Qkeymap))
765 766
    error ("attempt to define a key in a non-keymap");

767 768 769 770 771 772 773 774 775
  /* If idx is a cons, and the car part is a character, idx must be of
     the form (FROM-CHAR . TO-CHAR).  */
  if (CONSP (idx) && CHARACTERP (XCAR (idx)))
    CHECK_CHARACTER_CDR (idx);
  else
    /* If idx is a list (some sort of mouse click, perhaps?),
       the index we want to use is the car of the list, which
       ought to be a symbol.  */
    idx = EVENT_HEAD (idx);
Jim Blandy's avatar
Jim Blandy committed
776

777 778
  /* If idx is a symbol, it might have modifiers, which need to
     be put in the canonical order.  */
779
  if (SYMBOLP (idx))
780
    idx = reorder_modifiers (idx);
781
  else if (FIXNUMP (idx))
782 783
    /* Clobber the high bits that can be present on a machine
       with more than 24 bits of integer.  */
Tom Tromey's avatar
Tom Tromey committed
784
    XSETFASTINT (idx, XFIXNUM (idx) & (CHAR_META | (CHAR_META - 1)));
785 786

  /* Scan the keymap for a binding of idx.  */
Jim Blandy's avatar
Jim Blandy committed
787
  {
788
    Lisp_Object tail;
Jim Blandy's avatar
Jim Blandy committed
789

790 791 792 793 794 795
    /* The cons after which we should insert new bindings.  If the
       keymap has a table element, we record its position here, so new
       bindings will go after it; this way, the table will stay
       towards the front of the alist and character lookups in dense
       keymaps will remain fast.  Otherwise, this just points at the
       front of the keymap.  */
796
    Lisp_Object insertion_point;
Jim Blandy's avatar
Jim Blandy committed
797

798
    insertion_point = keymap;
799
    for (tail = XCDR (keymap); CONSP (tail); tail = XCDR (tail))
Jim Blandy's avatar
Jim Blandy committed
800
      {
801
	Lisp_Object elt;
802

803
	elt = XCAR (tail);
804
	if (VECTORP (elt))
805
	  {
Tom Tromey's avatar
Tom Tromey committed
806
	    if (FIXNATP (idx) && XFIXNAT (idx) < ASIZE (elt))
807
	      {
Paul Eggert's avatar
Paul Eggert committed
808
		CHECK_IMPURE (elt, XVECTOR (elt));
Tom Tromey's avatar
Tom Tromey committed
809
		ASET (elt, XFIXNAT (idx), def);
810 811
		return def;
	      }
812 813
	    else if (CONSP (idx) && CHARACTERP (XCAR (idx)))
	      {
Tom Tromey's avatar
Tom Tromey committed
814 815
		int from = XFIXNAT (XCAR (idx));
		int to = XFIXNAT (XCDR (idx));
816 817 818 819 820

		if (to >= ASIZE (elt))
		  to = ASIZE (elt) - 1;
		for (; from <= to; from++)
		  ASET (elt, from, def);
Tom Tromey's avatar
Tom Tromey committed
821
		if (to == XFIXNAT (XCDR (idx)))
822 823 824
		  /* We have defined all keys in IDX.  */
		  return def;
	      }
825
	    insertion_point = tail;
826
	  }
827 828
	else if (CHAR_TABLE_P (elt))
	  {
829 830 831
	    /* Character codes with modifiers
	       are not included in a char-table.
	       All character codes without modifiers are included.  */
Tom Tromey's avatar
Tom Tromey committed
832
	    if (FIXNATP (idx) && !(XFIXNAT (idx) & CHAR_MODIFIER_MASK))
833
	      {
834
		Faset (elt, idx,
835
		       /* nil has a special meaning for char-tables, so
836 837 838
			  we use something else to record an explicitly
			  unbound entry.  */
		       NILP (def) ? Qt : def);
839 840
		return def;
	      }
Kenichi Handa's avatar
Kenichi Handa committed
841 842 843 844 845
	    else if (CONSP (idx) && CHARACTERP (XCAR (idx)))
	      {
		Fset_char_table_range (elt, idx, NILP (def) ? Qt : def);
		return def;
	      }
846 847
	    insertion_point = tail;
	  }
848 849
	else if (CONSP (elt))
	  {
850 851 852 853 854 855 856 857 858 859
	    if (EQ (Qkeymap, XCAR (elt)))
	      { /* A sub keymap.  This might be due to a lookup that found
		   two matching bindings (maybe because of a sub keymap).
		   It almost never happens (since the second binding normally
		   only happens in the inherited part of the keymap), but
		   if it does, we want to update the sub-keymap since the
		   main one might be temporary (built by access_keymap).  */
		tail = insertion_point = elt;
	      }
	    else if (EQ (idx, XCAR (elt)))
860
	      {
Paul Eggert's avatar
Paul Eggert committed
861
		CHECK_IMPURE (elt, XCONS (elt));
862
		XSETCDR (elt, def);
863 864
		return def;
	      }
865 866 867
	    else if (CONSP (idx)
		     && CHARACTERP (XCAR (idx))
		     && CHARACTERP (XCAR (elt)))
868
	      {
Tom Tromey's avatar
Tom Tromey committed
869 870
		int from = XFIXNAT (XCAR (idx));
		int to = XFIXNAT (XCDR (idx));
871

Tom Tromey's avatar
Tom Tromey committed
872 873
		if (from <= XFIXNAT (XCAR (elt))
		    && to >= XFIXNAT (XCAR (elt)))
874 875 876 877 878 879
		  {
		    XSETCDR (elt, def);
		    if (from == to)
		      return def;
		  }
	      }
880
	  }
881 882 883 884 885 886
	else if (EQ (elt, Qkeymap))
	  /* If we find a 'keymap' symbol in the spine of KEYMAP,
	     then we must have found the start of a second keymap
	     being used as the tail of KEYMAP, and a binding for IDX
	     should be inserted before it.  */
	  goto keymap_end;
887

Paul Eggert's avatar
Paul Eggert committed
888
	maybe_quit ();
Jim Blandy's avatar
Jim Blandy committed
889 890
      }

891 892 893
  keymap_end:
    /* We have scanned the entire keymap, and not found a binding for
       IDX.  Let's add one.  */
894 895 896 897 898 899 900 901 902 903 904 905 906
    {
      Lisp_Object elt;

      if (CONSP (idx) && CHARACTERP (XCAR (idx)))
	{
	  /* IDX specifies a range of characters, and not all of them
	     were handled yet, which means this keymap doesn't have a
	     char-table.  So, we insert a char-table now.  */
	  elt = Fmake_char_table (Qkeymap, Qnil);
	  Fset_char_table_range (elt, idx, NILP (def) ? Qt : def);
	}
      else
	elt = Fcons (idx, def);
Paul Eggert's avatar
Paul Eggert committed
907
      CHECK_IMPURE (insertion_point, XCONS (insertion_point));
908 909
      XSETCDR (insertion_point, Fcons (elt, XCDR (insertion_point)));
    }
910
  }
911

Jim Blandy's avatar
Jim Blandy committed
912 913 914
  return def;
}

915 916
static Lisp_Object copy_keymap_1 (Lisp_Object keymap, int depth);

917
static Lisp_Object
918
copy_keymap_item (Lisp_Object elt, int depth)
919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947
{
  Lisp_Object res, tem;

  if (!CONSP (elt))
    return elt;

  res = tem = elt;

  /* Is this a new format menu item.  */
  if (EQ (XCAR (tem), Qmenu_item))
    {
      /* Copy cell with menu-item marker.  */
      res = elt = Fcons (XCAR (tem), XCDR (tem));
      tem = XCDR (elt);
      if (CONSP (tem))
	{
	  /* Copy cell with menu-item name.  */
	  XSETCDR (elt, Fcons (XCAR (tem), XCDR (tem)));
	  elt = XCDR (elt);
	  tem = XCDR (elt);
	}
      if (CONSP (tem))
	{
	  /* Copy cell with binding and if the binding is a keymap,
	     copy that.  */
	  XSETCDR (elt, Fcons (XCAR (tem), XCDR (tem)));
	  elt = XCDR (elt);
	  tem = XCAR (elt);
	  if (CONSP (tem) && EQ (XCAR (tem), Qkeymap))
948
	    XSETCAR (elt, copy_keymap_1 (tem, depth));
949 950 951 952 953
	  tem = XCDR (elt);
	}
    }
  else
    {
Paul Eggert's avatar
Paul Eggert committed
954
      /* It may be an old format menu item.
955 956 957 958 959 960 961 962 963 964 965 966 967 968
	 Skip the optional menu string.  */
      if (STRINGP (XCAR (tem)))
	{
	  /* Copy the cell, since copy-alist didn't go this deep.  */
	  res = elt = Fcons (XCAR (tem), XCDR (tem));
	  tem = XCDR (elt);
	  /* Also skip the optional menu help string.  */
	  if (CONSP (tem) && STRINGP (XCAR (tem)))
	    {
	      XSETCDR (elt, Fcons (XCAR (tem), XCDR (tem)));
	      elt = XCDR (elt);
	      tem = XCDR (elt);
	    }
	  if (CONSP (tem) && EQ (XCAR (tem), Qkeymap))
969
	    XSETCDR (elt, copy_keymap_1 (tem, depth));
970 971
	}
      else if (EQ (XCAR (tem), Qkeymap))
972
	res = copy_keymap_1 (elt, depth);
973 974 975 976
    }
  return res;
}

977
static void
978
copy_keymap_set_char_table (Lisp_Object chartable_and_depth, Lisp_Object idx,
979
			    Lisp_Object elt)
980
{
981 982 983
  Fset_char_table_range
    (XCAR (chartable_and_depth), idx,
     copy_keymap_item (elt, XFIXNUM (XCDR (chartable_and_depth))));
984
}
985

986 987
static Lisp_Object
copy_keymap_1 (Lisp_Object keymap, int depth)
Jim Blandy's avatar
Jim Blandy committed
988
{