keyboard.c 184 KB
Newer Older
Jim Blandy's avatar
Jim Blandy committed
1
/* Keyboard and mouse input; editor command loop.
2
   Copyright (C) 1985,86,87,88,89,93,94,95 Free Software Foundation, Inc.
Jim Blandy's avatar
Jim Blandy committed
3 4 5 6 7

This file is part of GNU Emacs.

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

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
along with GNU Emacs; see the file COPYING.  If not, write to
the Free Software Foundation, 675 Mass Ave, Cambridge, MA 02139, USA.  */

/* Allow config.h to undefine symbols found here.  */
#include <signal.h>

23
#include <config.h>
Jim Blandy's avatar
Jim Blandy committed
24 25 26 27 28 29 30
#include <stdio.h>
#undef NULL
#include "termchar.h"
#include "termopts.h"
#include "lisp.h"
#include "termhooks.h"
#include "macros.h"
Jim Blandy's avatar
Jim Blandy committed
31
#include "frame.h"
Jim Blandy's avatar
Jim Blandy committed
32 33 34 35
#include "window.h"
#include "commands.h"
#include "buffer.h"
#include "disptab.h"
36
#include "dispextern.h"
Jim Blandy's avatar
Jim Blandy committed
37
#include "keyboard.h"
Richard M. Stallman's avatar
Richard M. Stallman committed
38
#include "intervals.h"
39
#include "blockinput.h"
Jim Blandy's avatar
Jim Blandy committed
40 41 42
#include <setjmp.h>
#include <errno.h>

43 44 45 46
#ifdef MSDOS
#include "msdos.h"
#include <time.h>
#else /* not MSDOS */
Jim Blandy's avatar
Jim Blandy committed
47 48 49
#ifndef VMS
#include <sys/ioctl.h>
#endif
50
#endif /* not MSDOS */
Jim Blandy's avatar
Jim Blandy committed
51

Jim Blandy's avatar
Jim Blandy committed
52
#include "syssignal.h"
53
#include "systty.h"
Jim Blandy's avatar
Jim Blandy committed
54

55 56 57 58 59
/* This is to get the definitions of the XK_ symbols.  */
#ifdef HAVE_X_WINDOWS
#include "xterm.h"
#endif

60 61 62
/* Include systime.h after xterm.h to avoid double inclusion of time.h. */
#include "systime.h"

Jim Blandy's avatar
Jim Blandy committed
63 64
extern int errno;

65 66 67
/* Variables for blockinput.h: */

/* Non-zero if interrupt input is blocked right now.  */
68
int interrupt_input_blocked;
69 70 71

/* Nonzero means an input interrupt has arrived
   during the current critical section.  */
72
int interrupt_input_pending;
73 74


75 76
/* File descriptor to use for input.  */
extern int input_fd;
Jim Blandy's avatar
Jim Blandy committed
77

78
#ifdef HAVE_X_WINDOWS
Jim Blandy's avatar
Jim Blandy committed
79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97
/* Make all keyboard buffers much bigger when using X windows.  */
#define KBD_BUFFER_SIZE 4096
#else	/* No X-windows, character input */
#define KBD_BUFFER_SIZE 256
#endif	/* No X-windows */

/* Following definition copied from eval.c */

struct backtrace
  {
    struct backtrace *next;
    Lisp_Object *function;
    Lisp_Object *args;	/* Points to vector of args. */
    int nargs;		/* length of vector.  If nargs is UNEVALLED,
			   args points to slot holding list of
			   unevalled args */
    char evalargs;
  };

98
PERDISPLAY the_only_perdisplay;
99

Jim Blandy's avatar
Jim Blandy committed
100 101
/* Non-nil disable property on a command means
   do not execute it; call disabled-command-hook's value instead.  */
102
Lisp_Object Qdisabled, Qdisabled_command_hook;
Jim Blandy's avatar
Jim Blandy committed
103 104 105 106

#define NUM_RECENT_KEYS (100)
int recent_keys_index;	/* Index for storing next element into recent_keys */
int total_keys;		/* Total number of elements stored into recent_keys */
107
Lisp_Object recent_keys; /* A vector, holding the last 100 keystrokes */
Jim Blandy's avatar
Jim Blandy committed
108

109 110 111 112 113 114 115
/* Vector holding the key sequence that invoked the current command.
   It is reused for each command, and it may be longer than the current
   sequence; this_command_key_count indicates how many elements
   actually mean something.
   It's easier to staticpro a single Lisp_Object than an array.  */
Lisp_Object this_command_keys;
int this_command_key_count;
Jim Blandy's avatar
Jim Blandy committed
116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135

extern int minbuf_level;

extern struct backtrace *backtrace_list;

/* Nonzero means do menu prompting.  */
static int menu_prompting;

/* Character to see next line of menu prompt.  */
static Lisp_Object menu_prompt_more_char;

/* For longjmp to where kbd input is being done.  */
static jmp_buf getcjmp;

/* True while doing kbd input.  */
int waiting_for_input;

/* True while displaying for echoing.   Delays C-g throwing.  */
static int echoing;

136 137 138
/* Nonzero means disregard local maps for the menu bar.  */
static int inhibit_local_menu_bar_menus;

139
/* Nonzero means C-g should cause immediate error-signal.  */
Jim Blandy's avatar
Jim Blandy committed
140 141 142
int immediate_quit;

/* Character to recognize as the help char.  */
143
Lisp_Object Vhelp_char;
Jim Blandy's avatar
Jim Blandy committed
144 145 146 147

/* Form to execute when help char is typed.  */
Lisp_Object Vhelp_form;

148 149 150
/* Command to run when the help character follows a prefix key.  */
Lisp_Object Vprefix_help_command;

151 152
/* List of items that should move to the end of the menu bar.  */
Lisp_Object Vmenu_bar_final_items;
153

Jim Blandy's avatar
Jim Blandy committed
154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174
/* Character that causes a quit.  Normally C-g.

   If we are running on an ordinary terminal, this must be an ordinary
   ASCII char, since we want to make it our interrupt character.

   If we are not running on an ordinary terminal, it still needs to be
   an ordinary ASCII char.  This character needs to be recognized in
   the input interrupt handler.  At this point, the keystroke is
   represented as a struct input_event, while the desired quit
   character is specified as a lispy event.  The mapping from struct
   input_events to lispy events cannot run in an interrupt handler,
   and the reverse mapping is difficult for anything but ASCII
   keystrokes.

   FOR THESE ELABORATE AND UNSATISFYING REASONS, quit_char must be an
   ASCII character.  */
int quit_char;

extern Lisp_Object current_global_map;
extern int minibuf_level;

175 176 177
/* If non-nil, this is a map that overrides all other local maps.  */
Lisp_Object Voverriding_local_map;

178 179 180
/* If non-nil, Voverriding_local_map applies to the menu bar.  */
Lisp_Object Voverriding_local_map_menu_flag;

Jim Blandy's avatar
Jim Blandy committed
181 182 183 184 185 186 187 188 189
/* Current depth in recursive edits.  */
int command_loop_level;

/* Total number of times command_loop has read a key sequence.  */
int num_input_keys;

/* Last input character read as a command.  */
Lisp_Object last_command_char;

190 191 192 193
/* Last input character read as a command, not counting menus
   reached by the mouse.  */
Lisp_Object last_nonmenu_event;

Jim Blandy's avatar
Jim Blandy committed
194 195 196
/* Last input character read for any purpose.  */
Lisp_Object last_input_char;

Jim Blandy's avatar
Jim Blandy committed
197
/* If not Qnil, a list of objects to be read as subsequent command input.  */
198
Lisp_Object Vunread_command_events;
Jim Blandy's avatar
Jim Blandy committed
199

200 201 202
/* If not -1, an event to be read as subsequent command input.  */
int unread_command_char;

203 204
/* If not Qnil, this is a switch-frame event which we decided to put
   off until the end of a key sequence.  This should be read as the
Jim Blandy's avatar
Jim Blandy committed
205
   next command input, after any unread_command_events.
206 207 208 209 210

   read_key_sequence uses this to delay switch-frame events until the
   end of the key sequence; Fread_char uses it to put off switch-frame
   events until a non-ASCII event is acceptable as input.  */
Lisp_Object unread_switch_frame;
211

212 213 214
/* A mask of extra modifier bits to put into every keyboard char.  */
int extra_keyboard_modifiers;

Jim Blandy's avatar
Jim Blandy committed
215 216 217 218 219 220 221 222
/* Char to use as prefix when a meta character is typed in.
   This is bound on entry to minibuffer in case ESC is changed there.  */

Lisp_Object meta_prefix_char;

/* Last size recorded for a current buffer which is not a minibuffer.  */
static int last_non_minibuf_size;

223
/* Number of idle seconds before an auto-save and garbage collection.  */
Jim Blandy's avatar
Jim Blandy committed
224 225 226 227 228
static Lisp_Object Vauto_save_timeout;

/* Total number of times read_char has returned.  */
int num_input_chars;

229 230 231
/* Total number of times read_char has returned, outside of macros.  */
int num_nonmacro_input_chars;

Jim Blandy's avatar
Jim Blandy committed
232 233 234 235 236
/* Auto-save automatically when this many characters have been typed
   since the last time.  */

static int auto_save_interval;

237
/* Value of num_nonmacro_input_chars as of last auto save.  */
Jim Blandy's avatar
Jim Blandy committed
238 239 240 241 242 243 244 245 246 247 248 249 250

int last_auto_save;

/* Last command executed by the editor command loop, not counting
   commands that set the prefix argument.  */

Lisp_Object last_command;

/* The command being executed by the command loop.
   Commands may set this, and the value set will be copied into last_command
   instead of the actual command.  */
Lisp_Object this_command;

251 252 253
/* The value of point when the last command was executed.  */
int last_point_position;

254 255 256
/* The buffer that was current when the last command was started.  */
Lisp_Object last_point_position_buffer;

257
#ifdef MULTI_FRAME
258
/* The frame in which the last input event occurred, or Qmacro if the
259 260 261 262 263
   last event came from a macro.  We use this to determine when to
   generate switch-frame events.  This may be cleared by functions
   like Fselect_frame, to make sure that a switch-frame event is
   generated by the next character.  */
Lisp_Object internal_last_event_frame;
264
#endif
265 266 267 268

/* A user-visible version of the above, intended to allow users to
   figure out where the last event came from, if the event doesn't
   carry that information itself (i.e. if it was a character).  */
Jim Blandy's avatar
Jim Blandy committed
269
Lisp_Object Vlast_event_frame;
Jim Blandy's avatar
Jim Blandy committed
270

Jim Blandy's avatar
Jim Blandy committed
271 272
/* The timestamp of the last input event we received from the X server.
   X Windows wants this for selection ownership.  */
Jim Blandy's avatar
Jim Blandy committed
273 274 275 276 277
unsigned long last_event_timestamp;

Lisp_Object Qself_insert_command;
Lisp_Object Qforward_char;
Lisp_Object Qbackward_char;
278
Lisp_Object Qundefined;
Jim Blandy's avatar
Jim Blandy committed
279 280 281 282 283 284 285 286 287 288 289 290 291 292

/* read_key_sequence stores here the command definition of the
   key sequence that it reads.  */
Lisp_Object read_key_sequence_cmd;

/* Form to evaluate (if non-nil) when Emacs is started.  */
Lisp_Object Vtop_level;

/* User-supplied string to translate input characters through.  */
Lisp_Object Vkeyboard_translate_table;

/* Keymap mapping ASCII function key sequences onto their preferred forms.  */
extern Lisp_Object Vfunction_key_map;

293 294 295
/* Keymap mapping ASCII function key sequences onto their preferred forms.  */
Lisp_Object Vkey_translation_map;

296 297 298
/* Non-nil means deactivate the mark at end of this command.  */
Lisp_Object Vdeactivate_mark;

299 300 301 302 303
/* Menu bar specified in Lucid Emacs fashion.  */

Lisp_Object Vlucid_menu_bar_dirty_flag;
Lisp_Object Qrecompute_lucid_menubar, Qactivate_menubar_hook;

304 305 306
/* Hooks to run before and after each command.  */
Lisp_Object Qpre_command_hook, Qpost_command_hook;
Lisp_Object Vpre_command_hook, Vpost_command_hook;
307
Lisp_Object Qcommand_hook_internal, Vcommand_hook_internal;
308

309 310 311 312 313 314
/* List of deferred actions to be performed at a later time.
   The precise format isn't relevant here; we just check whether it is nil.  */
Lisp_Object Vdeferred_action_list;

/* Function to call to handle deferred actions, when there are any.  */
Lisp_Object Vdeferred_action_function;
315
Lisp_Object Qdeferred_action_function;
316

Jim Blandy's avatar
Jim Blandy committed
317 318 319 320 321 322
/* File in which we write all commands we read.  */
FILE *dribble;

/* Nonzero if input is available.  */
int input_pending;

323 324 325
/* 1 if should obey 0200 bit in input chars as "Meta", 2 if should
   keep 0200 bit in input chars.  0 to ignore the 0200 bit.  */

Jim Blandy's avatar
Jim Blandy committed
326 327 328 329
int meta_key;

extern char *pending_malloc_warning;

330
#ifdef HAVE_MOUSE
331 332 333 334
/* If this flag is a frame, we check mouse_moved to see when the
   mouse moves, and motion events will appear in the input stream.
   Otherwise, mouse motion is ignored.  */
static Lisp_Object do_mouse_tracking;
Jim Blandy's avatar
Jim Blandy committed
335 336 337 338 339 340 341 342

/* The window system handling code should set this if the mouse has
   moved since the last call to the mouse_position_hook.  Calling that
   hook should clear this.  Code assumes that if this is set, it can
   call mouse_position_hook to get the promised position, so don't set
   it unless you're prepared to substantiate the claim!  */
int mouse_moved;

343
#define MOUSE_ACTIVITY_AVAILABLE (FRAMEP (do_mouse_tracking) && mouse_moved)
344
#else /* Not HAVE_MOUSE.  */
345
#define MOUSE_ACTIVITY_AVAILABLE 0
346
#endif /* HAVE_MOUSE.  */
Jim Blandy's avatar
Jim Blandy committed
347 348 349

/* Symbols to head events.  */
Lisp_Object Qmouse_movement;
350
Lisp_Object Qscroll_bar_movement;
351
Lisp_Object Qswitch_frame;
352
Lisp_Object Qdelete_frame;
353 354
Lisp_Object Qiconify_frame;
Lisp_Object Qmake_frame_visible;
355

Jim Blandy's avatar
Jim Blandy committed
356 357 358 359 360 361 362
/* Symbols to denote kinds of events.  */
Lisp_Object Qfunction_key;
Lisp_Object Qmouse_click;
/* Lisp_Object Qmouse_movement; - also an event header */

/* Properties of event headers.  */
Lisp_Object Qevent_kind;
363
Lisp_Object Qevent_symbol_elements;
Jim Blandy's avatar
Jim Blandy committed
364

365 366
Lisp_Object Qmenu_enable;

367 368 369 370 371 372 373 374 375 376 377 378 379
/* An event header symbol HEAD may have a property named
   Qevent_symbol_element_mask, which is of the form (BASE MODIFIERS);
   BASE is the base, unmodified version of HEAD, and MODIFIERS is the
   mask of modifiers applied to it.  If present, this is used to help
   speed up parse_modifiers.  */
Lisp_Object Qevent_symbol_element_mask;

/* An unmodified event header BASE may have a property named
   Qmodifier_cache, which is an alist mapping modifier masks onto
   modified versions of BASE.  If present, this helps speed up
   apply_modifiers.  */
Lisp_Object Qmodifier_cache;

380
/* Symbols to use for parts of windows.  */
Jim Blandy's avatar
Jim Blandy committed
381
Lisp_Object Qmode_line;
Jim Blandy's avatar
Jim Blandy committed
382
Lisp_Object Qvertical_line;
383
Lisp_Object Qvertical_scroll_bar;
384 385 386
Lisp_Object Qmenu_bar;

extern Lisp_Object Qmenu_enable;
Jim Blandy's avatar
Jim Blandy committed
387

388 389
Lisp_Object recursive_edit_unwind (), command_loop ();
Lisp_Object Fthis_command_keys ();
390
Lisp_Object Qextended_command_history;
Jim Blandy's avatar
Jim Blandy committed
391

392 393
Lisp_Object Qpolling_period;

Jim Blandy's avatar
Jim Blandy committed
394 395 396
/* Address (if not 0) of EMACS_TIME to zero out if a SIGIO interrupt
   happens.  */
EMACS_TIME *input_available_clear_time;
Jim Blandy's avatar
Jim Blandy committed
397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420

/* Nonzero means use SIGIO interrupts; zero means use CBREAK mode.
   Default is 1 if INTERRUPT_INPUT is defined.  */
int interrupt_input;

/* Nonzero while interrupts are temporarily deferred during redisplay.  */
int interrupts_deferred;

/* nonzero means use ^S/^Q for flow control.  */
int flow_control;

/* Allow m- file to inhibit use of FIONREAD.  */
#ifdef BROKEN_FIONREAD
#undef FIONREAD
#endif

/* We are unable to use interrupts if FIONREAD is not available,
   so flush SIGIO so we won't try.  */
#ifndef FIONREAD
#ifdef SIGIO
#undef SIGIO
#endif
#endif

421 422
/* If we support X Windows, turn on the code to poll periodically
   to detect C-g.  It isn't actually used when doing interrupt input.  */
Jim Blandy's avatar
Jim Blandy committed
423 424 425 426 427 428 429 430 431 432 433
#ifdef HAVE_X_WINDOWS
#define POLL_FOR_INPUT
#endif

/* Global variable declarations.  */

/* Function for init_keyboard to call with no args (if nonzero).  */
void (*keyboard_init_hook) ();

static int read_avail_input ();
static void get_input_pending ();
434
static int readable_events ();
435 436
static Lisp_Object read_char_x_menu_prompt ();
static Lisp_Object read_char_minibuf_menu_prompt ();
437 438 439 440
static Lisp_Object make_lispy_event ();
static Lisp_Object make_lispy_movement ();
static Lisp_Object modify_event_symbol ();
static Lisp_Object make_lispy_switch_frame ();
Jim Blandy's avatar
Jim Blandy committed
441 442 443 444

/* > 0 if we are to echo keystrokes.  */
static int echo_keystrokes;

445 446 447 448
/* Nonzero means don't try to suspend even if the operating system seems
   to support it.  */
static int cannot_suspend;

Jim Blandy's avatar
Jim Blandy committed
449 450 451 452 453 454 455 456 457 458
#define	min(a,b)	((a)<(b)?(a):(b))
#define	max(a,b)	((a)>(b)?(a):(b))

/* Install the string STR as the beginning of the string of echoing,
   so that it serves as a prompt for the next character.
   Also start echoing.  */

echo_prompt (str)
     char *str;
{
459
  PERDISPLAY *perd = get_perdisplay (selected_frame);
Jim Blandy's avatar
Jim Blandy committed
460
  int len = strlen (str);
461

462 463 464 465 466
  if (len > ECHOBUFSIZE - 4)
    len = ECHOBUFSIZE - 4;
  bcopy (str, perd->echobuf, len);
  perd->echoptr = perd->echobuf + len;
  *perd->echoptr = '\0';
Jim Blandy's avatar
Jim Blandy committed
467

468
  perd->echo_after_prompt = len;
469

Jim Blandy's avatar
Jim Blandy committed
470 471 472 473 474 475 476 477 478 479 480
  echo ();
}

/* Add C to the echo string, if echoing is going on.  
   C can be a character, which is printed prettily ("M-C-x" and all that
   jazz), or a symbol, whose name is printed.  */

echo_char (c)
     Lisp_Object c;
{
  extern char *push_key_description ();
481
  PERDISPLAY *perd = get_perdisplay (selected_frame);
Jim Blandy's avatar
Jim Blandy committed
482

483
  if (perd->immediate_echo)
Jim Blandy's avatar
Jim Blandy committed
484
    {
485
      char *ptr = perd->echoptr;
Jim Blandy's avatar
Jim Blandy committed
486
      
487
      if (ptr != perd->echobuf)
Jim Blandy's avatar
Jim Blandy committed
488 489 490
	*ptr++ = ' ';

      /* If someone has passed us a composite event, use its head symbol.  */
491
      c = EVENT_HEAD (c);
Jim Blandy's avatar
Jim Blandy committed
492

493
      if (INTEGERP (c))
Jim Blandy's avatar
Jim Blandy committed
494
	{
495
	  if (ptr - perd->echobuf > ECHOBUFSIZE - 6)
Jim Blandy's avatar
Jim Blandy committed
496 497
	    return;

498
	  ptr = push_key_description (XINT (c), ptr);
Jim Blandy's avatar
Jim Blandy committed
499
	}
500
      else if (SYMBOLP (c))
Jim Blandy's avatar
Jim Blandy committed
501 502
	{
	  struct Lisp_String *name = XSYMBOL (c)->name;
503
	  if (((ptr - perd->echobuf) + name->size + 4) > ECHOBUFSIZE)
Jim Blandy's avatar
Jim Blandy committed
504 505 506 507 508
	    return;
	  bcopy (name->data, ptr, name->size);
	  ptr += name->size;
	}

509
      if (perd->echoptr == perd->echobuf && EQ (c, Vhelp_char))
Jim Blandy's avatar
Jim Blandy committed
510 511 512 513 514 515
	{
	  strcpy (ptr, " (Type ? for further options)");
	  ptr += strlen (ptr);
	}

      *ptr = 0;
516
      perd->echoptr = ptr;
Jim Blandy's avatar
Jim Blandy committed
517 518 519 520 521 522 523 524 525 526

      echo ();
    }
}

/* Temporarily add a dash to the end of the echo string if it's not
   empty, so that it serves as a mini-prompt for the very next character.  */

echo_dash ()
{
527 528
  PERDISPLAY *perd = get_perdisplay (selected_frame);
  if (!perd->immediate_echo && perd->echoptr == perd->echobuf)
Jim Blandy's avatar
Jim Blandy committed
529
    return;
530
  /* Do nothing if we just printed a prompt.  */
531
  if (perd->echo_after_prompt == perd->echoptr - perd->echobuf)
532
    return;
533
  /* Do nothing if not echoing at all.  */
534
  if (perd->echoptr == 0)
535
    return;
Jim Blandy's avatar
Jim Blandy committed
536 537 538

  /* Put a dash at the end of the buffer temporarily,
     but make it go away when the next character is added.  */
539 540
  perd->echoptr[0] = '-';
  perd->echoptr[1] = 0;
Jim Blandy's avatar
Jim Blandy committed
541 542 543 544 545 546 547 548 549

  echo ();
}

/* Display the current echo string, and begin echoing if not already
   doing so.  */

echo ()
{
550 551
  PERDISPLAY *perd = get_perdisplay (selected_frame);
  if (!perd->immediate_echo)
Jim Blandy's avatar
Jim Blandy committed
552 553
    {
      int i;
554
      perd->immediate_echo = 1;
Jim Blandy's avatar
Jim Blandy committed
555 556

      for (i = 0; i < this_command_key_count; i++)
557 558 559 560 561 562 563
	{
	  Lisp_Object c;
	  c = XVECTOR (this_command_keys)->contents[i];
	  if (! (EVENT_HAS_PARAMETERS (c)
		 && EQ (EVENT_HEAD_KIND (EVENT_HEAD (c)), Qmouse_movement)))
	    echo_char (c);
	}
Jim Blandy's avatar
Jim Blandy committed
564 565 566 567
      echo_dash ();
    }

  echoing = 1;
568
  message2_nolog (perd->echobuf, strlen (perd->echobuf));
Jim Blandy's avatar
Jim Blandy committed
569 570 571 572 573 574 575 576 577 578
  echoing = 0;

  if (waiting_for_input && !NILP (Vquit_flag))
    quit_throw_to_read_char ();
}

/* Turn off echoing, for the start of a new command.  */

cancel_echoing ()
{
579 580 581 582
  PERDISPLAY *perd = get_perdisplay (selected_frame);
  perd->immediate_echo = 0;
  perd->echoptr = perd->echobuf;
  perd->echo_after_prompt = -1;
Jim Blandy's avatar
Jim Blandy committed
583 584 585 586 587 588 589
}

/* Return the length of the current echo string.  */

static int
echo_length ()
{
590 591
  PERDISPLAY *perd = get_perdisplay (selected_frame);
  return perd->echoptr - perd->echobuf;
Jim Blandy's avatar
Jim Blandy committed
592 593 594 595
}

/* Truncate the current echo message to its first LEN chars.
   This and echo_char get used by read_key_sequence when the user
Jim Blandy's avatar
Jim Blandy committed
596
   switches frames while entering a key sequence.  */
Jim Blandy's avatar
Jim Blandy committed
597 598 599 600 601

static void
echo_truncate (len)
     int len;
{
602 603 604
  PERDISPLAY *perd = get_perdisplay (selected_frame);
  perd->echobuf[len] = '\0';
  perd->echoptr = perd->echobuf + len;
605
  truncate_echo_area (len);
Jim Blandy's avatar
Jim Blandy committed
606 607 608 609 610 611 612 613
}


/* Functions for manipulating this_command_keys.  */
static void
add_command_key (key)
     Lisp_Object key;
{
614 615 616
  int size = XVECTOR (this_command_keys)->size;

  if (this_command_key_count >= size)
Jim Blandy's avatar
Jim Blandy committed
617
    {
618
      Lisp_Object new_keys;
619

620
      new_keys = Fmake_vector (make_number (size * 2), Qnil);
621 622
      bcopy (XVECTOR (this_command_keys)->contents,
	     XVECTOR (new_keys)->contents,
623
	     size * sizeof (Lisp_Object));
624 625

      this_command_keys = new_keys;
Jim Blandy's avatar
Jim Blandy committed
626
    }
627 628

  XVECTOR (this_command_keys)->contents[this_command_key_count++] = key;
Jim Blandy's avatar
Jim Blandy committed
629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646
}

Lisp_Object
recursive_edit_1 ()
{
  int count = specpdl_ptr - specpdl;
  Lisp_Object val;

  if (command_loop_level > 0)
    {
      specbind (Qstandard_output, Qt);
      specbind (Qstandard_input, Qt);
    }

  val = command_loop ();
  if (EQ (val, Qt))
    Fsignal (Qquit, Qnil);

647
  return unbind_to (count, Qnil);
Jim Blandy's avatar
Jim Blandy committed
648 649 650
}

/* When an auto-save happens, record the "time", and don't do again soon.  */
651

Jim Blandy's avatar
Jim Blandy committed
652 653
record_auto_save ()
{
654
  last_auto_save = num_nonmacro_input_chars;
Jim Blandy's avatar
Jim Blandy committed
655
}
656 657 658 659 660 661

/* Make an auto save happen as soon as possible at command level.  */

force_auto_save_soon ()
{
  last_auto_save = - auto_save_interval - 1;
662 663

  record_asynch_buffer_change ();
664
}
Jim Blandy's avatar
Jim Blandy committed
665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703

DEFUN ("recursive-edit", Frecursive_edit, Srecursive_edit, 0, 0, "",
  "Invoke the editor command loop recursively.\n\
To get out of the recursive edit, a command can do `(throw 'exit nil)';\n\
that tells this function to return.\n\
Alternately, `(throw 'exit t)' makes this function signal an error.\n\
This function is called by the editor initialization to begin editing.")
  ()
{
  int count = specpdl_ptr - specpdl;
  Lisp_Object val;

  command_loop_level++;
  update_mode_lines = 1;

  record_unwind_protect (recursive_edit_unwind,
			 (command_loop_level
			  && current_buffer != XBUFFER (XWINDOW (selected_window)->buffer))
			 ? Fcurrent_buffer ()
			 : Qnil);
  recursive_edit_1 ();
  return unbind_to (count, Qnil);
}

Lisp_Object
recursive_edit_unwind (buffer)
     Lisp_Object buffer;
{
  if (!NILP (buffer))
    Fset_buffer (buffer);

  command_loop_level--;
  update_mode_lines = 1;
  return Qnil;
}

Lisp_Object
cmd_error (data)
     Lisp_Object data;
704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719
{
  Vstandard_output = Qt;
  Vstandard_input = Qt;
  Vexecuting_macro = Qnil;
  cmd_error_internal (data, 0);

  Vquit_flag = Qnil;

  Vinhibit_quit = Qnil;

  return make_number (0);
}

cmd_error_internal (data, context)
     Lisp_Object data;
     char *context;
Jim Blandy's avatar
Jim Blandy committed
720 721 722 723 724 725 726 727 728 729
{
  Lisp_Object errmsg, tail, errname, file_error;
  Lisp_Object stream;
  struct gcpro gcpro1;
  int i;

  Vquit_flag = Qnil;
  Vinhibit_quit = Qt;
  echo_area_glyphs = 0;

Jim Blandy's avatar
Jim Blandy committed
730
  /* If the window system or terminal frame hasn't been initialized
Jim Blandy's avatar
Jim Blandy committed
731 732
     yet, or we're not interactive, it's best to dump this message out
     to stderr and exit.  */
Jim Blandy's avatar
Jim Blandy committed
733
  if (! FRAME_MESSAGE_BUF (selected_frame)
Jim Blandy's avatar
Jim Blandy committed
734 735 736 737 738 739 740 741 742
      || noninteractive)
    stream = Qexternal_debugging_output;
  else
    {
      Fdiscard_input ();
      bitch_at_user ();
      stream = Qt;
    }

743 744 745
  if (context != 0)
    write_string_1 (context, -1, stream);

Jim Blandy's avatar
Jim Blandy committed
746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774
  errname = Fcar (data);

  if (EQ (errname, Qerror))
    {
      data = Fcdr (data);
      if (!CONSP (data)) data = Qnil;
      errmsg = Fcar (data);
      file_error = Qnil;
    }
  else
    {
      errmsg = Fget (errname, Qerror_message);
      file_error = Fmemq (Qfile_error,
			  Fget (errname, Qerror_conditions));
    }

  /* Print an error message including the data items.
     This is done by printing it into a scratch buffer
     and then making a copy of the text in the buffer. */

  if (!CONSP (data)) data = Qnil;
  tail = Fcdr (data);
  GCPRO1 (tail);

  /* For file-error, make error message by concatenating
     all the data items.  They are all strings.  */
  if (!NILP (file_error) && !NILP (tail))
    errmsg = XCONS (tail)->car, tail = XCONS (tail)->cdr;

775
  if (STRINGP (errmsg))
Jim Blandy's avatar
Jim Blandy committed
776 777 778 779 780 781 782 783 784 785 786 787 788 789
    Fprinc (errmsg, stream);
  else
    write_string_1 ("peculiar error", -1, stream);

  for (i = 0; CONSP (tail); tail = Fcdr (tail), i++)
    {
      write_string_1 (i ? ", " : ": ", 2, stream);
      if (!NILP (file_error))
	Fprinc (Fcar (tail), stream);
      else
	Fprin1 (Fcar (tail), stream);
    }
  UNGCPRO;

Jim Blandy's avatar
Jim Blandy committed
790
  /* If the window system or terminal frame hasn't been initialized
Jim Blandy's avatar
Jim Blandy committed
791
     yet, or we're in -batch mode, this error should cause Emacs to exit.  */
Jim Blandy's avatar
Jim Blandy committed
792
  if (! FRAME_MESSAGE_BUF (selected_frame)
Jim Blandy's avatar
Jim Blandy committed
793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895
      || noninteractive)
    {
      Fterpri (stream);
      Fkill_emacs (make_number (-1));
    }
}

Lisp_Object command_loop_1 ();
Lisp_Object command_loop_2 ();
Lisp_Object top_level_1 ();

/* Entry to editor-command-loop.
   This level has the catches for exiting/returning to editor command loop.
   It returns nil to exit recursive edit, t to abort it.  */

Lisp_Object
command_loop ()
{
  if (command_loop_level > 0 || minibuf_level > 0)
    {
      return internal_catch (Qexit, command_loop_2, Qnil);
    }
  else
    while (1)
      {
	internal_catch (Qtop_level, top_level_1, Qnil);
	internal_catch (Qtop_level, command_loop_2, Qnil);
	
	/* End of file in -batch run causes exit here.  */
	if (noninteractive)
	  Fkill_emacs (Qt);
      }
}

/* Here we catch errors in execution of commands within the
   editing loop, and reenter the editing loop.
   When there is an error, cmd_error runs and returns a non-nil
   value to us.  A value of nil means that cmd_loop_1 itself
   returned due to end of file (or end of kbd macro).  */

Lisp_Object
command_loop_2 ()
{
  register Lisp_Object val;

  do
    val = internal_condition_case (command_loop_1, Qerror, cmd_error);
  while (!NILP (val));

  return Qnil;
}

Lisp_Object
top_level_2 ()
{
  return Feval (Vtop_level);
}

Lisp_Object
top_level_1 ()
{
  /* On entry to the outer level, run the startup file */
  if (!NILP (Vtop_level))
    internal_condition_case (top_level_2, Qerror, cmd_error);
  else if (!NILP (Vpurify_flag))
    message ("Bare impure Emacs (standard Lisp code not loaded)");
  else
    message ("Bare Emacs (standard Lisp code not loaded)");
  return Qnil;
}

DEFUN ("top-level", Ftop_level, Stop_level, 0, 0, "",
  "Exit all recursive editing levels.")
  ()
{
  Fthrow (Qtop_level, Qnil);
}

DEFUN ("exit-recursive-edit", Fexit_recursive_edit, Sexit_recursive_edit, 0, 0, "",
  "Exit from the innermost recursive edit or minibuffer.")
  ()
{
  if (command_loop_level > 0 || minibuf_level > 0)
    Fthrow (Qexit, Qnil);

  error ("No recursive edit is in progress");
}

DEFUN ("abort-recursive-edit", Fabort_recursive_edit, Sabort_recursive_edit, 0, 0, "",
  "Abort the command that requested this recursive edit or minibuffer input.")
  ()
{
  if (command_loop_level > 0 || minibuf_level > 0)
    Fthrow (Qexit, Qt);

  error ("No recursive edit is in progress");
}

/* This is the actual command reading loop,
   sans error-handling encapsulation.  */

Lisp_Object Fcommand_execute ();
static int read_key_sequence ();
896
static void safe_run_hooks ();
Jim Blandy's avatar
Jim Blandy committed
897 898 899 900

Lisp_Object
command_loop_1 ()
{
901
  Lisp_Object cmd, tem;
Jim Blandy's avatar
Jim Blandy committed
902 903 904 905 906 907
  int lose;
  int nonundocount;
  Lisp_Object keybuf[30];
  int i;
  int no_redisplay;
  int no_direct;
908 909
  int prev_modiff;
  struct buffer *prev_buffer;
Jim Blandy's avatar
Jim Blandy committed
910 911

  Vprefix_arg = Qnil;
912
  Vdeactivate_mark = Qnil;
Jim Blandy's avatar
Jim Blandy committed
913 914 915 916 917 918 919
  waiting_for_input = 0;
  cancel_echoing ();

  nonundocount = 0;
  no_redisplay = 0;
  this_command_key_count = 0;

920 921
  /* Make sure this hook runs after commands that get errors and
     throw to top level.  */
922 923 924 925
  /* Note that the value cell will never directly contain nil
     if the symbol is a local variable.  */
  if (!NILP (XSYMBOL (Qpost_command_hook)->value) && !NILP (Vrun_hooks))
    safe_run_hooks (Qpost_command_hook);
926

927 928 929
  if (!NILP (Vdeferred_action_list))
    call0 (Vdeferred_action_function);

930 931 932
  /* Do this after running Vpost_command_hook, for consistency.  */
  last_command = this_command;

Jim Blandy's avatar
Jim Blandy committed
933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951
  while (1)
    {
      /* Install chars successfully executed in kbd macro.  */

      if (defining_kbd_macro && NILP (Vprefix_arg))
	finalize_kbd_macro_chars ();

      /* Make sure the current window's buffer is selected.  */
      if (XBUFFER (XWINDOW (selected_window)->buffer) != current_buffer)
	set_buffer_internal (XBUFFER (XWINDOW (selected_window)->buffer));

      /* Display any malloc warning that just came out.  Use while because
	 displaying one warning can cause another.  */

      while (pending_malloc_warning)
	display_malloc_warning ();

      no_direct = 0;

952 953
      Vdeactivate_mark = Qnil;

Jim Blandy's avatar
Jim Blandy committed
954
      /* If minibuffer on and echo area in use,
955
	 wait 2 sec and redraw minibuffer.  */
Jim Blandy's avatar
Jim Blandy committed
956 957 958

      if (minibuf_level && echo_area_glyphs)
	{
959 960 961 962
	  /* Bind inhibit-quit to t so that C-g gets read in
	     rather than quitting back to the minibuffer.  */
	  int count = specpdl_ptr - specpdl;
	  specbind (Qinhibit_quit, Qt);
Jim Blandy's avatar
Jim Blandy committed
963
	  Fsit_for (make_number (2), Qnil, Qnil);
964
	  unbind_to (count, Qnil);
965

Jim Blandy's avatar
Jim Blandy committed
966 967 968 969 970
	  echo_area_glyphs = 0;
	  no_direct = 1;
	  if (!NILP (Vquit_flag))
	    {
	      Vquit_flag = Qnil;
971
	      Vunread_command_events = Fcons (make_number (quit_char), Qnil);
Jim Blandy's avatar
Jim Blandy committed
972 973 974 975 976 977 978 979
	    }
	}

#ifdef C_ALLOCA
	  alloca (0);		/* Cause a garbage collection now */
				/* Since we can free the most stuff here.  */
#endif /* C_ALLOCA */

980
#if 0
Jim Blandy's avatar
Jim Blandy committed
981
#ifdef MULTI_FRAME
982 983 984 985
      /* Select the frame that the last event came from.  Usually,
	 switch-frame events will take care of this, but if some lisp
	 code swallows a switch-frame event, we'll fix things up here.
	 Is this a good idea?  */
986
      if (FRAMEP (internal_last_event_frame)
987 988
	  && XFRAME (internal_last_event_frame) != selected_frame)
	Fselect_frame (internal_last_event_frame, Qnil);
989
#endif
Jim Blandy's avatar
Jim Blandy committed
990
#endif
991 992
      /* If it has changed current-menubar from previous value,
	 really recompute the menubar from the value.  */
993 994
      if (! NILP (Vlucid_menu_bar_dirty_flag)
	  && !NILP (Ffboundp (Qrecompute_lucid_menubar)))
995 996
	call0 (Qrecompute_lucid_menubar);

997
      /* Read next key sequence; i gets its length.  */
998
      i = read_key_sequence (keybuf, (sizeof keybuf / sizeof (keybuf[0])), Qnil, 0);
999 1000 1001

      ++num_input_keys;

Jim Blandy's avatar
Jim Blandy committed
1002 1003 1004 1005 1006
      /* Now we have read a key sequence of length I,
	 or else I is 0 and we found end of file.  */

      if (i == 0)		/* End of file -- happens only in */
	return Qnil;		/* a kbd macro, at the end.  */
1007 1008 1009 1010 1011 1012 1013 1014
      /* -1 means read_key_sequence got a menu that was rejected.
	 Just loop around and read another command.  */
      if (i == -1)
	{
	  cancel_echoing ();
	  this_command_key_count = 0;
	  continue;
	}
Jim Blandy's avatar
Jim Blandy committed
1015 1016 1017

      last_command_char = keybuf[i - 1];

1018 1019 1020 1021 1022
      /* If the previous command tried to force a specific window-start,
	 forget about that, in case this command moves point far away
	 from that position.  */
      XWINDOW (selected_window)->force_start = Qnil;

Jim Blandy's avatar
Jim Blandy committed
1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034
      cmd = read_key_sequence_cmd;
      if (!NILP (Vexecuting_macro))
	{
	  if (!NILP (Vquit_flag))
	    {
	      Vexecuting_macro = Qt;
	      QUIT;		/* Make some noise. */
				/* Will return since macro now empty. */
	    }
	}

      /* Do redisplay processing after this command except in special
1035 1036 1037 1038
	 cases identified below that set no_redisplay to 1.
	 (actually, there's currently no way to prevent the redisplay,
	 and no_redisplay is ignored.
	 Perhaps someday we will really implement it.  */
Jim Blandy's avatar
Jim Blandy committed
1039 1040
      no_redisplay = 0;

1041 1042
      prev_buffer = current_buffer;
      prev_modiff = MODIFF;
1043
      last_point_position = PT;
1044
      XSETBUFFER (last_point_position_buffer, prev_buffer);
1045

Jim Blandy's avatar
Jim Blandy committed
1046 1047
      /* Execute the command.  */

1048
      this_command = cmd;
1049 1050 1051 1052
      /* Note that the value cell will never directly contain nil
	 if the symbol is a local variable.  */
      if (!NILP (XSYMBOL (Qpre_command_hook)->value) && !NILP (Vrun_hooks))
	safe_run_hooks (Qpre_command_hook);
1053

1054
      if (NILP (this_command))
Jim Blandy's avatar
Jim Blandy committed
1055 1056 1057 1058 1059 1060
	{
	  /* nil means key is undefined.  */
	  bitch_at_user ();
	  defining_kbd_macro = 0;
	  update_mode_lines = 1;
	  Vprefix_arg = Qnil;
1061

Jim Blandy's avatar
Jim Blandy committed
1062 1063 1064 1065 1066 1067 1068
	}
      else
	{
	  if (NILP (Vprefix_arg) && ! no_direct)
	    {
	      /* Recognize some common commands in common situations and
		 do them directly.  */
Karl Heuer's avatar
Karl Heuer committed
1069
	      if (EQ (this_command, Qforward_char) && PT < ZV)
Jim Blandy's avatar
Jim Blandy committed
1070 1071 1072
		{
                  struct Lisp_Vector *dp
		    = window_display_table (XWINDOW (selected_window));
Karl Heuer's avatar
Karl Heuer committed
1073 1074
		  lose = FETCH_CHAR (PT);
		  SET_PT (PT + 1);
1075
		  if ((dp
1076
		       ? (VECTORP (DISP_CHAR_VECTOR (dp, lose))
1077 1078 1079
			  ? XVECTOR (DISP_CHAR_VECTOR (dp, lose))->size == 1
                          : (NILP (DISP_CHAR_VECTOR (dp, lose))
                             && (lose >= 0x20 && lose < 0x7f)))
1080
		       : (lose >= 0x20 && lose < 0x7f))
Jim Blandy's avatar
Jim Blandy committed
1081 1082 1083
		      && (XFASTINT (XWINDOW (selected_window)->last_modified)
			  >= MODIFF)
		      && (XFASTINT (XWINDOW (selected_window)->last_point)
Karl Heuer's avatar
Karl Heuer committed
1084
			  == PT - 1)
Jim Blandy's avatar
Jim Blandy committed
1085 1086 1087 1088 1089 1090 1091
		      && !windows_or_buffers_changed
		      && EQ (current_buffer->selective_display, Qnil)
		      && !detect_input_pending ()
		      && NILP (Vexecuting_macro))
		    no_redisplay = direct_output_forward_char (1);
		  goto directly_done;
		}
Karl Heuer's avatar
Karl Heuer committed
1092
	      else if (EQ (this_command, Qbackward_char) && PT > BEGV)
Jim Blandy's avatar
Jim Blandy committed
1093 1094 1095
		{
                  struct Lisp_Vector *dp
		    = window_display_table (XWINDOW (selected_window));
Karl Heuer's avatar
Karl Heuer committed
1096 1097
		  SET_PT (PT - 1);
		  lose = FETCH_CHAR (PT);
1098
		  if ((dp
1099
		       ? (VECTORP (DISP_CHAR_VECTOR (dp, lose))
1100 1101 1102
			  ? XVECTOR (DISP_CHAR_VECTOR (dp, lose))->size == 1
                          : (NILP (DISP_CHAR_VECTOR (dp, lose))
                             && (lose >= 0x20 && lose < 0x7f)))
1103
		       : (lose >= 0x20 && lose < 0x7f))
Jim Blandy's avatar
Jim Blandy committed
1104 1105 1106
		      && (XFASTINT (XWINDOW (selected_window)->last_modified)
			  >= MODIFF)
		      && (XFASTINT (XWINDOW (selected_window)->last_point)
Karl Heuer's avatar
Karl Heuer committed
1107
			  == PT + 1)
Jim Blandy's avatar
Jim Blandy committed
1108 1109 1110 1111 1112 1113 1114
		      && !windows_or_buffers_changed
		      && EQ (current_buffer->selective_display, Qnil)
		      && !detect_input_pending ()
		      && NILP (Vexecuting_macro))
		    no_redisplay = direct_output_forward_char (-1);
		  goto directly_done;
		}
1115
	      else if (EQ (this_command, Qself_insert_command)
Jim Blandy's avatar
Jim Blandy committed
1116
		       /* Try this optimization only on ascii keystrokes.  */
1117
		       && INTEGERP (last_command_char))
Jim Blandy's avatar
Jim Blandy committed
1118 1119
		{
		  unsigned char c = XINT (last_command_char);
1120
		  int value;
Jim Blandy's avatar
Jim Blandy committed
1121

1122 1123
		  if (NILP (Vexecuting_macro)
		      && !EQ (minibuf_window, selected_window))
Jim Blandy's avatar
Jim Blandy committed
1124 1125 1126 1127 1128 1129 1130 1131
		    {
		      if (!nonundocount || nonundocount >= 20)
			{
			  Fundo_boundary ();
			  nonundocount = 0;
			}
		      nonundocount++;
		    }
1132 1133 1134 1135
		  lose = ((XFASTINT (XWINDOW (selected_window)->last_modified)
			   < MODIFF)
			  || (XFASTINT (XWINDOW (selected_window)->last_point)
			      != PT)
1136
			  || MODIFF <= SAVE_MODIFF
1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148
			  || windows_or_buffers_changed
			  || !EQ (current_buffer->selective_display, Qnil)
			  || detect_input_pending ()
			  || !NILP (Vexecuting_macro));
		  value = internal_self_insert (c, 0);
		  if (value)
		    lose = 1;
		  if (value == 2)
		    nonundocount = 0;

		  if (!lose
		      && (PT == ZV || FETCH_CHAR (PT) == '\n'))
Jim Blandy's avatar
Jim Blandy committed
1149 1150 1151
		    {
		      struct Lisp_Vector *dp
			= window_display_table (XWINDOW (selected_window));
1152
		      int lose = c;
Jim Blandy's avatar
Jim Blandy committed
1153

1154 1155
		      if (dp)
			{
1156
			  Lisp_Object obj;
1157

1158
			  obj = DISP_CHAR_VECTOR (dp, lose);
1159
			  if (NILP (obj))
1160 1161 1162 1163 1164 1165
			    {
			      /* Do it only for char codes
				 that by default display as themselves.  */
			      if (lose >= 0x20 && lose <= 0x7e)
				no_redisplay = direct_output_for_insert (lose);
			    }
1166
			  else if (VECTORP (obj)
1167
				   && XVECTOR (obj)->size == 1
1168 1169
				   && (obj = XVECTOR (obj)->contents[0],
				       INTEGERP (obj))
1170 1171
				   /* Insist face not specified in glyph.  */
				   && (XINT (obj) & ((-1) << 8)) == 0)
1172 1173
			    no_redisplay
			      = direct_output_for_insert (XINT (obj));
1174 1175 1176 1177