1 /* Minibuffer input and completion.
   2    Copyright (C) 1985, 1986, 1993, 1994, 1995, 1996, 1997, 1998, 1999,
   3                  2000, 2001, 2002, 2003, 2004, 2005, 2006, 2007,
   4                  2008, 2009, 2010  Free Software Foundation, Inc.
   5 
   6 This file is part of GNU Emacs.
   7 
   8 GNU Emacs is free software: you can redistribute it and/or modify
   9 it under the terms of the GNU General Public License as published by
  10 the Free Software Foundation, either version 3 of the License, or
  11 (at your option) any later version.
  12 
  13 GNU Emacs is distributed in the hope that it will be useful,
  14 but WITHOUT ANY WARRANTY; without even the implied warranty of
  15 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
  16 GNU General Public License for more details.
  17 
  18 You should have received a copy of the GNU General Public License
  19 along with GNU Emacs.  If not, see <http://www.gnu.org/licenses/>.  */
  20 
  21 
  22 #include <config.h>
  23 #include <stdio.h>
  24 #include <setjmp.h>
  25 
  26 #include "lisp.h"
  27 #include "commands.h"
  28 #include "buffer.h"
  29 #include "character.h"
  30 #include "dispextern.h"
  31 #include "keyboard.h"
  32 #include "frame.h"
  33 #include "window.h"
  34 #include "syntax.h"
  35 #include "intervals.h"
  36 #include "keymap.h"
  37 #include "termhooks.h"
  38 
  39 extern int quit_char;
  40 
  41 /* List of buffers for use as minibuffers.
  42    The first element of the list is used for the outermost minibuffer
  43    invocation, the next element is used for a recursive minibuffer
  44    invocation, etc.  The list is extended at the end as deeper
  45    minibuffer recursions are encountered.  */
  46 
  47 Lisp_Object Vminibuffer_list;
  48 
  49 /* Data to remember during recursive minibuffer invocations  */
  50 
  51 Lisp_Object minibuf_save_list;
  52 
  53 /* Depth in minibuffer invocations.  */
  54 
  55 int minibuf_level;
  56 
  57 /* The maximum length of a minibuffer history.  */
  58 
  59 Lisp_Object Qhistory_length, Vhistory_length;
  60 
  61 /* No duplicates in history.  */
  62 
  63 int history_delete_duplicates;
  64 
  65 /* Non-nil means add new input to history.  */
  66 
  67 Lisp_Object Vhistory_add_new_input;
  68 
  69 /* Fread_minibuffer leaves the input here as a string. */
  70 
  71 Lisp_Object last_minibuf_string;
  72 
  73 /* Nonzero means let functions called when within a minibuffer
  74    invoke recursive minibuffers (to read arguments, or whatever) */
  75 
  76 int enable_recursive_minibuffers;
  77 
  78 /* Nonzero means don't ignore text properties
  79    in Fread_from_minibuffer.  */
  80 
  81 int minibuffer_allow_text_properties;
  82 
  83 /* help-form is bound to this while in the minibuffer.  */
  84 
  85 Lisp_Object Vminibuffer_help_form;
  86 
  87 /* Variable which is the history list to add minibuffer values to.  */
  88 
  89 Lisp_Object Vminibuffer_history_variable;
  90 
  91 /* Current position in the history list (adjusted by M-n and M-p).  */
  92 
  93 Lisp_Object Vminibuffer_history_position;
  94 
  95 /* Text properties that are added to minibuffer prompts.
  96    These are in addition to the basic `field' property, and stickiness
  97    properties.  */
  98 
  99 Lisp_Object Vminibuffer_prompt_properties;
 100 
 101 Lisp_Object Qminibuffer_history, Qbuffer_name_history;
 102 
 103 Lisp_Object Qread_file_name_internal;
 104 
 105 /* Normal hooks for entry to and exit from minibuffer.  */
 106 
 107 Lisp_Object Qminibuffer_setup_hook, Vminibuffer_setup_hook;
 108 Lisp_Object Qminibuffer_exit_hook, Vminibuffer_exit_hook;
 109 
 110 /* Function to call to read a buffer name.  */
 111 Lisp_Object Vread_buffer_function;
 112 
 113 /* Nonzero means completion ignores case.  */
 114 
 115 int completion_ignore_case;
 116 Lisp_Object Qcompletion_ignore_case;
 117 int read_buffer_completion_ignore_case;
 118 
 119 /* List of regexps that should restrict possible completions.  */
 120 
 121 Lisp_Object Vcompletion_regexp_list;
 122 
 123 /* Nonzero means raise the minibuffer frame when the minibuffer
 124    is entered.  */
 125 
 126 int minibuffer_auto_raise;
 127 
 128 /* Keymap for reading expressions.  */
 129 Lisp_Object Vread_expression_map;
 130 
 131 Lisp_Object Vminibuffer_completion_table, Qminibuffer_completion_table;
 132 Lisp_Object Vminibuffer_completion_predicate, Qminibuffer_completion_predicate;
 133 Lisp_Object Vminibuffer_completion_confirm, Qminibuffer_completion_confirm;
 134 Lisp_Object Vminibuffer_completing_file_name;
 135 
 136 Lisp_Object Quser_variable_p;
 137 
 138 Lisp_Object Qminibuffer_default;
 139 
 140 Lisp_Object Qcurrent_input_method, Qactivate_input_method;
 141 
 142 Lisp_Object Qcase_fold_search;
 143 
 144 Lisp_Object Qread_expression_history;
 145 
 146 extern Lisp_Object Voverriding_local_map;
 147 
 148 extern Lisp_Object Qmouse_face;
 149 
 150 extern Lisp_Object Qfield;
 151 
 152 /* Put minibuf on currently selected frame's minibuffer.
 153    We do this whenever the user starts a new minibuffer
 154    or when a minibuffer exits.  */
 155 
 156 void
 157 choose_minibuf_frame ()
 158 {
 159   if (FRAMEP (selected_frame)
 160       && FRAME_LIVE_P (XFRAME (selected_frame))
 161       && !EQ (minibuf_window, XFRAME (selected_frame)->minibuffer_window))
 162     {
 163       struct frame *sf = XFRAME (selected_frame);
 164       Lisp_Object buffer;
 165 
 166       /* I don't think that any frames may validly have a null minibuffer
 167          window anymore.  */
 168       if (NILP (sf->minibuffer_window))
 169         abort ();
 170 
 171       /* Under X, we come here with minibuf_window being the
 172          minibuffer window of the unused termcap window created in
 173          init_window_once.  That window doesn't have a buffer.  */
 174       buffer = XWINDOW (minibuf_window)->buffer;
 175       if (BUFFERP (buffer))
 176         Fset_window_buffer (sf->minibuffer_window, buffer, Qnil);
 177       minibuf_window = sf->minibuffer_window;
 178     }
 179 
 180   /* Make sure no other frame has a minibuffer as its selected window,
 181      because the text would not be displayed in it, and that would be
 182      confusing.  Only allow the selected frame to do this,
 183      and that only if the minibuffer is active.  */
 184   {
 185     Lisp_Object tail, frame;
 186 
 187     FOR_EACH_FRAME (tail, frame)
 188       if (MINI_WINDOW_P (XWINDOW (FRAME_SELECTED_WINDOW (XFRAME (frame))))
 189           && !(EQ (frame, selected_frame)
 190                && minibuf_level > 0))
 191         Fset_frame_selected_window (frame, Fframe_first_window (frame), Qnil);
 192   }
 193 }
 194 
 195 Lisp_Object
 196 choose_minibuf_frame_1 (ignore)
 197      Lisp_Object ignore;
 198 {
 199   choose_minibuf_frame ();
 200   return Qnil;
 201 }
 202 
 203 DEFUN ("set-minibuffer-window", Fset_minibuffer_window,
 204        Sset_minibuffer_window, 1, 1, 0,
 205        doc: /* Specify which minibuffer window to use for the minibuffer.
 206 This affects where the minibuffer is displayed if you put text in it
 207 without invoking the usual minibuffer commands.  */)
 208      (window)
 209      Lisp_Object window;
 210 {
 211   CHECK_WINDOW (window);
 212   if (! MINI_WINDOW_P (XWINDOW (window)))
 213     error ("Window is not a minibuffer window");
 214 
 215   minibuf_window = window;
 216 
 217   return window;
 218 }
 219 
 220 
 221 /* Actual minibuffer invocation. */
 222 
 223 static Lisp_Object read_minibuf_unwind P_ ((Lisp_Object));
 224 static Lisp_Object run_exit_minibuf_hook P_ ((Lisp_Object));
 225 static Lisp_Object read_minibuf P_ ((Lisp_Object, Lisp_Object,
 226                                      Lisp_Object, Lisp_Object,
 227                                      int, Lisp_Object,
 228                                      Lisp_Object, Lisp_Object,
 229                                      int, int));
 230 static Lisp_Object read_minibuf_noninteractive P_ ((Lisp_Object, Lisp_Object,
 231                                                     Lisp_Object, Lisp_Object,
 232                                                     int, Lisp_Object,
 233                                                     Lisp_Object, Lisp_Object,
 234                                                     int, int));
 235 static Lisp_Object string_to_object P_ ((Lisp_Object, Lisp_Object));
 236 
 237 
 238 /* Read a Lisp object from VAL and return it.  If VAL is an empty
 239    string, and DEFALT is a string, read from DEFALT instead of VAL.  */
 240 
 241 static Lisp_Object
 242 string_to_object (val, defalt)
 243      Lisp_Object val, defalt;
 244 {
 245   struct gcpro gcpro1, gcpro2;
 246   Lisp_Object expr_and_pos;
 247   int pos;
 248 
 249   GCPRO2 (val, defalt);
 250 
 251   if (STRINGP (val) && SCHARS (val) == 0)
 252     {
 253       if (STRINGP (defalt))
 254         val = defalt;
 255       else if (CONSP (defalt) && STRINGP (XCAR (defalt)))
 256         val = XCAR (defalt);
 257     }
 258 
 259   expr_and_pos = Fread_from_string (val, Qnil, Qnil);
 260   pos = XINT (Fcdr (expr_and_pos));
 261   if (pos != SCHARS (val))
 262     {
 263       /* Ignore trailing whitespace; any other trailing junk
 264          is an error.  */
 265       int i;
 266       pos = string_char_to_byte (val, pos);
 267       for (i = pos; i < SBYTES (val); i++)
 268         {
 269           int c = SREF (val, i);
 270           if (c != ' ' && c != '\t' && c != '\n')
 271             error ("Trailing garbage following expression");
 272         }
 273     }
 274 
 275   val = Fcar (expr_and_pos);
 276   RETURN_UNGCPRO (val);
 277 }
 278 
 279 
 280 /* Like read_minibuf but reading from stdin.  This function is called
 281    from read_minibuf to do the job if noninteractive.  */
 282 
 283 static Lisp_Object
 284 read_minibuf_noninteractive (map, initial, prompt, backup_n, expflag,
 285                              histvar, histpos, defalt, allow_props,
 286                              inherit_input_method)
 287      Lisp_Object map;
 288      Lisp_Object initial;
 289      Lisp_Object prompt;
 290      Lisp_Object backup_n;
 291      int expflag;
 292      Lisp_Object histvar;
 293      Lisp_Object histpos;
 294      Lisp_Object defalt;
 295      int allow_props;
 296      int inherit_input_method;
 297 {
 298   int size, len;
 299   char *line, *s;
 300   Lisp_Object val;
 301 
 302   fprintf (stdout, "%s", SDATA (prompt));
 303   fflush (stdout);
 304 
 305   val = Qnil;
 306   size = 100;
 307   len = 0;
 308   line = (char *) xmalloc (size * sizeof *line);
 309   while ((s = fgets (line + len, size - len, stdin)) != NULL
 310          && (len = strlen (line),
 311              len == size - 1 && line[len - 1] != '\n'))
 312     {
 313       size *= 2;
 314       line = (char *) xrealloc (line, size);
 315     }
 316 
 317   if (s)
 318     {
 319       len = strlen (line);
 320 
 321       if (len > 0 && line[len - 1] == '\n')
 322         line[--len] = '\0';
 323 
 324       val = build_string (line);
 325       xfree (line);
 326     }
 327   else
 328     {
 329       xfree (line);
 330       error ("Error reading from stdin");
 331     }
 332 
 333   /* If Lisp form desired instead of string, parse it. */
 334   if (expflag)
 335     val = string_to_object (val, CONSP (defalt) ? XCAR (defalt) : defalt);
 336 
 337   return val;
 338 }
 339 
 340 DEFUN ("minibufferp", Fminibufferp,
 341        Sminibufferp, 0, 1, 0,
 342        doc: /* Return t if BUFFER is a minibuffer.
 343 No argument or nil as argument means use current buffer as BUFFER.
 344 BUFFER can be a buffer or a buffer name.  */)
 345      (buffer)
 346      Lisp_Object buffer;
 347 {
 348   Lisp_Object tem;
 349 
 350   if (NILP (buffer))
 351     buffer = Fcurrent_buffer ();
 352   else if (STRINGP (buffer))
 353     buffer = Fget_buffer (buffer);
 354   else
 355     CHECK_BUFFER (buffer);
 356 
 357   tem = Fmemq (buffer, Vminibuffer_list);
 358   return ! NILP (tem) ? Qt : Qnil;
 359 }
 360 
 361 DEFUN ("minibuffer-prompt-end", Fminibuffer_prompt_end,
 362        Sminibuffer_prompt_end, 0, 0, 0,
 363        doc: /* Return the buffer position of the end of the minibuffer prompt.
 364 Return (point-min) if current buffer is not a minibuffer.  */)
 365      ()
 366 {
 367   /* This function is written to be most efficient when there's a prompt.  */
 368   Lisp_Object beg, end, tem;
 369   beg = make_number (BEGV);
 370 
 371   tem = Fmemq (Fcurrent_buffer (), Vminibuffer_list);
 372   if (NILP (tem))
 373     return beg;
 374 
 375   end = Ffield_end (beg, Qnil, Qnil);
 376 
 377   if (XINT (end) == ZV && NILP (Fget_char_property (beg, Qfield, Qnil)))
 378     return beg;
 379   else
 380     return end;
 381 }
 382 
 383 DEFUN ("minibuffer-contents", Fminibuffer_contents,
 384        Sminibuffer_contents, 0, 0, 0,
 385        doc: /* Return the user input in a minibuffer as a string.
 386 If the current buffer is not a minibuffer, return its entire contents.  */)
 387      ()
 388 {
 389   int prompt_end = XINT (Fminibuffer_prompt_end ());
 390   return make_buffer_string (prompt_end, ZV, 1);
 391 }
 392 
 393 DEFUN ("minibuffer-contents-no-properties", Fminibuffer_contents_no_properties,
 394        Sminibuffer_contents_no_properties, 0, 0, 0,
 395        doc: /* Return the user input in a minibuffer as a string, without text-properties.
 396 If the current buffer is not a minibuffer, return its entire contents.  */)
 397      ()
 398 {
 399   int prompt_end = XINT (Fminibuffer_prompt_end ());
 400   return make_buffer_string (prompt_end, ZV, 0);
 401 }
 402 
 403 DEFUN ("minibuffer-completion-contents", Fminibuffer_completion_contents,
 404        Sminibuffer_completion_contents, 0, 0, 0,
 405        doc: /* Return the user input in a minibuffer before point as a string.
 406 That is what completion commands operate on.
 407 If the current buffer is not a minibuffer, return its entire contents.  */)
 408      ()
 409 {
 410   int prompt_end = XINT (Fminibuffer_prompt_end ());
 411   if (PT < prompt_end)
 412     error ("Cannot do completion in the prompt");
 413   return make_buffer_string (prompt_end, PT, 1);
 414 }
 415 
 416 
 417 /* Read from the minibuffer using keymap MAP and initial contents INITIAL,
 418    putting point minus BACKUP_N bytes from the end of INITIAL,
 419    prompting with PROMPT (a string), using history list HISTVAR
 420    with initial position HISTPOS.  INITIAL should be a string or a
 421    cons of a string and an integer.  BACKUP_N should be <= 0, or
 422    Qnil, which is equivalent to 0.  If INITIAL is a cons, BACKUP_N is
 423    ignored and replaced with an integer that puts point at one-indexed
 424    position N in INITIAL, where N is the CDR of INITIAL, or at the
 425    beginning of INITIAL if N <= 0.
 426 
 427    Normally return the result as a string (the text that was read),
 428    but if EXPFLAG is nonzero, read it and return the object read.
 429    If HISTVAR is given, save the value read on that history only if it doesn't
 430    match the front of that history list exactly.  The value is pushed onto
 431    the list as the string that was read.
 432 
 433    DEFALT specifies the default value for the sake of history commands.
 434 
 435    If ALLOW_PROPS is nonzero, we do not throw away text properties.
 436 
 437    if INHERIT_INPUT_METHOD is nonzero, the minibuffer inherits the
 438    current input method.  */
 439 
 440 static Lisp_Object
 441 read_minibuf (map, initial, prompt, backup_n, expflag,
 442               histvar, histpos, defalt, allow_props, inherit_input_method)
 443      Lisp_Object map;
 444      Lisp_Object initial;
 445      Lisp_Object prompt;
 446      Lisp_Object backup_n;
 447      int expflag;
 448      Lisp_Object histvar;
 449      Lisp_Object histpos;
 450      Lisp_Object defalt;
 451      int allow_props;
 452      int inherit_input_method;
 453 {
 454   Lisp_Object val;
 455   int count = SPECPDL_INDEX ();
 456   Lisp_Object mini_frame, ambient_dir, minibuffer, input_method;
 457   struct gcpro gcpro1, gcpro2, gcpro3, gcpro4, gcpro5;
 458   Lisp_Object enable_multibyte;
 459   int pos = INTEGERP (backup_n) ? XINT (backup_n) : 0;
 460   /* String to add to the history.  */
 461   Lisp_Object histstring;
 462 
 463   Lisp_Object empty_minibuf;
 464   Lisp_Object dummy, frame;
 465 
 466   extern Lisp_Object Qfront_sticky;
 467   extern Lisp_Object Qrear_nonsticky;
 468 
 469   specbind (Qminibuffer_default, defalt);
 470 
 471   /* If Vminibuffer_completing_file_name is `lambda' on entry, it was t
 472      in previous recursive minibuffer, but was not set explicitly
 473      to t for this invocation, so set it to nil in this minibuffer.
 474      Save the old value now, before we change it.  */
 475   specbind (intern ("minibuffer-completing-file-name"), Vminibuffer_completing_file_name);
 476   if (EQ (Vminibuffer_completing_file_name, Qlambda))
 477     Vminibuffer_completing_file_name = Qnil;
 478 
 479 #ifdef HAVE_WINDOW_SYSTEM
 480   if (display_hourglass_p)
 481     cancel_hourglass ();
 482 #endif
 483 
 484   if (!NILP (initial))
 485     {
 486       if (CONSP (initial))
 487         {
 488           backup_n = Fcdr (initial);
 489           initial = Fcar (initial);
 490           CHECK_STRING (initial);
 491           if (!NILP (backup_n))
 492             {
 493               CHECK_NUMBER (backup_n);
 494               /* Convert to distance from end of input.  */
 495               if (XINT (backup_n) < 1)
 496                 /* A number too small means the beginning of the string.  */
 497                 pos =  - SCHARS (initial);
 498               else
 499                 pos = XINT (backup_n) - 1 - SCHARS (initial);
 500             }
 501         }
 502       else
 503         CHECK_STRING (initial);
 504     }
 505   val = Qnil;
 506   ambient_dir = current_buffer->directory;
 507   input_method = Qnil;
 508   enable_multibyte = Qnil;
 509 
 510   /* Don't need to protect PROMPT, HISTVAR, and HISTPOS because we
 511      store them away before we can GC.  Don't need to protect
 512      BACKUP_N because we use the value only if it is an integer.  */
 513   GCPRO5 (map, initial, val, ambient_dir, input_method);
 514 
 515   if (!STRINGP (prompt))
 516     prompt = empty_unibyte_string;
 517 
 518   if (!enable_recursive_minibuffers
 519       && minibuf_level > 0)
 520     {
 521       if (EQ (selected_window, minibuf_window))
 522         error ("Command attempted to use minibuffer while in minibuffer");
 523       else
 524         /* If we're in another window, cancel the minibuffer that's active.  */
 525         Fthrow (Qexit,
 526                 build_string ("Command attempted to use minibuffer while in minibuffer"));
 527     }
 528 
 529   if ((noninteractive
 530        /* In case we are running as a daemon, only do this before
 531           detaching from the terminal.  */
 532        || (IS_DAEMON && (daemon_pipe[1] >= 0)))
 533       && NILP (Vexecuting_kbd_macro))
 534     {
 535       val = read_minibuf_noninteractive (map, initial, prompt,
 536                                          make_number (pos),
 537                                          expflag, histvar, histpos, defalt,
 538                                          allow_props, inherit_input_method);
 539       UNGCPRO;
 540       return unbind_to (count, val);
 541     }
 542 
 543   /* Choose the minibuffer window and frame, and take action on them.  */
 544 
 545   choose_minibuf_frame ();
 546 
 547   record_unwind_protect (choose_minibuf_frame_1, Qnil);
 548 
 549   record_unwind_protect (Fset_window_configuration,
 550                          Fcurrent_window_configuration (Qnil));
 551 
 552   /* If the minibuffer window is on a different frame, save that
 553      frame's configuration too.  */
 554   mini_frame = WINDOW_FRAME (XWINDOW (minibuf_window));
 555   if (!EQ (mini_frame, selected_frame))
 556     record_unwind_protect (Fset_window_configuration,
 557                            Fcurrent_window_configuration (mini_frame));
 558 
 559   /* If the minibuffer is on an iconified or invisible frame,
 560      make it visible now.  */
 561   Fmake_frame_visible (mini_frame);
 562 
 563   if (minibuffer_auto_raise)
 564     Fraise_frame (mini_frame);
 565 
 566   temporarily_switch_to_single_kboard (XFRAME (mini_frame));
 567 
 568   /* We have to do this after saving the window configuration
 569      since that is what restores the current buffer.  */
 570 
 571   /* Arrange to restore a number of minibuffer-related variables.
 572      We could bind each variable separately, but that would use lots of
 573      specpdl slots.  */
 574   minibuf_save_list
 575     = Fcons (Voverriding_local_map,
 576              Fcons (minibuf_window,
 577                     minibuf_save_list));
 578   minibuf_save_list
 579     = Fcons (minibuf_prompt,
 580              Fcons (make_number (minibuf_prompt_width),
 581                     Fcons (Vhelp_form,
 582                            Fcons (Vcurrent_prefix_arg,
 583                                   Fcons (Vminibuffer_history_position,
 584                                          Fcons (Vminibuffer_history_variable,
 585                                                 minibuf_save_list))))));
 586 
 587   record_unwind_protect (read_minibuf_unwind, Qnil);
 588   minibuf_level++;
 589   /* We are exiting the minibuffer one way or the other, so run the hook.
 590      It should be run before unwinding the minibuf settings.  Do it
 591      separately from read_minibuf_unwind because we need to make sure that
 592      read_minibuf_unwind is fully executed even if exit-minibuffer-hook
 593      signals an error.  --Stef  */
 594   record_unwind_protect (run_exit_minibuf_hook, Qnil);
 595 
 596   /* Now that we can restore all those variables, start changing them.  */
 597 
 598   minibuf_prompt_width = 0;
 599   minibuf_prompt = Fcopy_sequence (prompt);
 600   Vminibuffer_history_position = histpos;
 601   Vminibuffer_history_variable = histvar;
 602   Vhelp_form = Vminibuffer_help_form;
 603   /* If this minibuffer is reading a file name, that doesn't mean
 604      recursive ones are.  But we cannot set it to nil, because
 605      completion code still need to know the minibuffer is completing a
 606      file name.  So use `lambda' as intermediate value meaning
 607      "t" in this minibuffer, but "nil" in next minibuffer.  */
 608   if (!NILP (Vminibuffer_completing_file_name))
 609     Vminibuffer_completing_file_name = Qlambda;
 610 
 611   if (inherit_input_method)
 612     {
 613       /* `current-input-method' is buffer local.  So, remember it in
 614          INPUT_METHOD before changing the current buffer.  */
 615       input_method = Fsymbol_value (Qcurrent_input_method);
 616       enable_multibyte = current_buffer->enable_multibyte_characters;
 617     }
 618 
 619   /* Switch to the minibuffer.  */
 620 
 621   minibuffer = get_minibuffer (minibuf_level);
 622   Fset_buffer (minibuffer);
 623 
 624   /* If appropriate, copy enable-multibyte-characters into the minibuffer.  */
 625   if (inherit_input_method)
 626     current_buffer->enable_multibyte_characters = enable_multibyte;
 627 
 628   /* The current buffer's default directory is usually the right thing
 629      for our minibuffer here.  However, if you're typing a command at
 630      a minibuffer-only frame when minibuf_level is zero, then buf IS
 631      the current_buffer, so reset_buffer leaves buf's default
 632      directory unchanged.  This is a bummer when you've just started
 633      up Emacs and buf's default directory is Qnil.  Here's a hack; can
 634      you think of something better to do?  Find another buffer with a
 635      better directory, and use that one instead.  */
 636   if (STRINGP (ambient_dir))
 637     current_buffer->directory = ambient_dir;
 638   else
 639     {
 640       Lisp_Object buf_list;
 641 
 642       for (buf_list = Vbuffer_alist;
 643            CONSP (buf_list);
 644            buf_list = XCDR (buf_list))
 645         {
 646           Lisp_Object other_buf;
 647 
 648           other_buf = XCDR (XCAR (buf_list));
 649           if (STRINGP (XBUFFER (other_buf)->directory))
 650             {
 651               current_buffer->directory = XBUFFER (other_buf)->directory;
 652               break;
 653             }
 654         }
 655     }
 656 
 657   if (!EQ (mini_frame, selected_frame))
 658     Fredirect_frame_focus (selected_frame, mini_frame);
 659 
 660   Vminibuf_scroll_window = selected_window;
 661   if (minibuf_level == 1 || !EQ (minibuf_window, selected_window))
 662     minibuf_selected_window = selected_window;
 663 
 664   /* Empty out the minibuffers of all frames other than the one
 665      where we are going to display one now.
 666      Set them to point to ` *Minibuf-0*', which is always empty.  */
 667   empty_minibuf = Fget_buffer (build_string (" *Minibuf-0*"));
 668 
 669   FOR_EACH_FRAME (dummy, frame)
 670     {
 671       Lisp_Object root_window = Fframe_root_window (frame);
 672       Lisp_Object mini_window = XWINDOW (root_window)->next;
 673 
 674       if (! NILP (mini_window) && ! EQ (mini_window, minibuf_window)
 675           && !NILP (Fwindow_minibuffer_p (mini_window)))
 676         Fset_window_buffer (mini_window, empty_minibuf, Qnil);
 677     }
 678 
 679   /* Display this minibuffer in the proper window.  */
 680   Fset_window_buffer (minibuf_window, Fcurrent_buffer (), Qnil);
 681   Fselect_window (minibuf_window, Qnil);
 682   XSETFASTINT (XWINDOW (minibuf_window)->hscroll, 0);
 683 
 684   Fmake_local_variable (Qprint_escape_newlines);
 685   print_escape_newlines = 1;
 686 
 687   /* Erase the buffer.  */
 688   {
 689     int count1 = SPECPDL_INDEX ();
 690     specbind (Qinhibit_read_only, Qt);
 691     specbind (Qinhibit_modification_hooks, Qt);
 692     Ferase_buffer ();
 693 
 694     if (!NILP (current_buffer->enable_multibyte_characters)
 695         && ! STRING_MULTIBYTE (minibuf_prompt))
 696       minibuf_prompt = Fstring_make_multibyte (minibuf_prompt);
 697 
 698     /* Insert the prompt, record where it ends.  */
 699     Finsert (1, &minibuf_prompt);
 700     if (PT > BEG)
 701       {
 702         Fput_text_property (make_number (BEG), make_number (PT),
 703                             Qfront_sticky, Qt, Qnil);
 704         Fput_text_property (make_number (BEG), make_number (PT),
 705                             Qrear_nonsticky, Qt, Qnil);
 706         Fput_text_property (make_number (BEG), make_number (PT),
 707                             Qfield, Qt, Qnil);
 708         Fadd_text_properties (make_number (BEG), make_number (PT),
 709                               Vminibuffer_prompt_properties, Qnil);
 710       }
 711     unbind_to (count1, Qnil);
 712   }
 713 
 714   minibuf_prompt_width = (int) current_column (); /* iftc */
 715 
 716   /* Put in the initial input.  */
 717   if (!NILP (initial))
 718     {
 719       Finsert (1, &initial);
 720       Fforward_char (make_number (pos));
 721     }
 722 
 723   clear_message (1, 1);
 724   current_buffer->keymap = map;
 725 
 726   /* Turn on an input method stored in INPUT_METHOD if any.  */
 727   if (STRINGP (input_method) && !NILP (Ffboundp (Qactivate_input_method)))
 728     call1 (Qactivate_input_method, input_method);
 729 
 730   /* Run our hook, but not if it is empty.
 731      (run-hooks would do nothing if it is empty,
 732      but it's important to save time here in the usual case.)  */
 733   if (!NILP (Vminibuffer_setup_hook) && !EQ (Vminibuffer_setup_hook, Qunbound)
 734       && !NILP (Vrun_hooks))
 735     call1 (Vrun_hooks, Qminibuffer_setup_hook);
 736 
 737   /* Don't allow the user to undo past this point.  */
 738   current_buffer->undo_list = Qnil;
 739 
 740   recursive_edit_1 ();
 741 
 742   /* If cursor is on the minibuffer line,
 743      show the user we have exited by putting it in column 0.  */
 744   if (XWINDOW (minibuf_window)->cursor.vpos >= 0
 745       && !noninteractive)
 746     {
 747       XWINDOW (minibuf_window)->cursor.hpos = 0;
 748       XWINDOW (minibuf_window)->cursor.x = 0;
 749       XWINDOW (minibuf_window)->must_be_updated_p = 1;
 750       update_frame (XFRAME (selected_frame), 1, 1);
 751       {
 752         struct frame *f = XFRAME (XWINDOW (minibuf_window)->frame);
 753         struct redisplay_interface *rif = FRAME_RIF (f);
 754         if (rif && rif->flush_display)
 755           rif->flush_display (f);
 756       }
 757     }
 758 
 759   /* Make minibuffer contents into a string.  */
 760   Fset_buffer (minibuffer);
 761   if (allow_props)
 762     val = Fminibuffer_contents ();
 763   else
 764     val = Fminibuffer_contents_no_properties ();
 765 
 766   /* VAL is the string of minibuffer text.  */
 767 
 768   last_minibuf_string = val;
 769 
 770   /* Choose the string to add to the history.  */
 771   if (SCHARS (val) != 0)
 772     histstring = val;
 773   else if (STRINGP (defalt))
 774     histstring = defalt;
 775   else if (CONSP (defalt) && STRINGP (XCAR (defalt)))
 776     histstring = XCAR (defalt);
 777   else
 778     histstring = Qnil;
 779 
 780   /* Add the value to the appropriate history list, if any.  */
 781   if (!NILP (Vhistory_add_new_input)
 782       && SYMBOLP (Vminibuffer_history_variable)
 783       && !NILP (histstring))
 784     {
 785       /* If the caller wanted to save the value read on a history list,
 786          then do so if the value is not already the front of the list.  */
 787       Lisp_Object histval;
 788 
 789       /* If variable is unbound, make it nil.  */
 790 
 791       histval = find_symbol_value (Vminibuffer_history_variable);
 792       if (EQ (histval, Qunbound))
 793         Fset (Vminibuffer_history_variable, Qnil);
 794 
 795       /* The value of the history variable must be a cons or nil.  Other
 796          values are unacceptable.  We silently ignore these values.  */
 797 
 798       if (NILP (histval)
 799           || (CONSP (histval)
 800               /* Don't duplicate the most recent entry in the history.  */
 801               && (NILP (Fequal (histstring, Fcar (histval))))))
 802         {
 803           Lisp_Object length;
 804 
 805           if (history_delete_duplicates) Fdelete (histstring, histval);
 806           histval = Fcons (histstring, histval);
 807           Fset (Vminibuffer_history_variable, histval);
 808 
 809           /* Truncate if requested.  */
 810           length = Fget (Vminibuffer_history_variable, Qhistory_length);
 811           if (NILP (length)) length = Vhistory_length;
 812           if (INTEGERP (length))
 813             {
 814               if (XINT (length) <= 0)
 815                 Fset (Vminibuffer_history_variable, Qnil);
 816               else
 817                 {
 818                   Lisp_Object temp;
 819 
 820                   temp = Fnthcdr (Fsub1 (length), histval);
 821                   if (CONSP (temp)) Fsetcdr (temp, Qnil);
 822                 }
 823             }
 824         }
 825     }
 826 
 827   /* If Lisp form desired instead of string, parse it. */
 828   if (expflag)
 829     val = string_to_object (val, defalt);
 830 
 831   /* The appropriate frame will get selected
 832      in set-window-configuration.  */
 833   UNGCPRO;
 834   return unbind_to (count, val);
 835 }
 836 
 837 /* Return a buffer to be used as the minibuffer at depth `depth'.
 838  depth = 0 is the lowest allowed argument, and that is the value
 839  used for nonrecursive minibuffer invocations */
 840 
 841 Lisp_Object
 842 get_minibuffer (depth)
 843      int depth;
 844 {
 845   Lisp_Object tail, num, buf;
 846   char name[24];
 847   extern Lisp_Object nconc2 ();
 848 
 849   XSETFASTINT (num, depth);
 850   tail = Fnthcdr (num, Vminibuffer_list);
 851   if (NILP (tail))
 852     {
 853       tail = Fcons (Qnil, Qnil);
 854       Vminibuffer_list = nconc2 (Vminibuffer_list, tail);
 855     }
 856   buf = Fcar (tail);
 857   if (NILP (buf) || NILP (XBUFFER (buf)->name))
 858     {
 859       sprintf (name, " *Minibuf-%d*", depth);
 860       buf = Fget_buffer_create (build_string (name));
 861 
 862       /* Although the buffer's name starts with a space, undo should be
 863          enabled in it.  */
 864       Fbuffer_enable_undo (buf);
 865 
 866       XSETCAR (tail, buf);
 867     }
 868   else
 869     {
 870       int count = SPECPDL_INDEX ();
 871       /* `reset_buffer' blindly sets the list of overlays to NULL, so we
 872          have to empty the list, otherwise we end up with overlays that
 873          think they belong to this buffer while the buffer doesn't know about
 874          them any more.  */
 875       delete_all_overlays (XBUFFER (buf));
 876       reset_buffer (XBUFFER (buf));
 877       record_unwind_protect (Fset_buffer, Fcurrent_buffer ());
 878       Fset_buffer (buf);
 879       Fkill_all_local_variables ();
 880       unbind_to (count, Qnil);
 881     }
 882 
 883   return buf;
 884 }
 885 
 886 static Lisp_Object
 887 run_exit_minibuf_hook (data)
 888      Lisp_Object data;
 889 {
 890   if (!NILP (Vminibuffer_exit_hook) && !EQ (Vminibuffer_exit_hook, Qunbound)
 891       && !NILP (Vrun_hooks))
 892     safe_run_hooks (Qminibuffer_exit_hook);
 893 
 894   return Qnil;
 895 }
 896 
 897 /* This function is called on exiting minibuffer, whether normally or
 898    not, and it restores the current window, buffer, etc. */
 899 
 900 static Lisp_Object
 901 read_minibuf_unwind (data)
 902      Lisp_Object data;
 903 {
 904   Lisp_Object old_deactivate_mark;
 905   Lisp_Object window;
 906 
 907   /* If this was a recursive minibuffer,
 908      tie the minibuffer window back to the outer level minibuffer buffer.  */
 909   minibuf_level--;
 910 
 911   window = minibuf_window;
 912   /* To keep things predictable, in case it matters, let's be in the
 913      minibuffer when we reset the relevant variables.  */
 914   Fset_buffer (XWINDOW (window)->buffer);
 915 
 916   /* Restore prompt, etc, from outer minibuffer level.  */
 917   minibuf_prompt = Fcar (minibuf_save_list);
 918   minibuf_save_list = Fcdr (minibuf_save_list);
 919   minibuf_prompt_width = XFASTINT (Fcar (minibuf_save_list));
 920   minibuf_save_list = Fcdr (minibuf_save_list);
 921   Vhelp_form = Fcar (minibuf_save_list);
 922   minibuf_save_list = Fcdr (minibuf_save_list);
 923   Vcurrent_prefix_arg = Fcar (minibuf_save_list);
 924   minibuf_save_list = Fcdr (minibuf_save_list);
 925   Vminibuffer_history_position = Fcar (minibuf_save_list);
 926   minibuf_save_list = Fcdr (minibuf_save_list);
 927   Vminibuffer_history_variable = Fcar (minibuf_save_list);
 928   minibuf_save_list = Fcdr (minibuf_save_list);
 929   Voverriding_local_map = Fcar (minibuf_save_list);
 930   minibuf_save_list = Fcdr (minibuf_save_list);
 931 #if 0
 932   temp = Fcar (minibuf_save_list);
 933   if (FRAME_LIVE_P (XFRAME (WINDOW_FRAME (XWINDOW (temp)))))
 934     minibuf_window = temp;
 935 #endif
 936   minibuf_save_list = Fcdr (minibuf_save_list);
 937 
 938   /* Erase the minibuffer we were using at this level.  */
 939   {
 940     int count = SPECPDL_INDEX ();
 941     /* Prevent error in erase-buffer.  */
 942     specbind (Qinhibit_read_only, Qt);
 943     specbind (Qinhibit_modification_hooks, Qt);
 944     old_deactivate_mark = Vdeactivate_mark;
 945     Ferase_buffer ();
 946     Vdeactivate_mark = old_deactivate_mark;
 947     unbind_to (count, Qnil);
 948   }
 949 
 950   /* When we get to the outmost level, make sure we resize the
 951      mini-window back to its normal size.  */
 952   if (minibuf_level == 0)
 953     resize_mini_window (XWINDOW (window), 0);
 954 
 955   /* Make sure minibuffer window is erased, not ignored.  */
 956   windows_or_buffers_changed++;
 957   XSETFASTINT (XWINDOW (window)->last_modified, 0);
 958   XSETFASTINT (XWINDOW (window)->last_overlay_modified, 0);
 959   return Qnil;
 960 }
 961 
 962 
 963 DEFUN ("read-from-minibuffer", Fread_from_minibuffer, Sread_from_minibuffer, 1, 7, 0,
 964        doc: /* Read a string from the minibuffer, prompting with string PROMPT.
 965 The optional second arg INITIAL-CONTENTS is an obsolete alternative to
 966   DEFAULT-VALUE.  It normally should be nil in new code, except when
 967   HIST is a cons.  It is discussed in more detail below.
 968 Third arg KEYMAP is a keymap to use whilst reading;
 969   if omitted or nil, the default is `minibuffer-local-map'.
 970 If fourth arg READ is non-nil, then interpret the result as a Lisp object
 971   and return that object:
 972   in other words, do `(car (read-from-string INPUT-STRING))'
 973 Fifth arg HIST, if non-nil, specifies a history list and optionally
 974   the initial position in the list.  It can be a symbol, which is the
 975   history list variable to use, or it can be a cons cell
 976   (HISTVAR . HISTPOS).  In that case, HISTVAR is the history list variable
 977   to use, and HISTPOS is the initial position for use by the minibuffer
 978   history commands.  For consistency, you should also specify that
 979   element of the history as the value of INITIAL-CONTENTS.  Positions
 980   are counted starting from 1 at the beginning of the list.
 981 Sixth arg DEFAULT-VALUE is the default value or the list of default values.
 982   If non-nil, it is available for history commands, and as the value
 983   (or the first element of the list of default values) to return
 984   if the user enters the empty string.  But, unless READ is non-nil,
 985   `read-from-minibuffer' does NOT return DEFAULT-VALUE if the user enters
 986   empty input!  It returns the empty string.
 987 Seventh arg INHERIT-INPUT-METHOD, if non-nil, means the minibuffer inherits
 988  the current input method and the setting of `enable-multibyte-characters'.
 989 If the variable `minibuffer-allow-text-properties' is non-nil,
 990  then the string which is returned includes whatever text properties
 991  were present in the minibuffer.  Otherwise the value has no text properties.
 992 
 993 The remainder of this documentation string describes the
 994 INITIAL-CONTENTS argument in more detail.  It is only relevant when
 995 studying existing code, or when HIST is a cons.  If non-nil,
 996 INITIAL-CONTENTS is a string to be inserted into the minibuffer before
 997 reading input.  Normally, point is put at the end of that string.
 998 However, if INITIAL-CONTENTS is \(STRING . POSITION), the initial
 999 input is STRING, but point is placed at _one-indexed_ position
1000 POSITION in the minibuffer.  Any integer value less than or equal to
1001 one puts point at the beginning of the string.  *Note* that this
1002 behavior differs from the way such arguments are used in `completing-read'
1003 and some related functions, which use zero-indexing for POSITION.  */)
1004    (prompt, initial_contents, keymap, read, hist, default_value, inherit_input_method)
1005      Lisp_Object prompt, initial_contents, keymap, read, hist, default_value;
1006      Lisp_Object inherit_input_method;
1007 {
1008   Lisp_Object histvar, histpos, val;
1009   struct gcpro gcpro1;
1010 
1011   CHECK_STRING (prompt);
1012   if (NILP (keymap))
1013     keymap = Vminibuffer_local_map;
1014   else
1015     keymap = get_keymap (keymap, 1, 0);
1016 
1017   if (SYMBOLP (hist))
1018     {
1019       histvar = hist;
1020       histpos = Qnil;
1021     }
1022   else
1023     {
1024       histvar = Fcar_safe (hist);
1025       histpos = Fcdr_safe (hist);
1026     }
1027   if (NILP (histvar))
1028     histvar = Qminibuffer_history;
1029   if (NILP (histpos))
1030     XSETFASTINT (histpos, 0);
1031 
1032   GCPRO1 (default_value);
1033   val = read_minibuf (keymap, initial_contents, prompt,
1034                       Qnil, !NILP (read),
1035                       histvar, histpos, default_value,
1036                       minibuffer_allow_text_properties,
1037                       !NILP (inherit_input_method));
1038   UNGCPRO;
1039   return val;
1040 }
1041 
1042 DEFUN ("read-minibuffer", Fread_minibuffer, Sread_minibuffer, 1, 2, 0,
1043        doc: /* Return a Lisp object read using the minibuffer, unevaluated.
1044 Prompt with PROMPT.  If non-nil, optional second arg INITIAL-CONTENTS
1045 is a string to insert in the minibuffer before reading.
1046 \(INITIAL-CONTENTS can also be a cons of a string and an integer.
1047 Such arguments are used as in `read-from-minibuffer'.)  */)
1048      (prompt, initial_contents)
1049      Lisp_Object prompt, initial_contents;
1050 {
1051   CHECK_STRING (prompt);
1052   return read_minibuf (Vminibuffer_local_map, initial_contents,
1053                        prompt, Qnil, 1, Qminibuffer_history,
1054                        make_number (0), Qnil, 0, 0);
1055 }
1056 
1057 DEFUN ("eval-minibuffer", Feval_minibuffer, Seval_minibuffer, 1, 2, 0,
1058        doc: /* Return value of Lisp expression read using the minibuffer.
1059 Prompt with PROMPT.  If non-nil, optional second arg INITIAL-CONTENTS
1060 is a string to insert in the minibuffer before reading.
1061 \(INITIAL-CONTENTS can also be a cons of a string and an integer.
1062 Such arguments are used as in `read-from-minibuffer'.)  */)
1063      (prompt, initial_contents)
1064      Lisp_Object prompt, initial_contents;
1065 {
1066   return Feval (read_minibuf (Vread_expression_map, initial_contents,
1067                               prompt, Qnil, 1, Qread_expression_history,
1068                               make_number (0), Qnil, 0, 0));
1069 }
1070 
1071 /* Functions that use the minibuffer to read various things. */
1072 
1073 DEFUN ("read-string", Fread_string, Sread_string, 1, 5, 0,
1074        doc: /* Read a string from the minibuffer, prompting with string PROMPT.
1075 If non-nil, second arg INITIAL-INPUT is a string to insert before reading.
1076   This argument has been superseded by DEFAULT-VALUE and should normally
1077   be nil in new code.  It behaves as in `read-from-minibuffer'.  See the
1078   documentation string of that function for details.
1079 The third arg HISTORY, if non-nil, specifies a history list
1080   and optionally the initial position in the list.
1081 See `read-from-minibuffer' for details of HISTORY argument.
1082 Fourth arg DEFAULT-VALUE is the default value or the list of default values.
1083  If non-nil, it is used for history commands, and as the value (or the first
1084  element of the list of default values) to return if the user enters the
1085  empty string.
1086 Fifth arg INHERIT-INPUT-METHOD, if non-nil, means the minibuffer inherits
1087  the current input method and the setting of `enable-multibyte-characters'.  */)
1088      (prompt, initial_input, history, default_value, inherit_input_method)
1089      Lisp_Object prompt, initial_input, history, default_value;
1090      Lisp_Object inherit_input_method;
1091 {
1092   Lisp_Object val;
1093   val = Fread_from_minibuffer (prompt, initial_input, Qnil,
1094                                Qnil, history, default_value,
1095                                inherit_input_method);
1096   if (STRINGP (val) && SCHARS (val) == 0 && ! NILP (default_value))
1097     val = CONSP (default_value) ? XCAR (default_value) : default_value;
1098   return val;
1099 }
1100 
1101 DEFUN ("read-no-blanks-input", Fread_no_blanks_input, Sread_no_blanks_input, 1, 3, 0,
1102        doc: /* Read a string from the terminal, not allowing blanks.
1103 Prompt with PROMPT.  Whitespace terminates the input.  If INITIAL is
1104 non-nil, it should be a string, which is used as initial input, with
1105 point positioned at the end, so that SPACE will accept the input.
1106 \(Actually, INITIAL can also be a cons of a string and an integer.
1107 Such values are treated as in `read-from-minibuffer', but are normally
1108 not useful in this function.)
1109 Third arg INHERIT-INPUT-METHOD, if non-nil, means the minibuffer inherits
1110 the current input method and the setting of`enable-multibyte-characters'.  */)
1111      (prompt, initial, inherit_input_method)
1112      Lisp_Object prompt, initial, inherit_input_method;
1113 {
1114   CHECK_STRING (prompt);
1115   return read_minibuf (Vminibuffer_local_ns_map, initial, prompt, Qnil,
1116                        0, Qminibuffer_history, make_number (0), Qnil, 0,
1117                        !NILP (inherit_input_method));
1118 }
1119 
1120 DEFUN ("read-command", Fread_command, Sread_command, 1, 2, 0,
1121        doc: /* Read the name of a command and return as a symbol.
1122 Prompt with PROMPT.  By default, return DEFAULT-VALUE or its first element
1123 if it is a list.  */)
1124      (prompt, default_value)
1125      Lisp_Object prompt, default_value;
1126 {
1127   Lisp_Object name, default_string;
1128 
1129   if (NILP (default_value))
1130     default_string = Qnil;
1131   else if (SYMBOLP (default_value))
1132     default_string = SYMBOL_NAME (default_value);
1133   else
1134     default_string = default_value;
1135 
1136   name = Fcompleting_read (prompt, Vobarray, Qcommandp, Qt,
1137                            Qnil, Qnil, default_string, Qnil);
1138   if (NILP (name))
1139     return name;
1140   return Fintern (name, Qnil);
1141 }
1142 
1143 #ifdef NOTDEF
1144 DEFUN ("read-function", Fread_function, Sread_function, 1, 1, 0,
1145        doc: /* One arg PROMPT, a string.  Read the name of a function and return as a symbol.
1146 Prompt with PROMPT.  */)
1147      (prompt)
1148      Lisp_Object prompt;
1149 {
1150   return Fintern (Fcompleting_read (prompt, Vobarray, Qfboundp, Qt, Qnil, Qnil, Qnil, Qnil),
1151                   Qnil);
1152 }
1153 #endif /* NOTDEF */
1154 
1155 DEFUN ("read-variable", Fread_variable, Sread_variable, 1, 2, 0,
1156        doc: /* Read the name of a user variable and return it as a symbol.
1157 Prompt with PROMPT.  By default, return DEFAULT-VALUE or its first element
1158 if it is a list.
1159 A user variable is one for which `user-variable-p' returns non-nil.  */)
1160      (prompt, default_value)
1161      Lisp_Object prompt, default_value;
1162 {
1163   Lisp_Object name, default_string;
1164 
1165   if (NILP (default_value))
1166     default_string = Qnil;
1167   else if (SYMBOLP (default_value))
1168     default_string = SYMBOL_NAME (default_value);
1169   else
1170     default_string = default_value;
1171 
1172   name = Fcompleting_read (prompt, Vobarray,
1173                            Quser_variable_p, Qt,
1174                            Qnil, Qnil, default_string, Qnil);
1175   if (NILP (name))
1176     return name;
1177   return Fintern (name, Qnil);
1178 }
1179 
1180 DEFUN ("read-buffer", Fread_buffer, Sread_buffer, 1, 3, 0,
1181        doc: /* Read the name of a buffer and return as a string.
1182 Prompt with PROMPT.
1183 Optional second arg DEF is value to return if user enters an empty line.
1184  If DEF is a list of default values, return its first element.
1185 Optional third arg REQUIRE-MATCH determines whether non-existing
1186  buffer names are allowed.  It has the same meaning as the
1187  REQUIRE-MATCH argument of `confirm-after-completion'.
1188 The argument PROMPT should be a string ending with a colon and a space.
1189 If `read-buffer-completion-ignore-case' is non-nil, completion ignores
1190 case while reading the buffer name.
1191 If `read-buffer-function' is non-nil, this works by calling it as a
1192 function, instead of the usual behavior.  */)
1193      (prompt, def, require_match)
1194      Lisp_Object prompt, def, require_match;
1195 {
1196   Lisp_Object args[4], result;
1197   unsigned char *s;
1198   int len;
1199   int count = SPECPDL_INDEX ();
1200 
1201   if (BUFFERP (def))
1202     def = XBUFFER (def)->name;
1203 
1204   specbind (Qcompletion_ignore_case,
1205             read_buffer_completion_ignore_case ? Qt : Qnil);
1206 
1207   if (NILP (Vread_buffer_function))
1208     {
1209       if (!NILP (def))
1210         {
1211           /* A default value was provided: we must change PROMPT,
1212              editing the default value in before the colon.  To achieve
1213              this, we replace PROMPT with a substring that doesn't
1214              contain the terminal space and colon (if present).  They
1215              are then added back using Fformat.  */
1216 
1217           if (STRINGP (prompt))
1218             {
1219               s = SDATA (prompt);
1220               len = strlen (s);
1221               if (len >= 2 && s[len - 2] == ':' && s[len - 1] == ' ')
1222                 len = len - 2;
1223               else if (len >= 1 && (s[len - 1] == ':' || s[len - 1] == ' '))
1224                 len--;
1225 
1226               prompt = make_specified_string (s, -1, len,
1227                                               STRING_MULTIBYTE (prompt));
1228             }
1229 
1230           args[0] = build_string ("%s (default %s): ");
1231           args[1] = prompt;
1232           args[2] = CONSP (def) ? XCAR (def) : def;
1233           prompt = Fformat (3, args);
1234         }
1235 
1236       result = Fcompleting_read (prompt, intern ("internal-complete-buffer"),
1237                                  Qnil, require_match, Qnil, Qbuffer_name_history,
1238                                  def, Qnil);
1239     }
1240   else
1241     {
1242       args[0] = Vread_buffer_function;
1243       args[1] = prompt;
1244       args[2] = def;
1245       args[3] = require_match;
1246       result = Ffuncall(4, args);
1247     }
1248   return unbind_to (count, result);
1249 }
1250 
1251 static Lisp_Object
1252 minibuf_conform_representation (string, basis)
1253      Lisp_Object string, basis;
1254 {
1255   if (STRING_MULTIBYTE (string) == STRING_MULTIBYTE (basis))
1256     return string;
1257 
1258   if (STRING_MULTIBYTE (string))
1259     return Fstring_make_unibyte (string);
1260   else
1261     return Fstring_make_multibyte (string);
1262 }
1263 
1264 DEFUN ("try-completion", Ftry_completion, Stry_completion, 2, 3, 0,
1265        doc: /* Return common substring of all completions of STRING in COLLECTION.
1266 Test each possible completion specified by COLLECTION
1267 to see if it begins with STRING.  The possible completions may be
1268 strings or symbols.  Symbols are converted to strings before testing,
1269 see `symbol-name'.
1270 All that match STRING are compared together; the longest initial sequence
1271 common to all these matches is the return value.
1272 If there is no match at all, the return value is nil.
1273 For a unique match which is exact, the return value is t.
1274 
1275 If COLLECTION is an alist, the keys (cars of elements) are the
1276 possible completions.  If an element is not a cons cell, then the
1277 element itself is the possible completion.
1278 If COLLECTION is a hash-table, all the keys that are strings or symbols
1279 are the possible completions.
1280 If COLLECTION is an obarray, the names of all symbols in the obarray
1281 are the possible completions.
1282 
1283 COLLECTION can also be a function to do the completion itself.
1284 It receives three arguments: the values STRING, PREDICATE and nil.
1285 Whatever it returns becomes the value of `try-completion'.
1286 
1287 If optional third argument PREDICATE is non-nil,
1288 it is used to test each possible match.
1289 The match is a candidate only if PREDICATE returns non-nil.
1290 The argument given to PREDICATE is the alist element
1291 or the symbol from the obarray.  If COLLECTION is a hash-table,
1292 predicate is called with two arguments: the key and the value.
1293 Additionally to this predicate, `completion-regexp-list'
1294 is used to further constrain the set of candidates.  */)
1295      (string, collection, predicate)
1296      Lisp_Object string, collection, predicate;
1297 {
1298   Lisp_Object bestmatch, tail, elt, eltstring;
1299   /* Size in bytes of BESTMATCH.  */
1300   int bestmatchsize = 0;
1301   /* These are in bytes, too.  */
1302   int compare, matchsize;
1303   enum { function_table, list_table, obarray_table, hash_table}
1304     type = (HASH_TABLE_P (collection) ? hash_table
1305             : VECTORP (collection) ? obarray_table
1306             : ((NILP (collection)
1307                 || (CONSP (collection)
1308                     && (!SYMBOLP (XCAR (collection))
1309                         || NILP (XCAR (collection)))))
1310                ? list_table : function_table));
1311   int index = 0, obsize = 0;
1312   int matchcount = 0;
1313   int bindcount = -1;
1314   Lisp_Object bucket, zero, end, tem;
1315   struct gcpro gcpro1, gcpro2, gcpro3, gcpro4;
1316 
1317   CHECK_STRING (string);
1318   if (type == function_table)
1319     return call3 (collection, string, predicate, Qnil);
1320 
1321   bestmatch = bucket = Qnil;
1322   zero = make_number (0);
1323 
1324   /* If COLLECTION is not a list, set TAIL just for gc pro.  */
1325   tail = collection;
1326   if (type == obarray_table)
1327     {
1328       collection = check_obarray (collection);
1329       obsize = XVECTOR (collection)->size;
1330       bucket = XVECTOR (collection)->contents[index];
1331     }
1332 
1333   while (1)
1334     {
1335       /* Get the next element of the alist, obarray, or hash-table. */
1336       /* Exit the loop if the elements are all used up. */
1337       /* elt gets the alist element or symbol.
1338          eltstring gets the name to check as a completion. */
1339 
1340       if (type == list_table)
1341         {
1342           if (!CONSP (tail))
1343             break;
1344           elt = XCAR (tail);
1345           eltstring = CONSP (elt) ? XCAR (elt) : elt;
1346           tail = XCDR (tail);
1347         }
1348       else if (type == obarray_table)
1349         {
1350           if (!EQ (bucket, zero))
1351             {
1352               if (!SYMBOLP (bucket))
1353                 error ("Bad data in guts of obarray");
1354               elt = bucket;
1355               eltstring = elt;
1356               if (XSYMBOL (bucket)->next)
1357                 XSETSYMBOL (bucket, XSYMBOL (bucket)->next);
1358               else
1359                 XSETFASTINT (bucket, 0);
1360             }
1361           else if (++index >= obsize)
1362             break;
1363           else
1364             {
1365               bucket = XVECTOR (collection)->contents[index];
1366               continue;
1367             }
1368         }
1369       else /* if (type == hash_table) */
1370         {
1371           while (index < HASH_TABLE_SIZE (XHASH_TABLE (collection))
1372                  && NILP (HASH_HASH (XHASH_TABLE (collection), index)))
1373             index++;
1374           if (index >= HASH_TABLE_SIZE (XHASH_TABLE (collection)))
1375             break;
1376           else
1377             elt = eltstring = HASH_KEY (XHASH_TABLE (collection), index++);
1378         }
1379 
1380       /* Is this element a possible completion? */
1381 
1382       if (SYMBOLP (eltstring))
1383         eltstring = Fsymbol_name (eltstring);
1384 
1385       if (STRINGP (eltstring)
1386           && SCHARS (string) <= SCHARS (eltstring)
1387           && (tem = Fcompare_strings (eltstring, zero,
1388                                       make_number (SCHARS (string)),
1389                                       string, zero, Qnil,
1390                                       completion_ignore_case ? Qt : Qnil),
1391               EQ (Qt, tem)))
1392         {
1393           /* Yes. */
1394           Lisp_Object regexps;
1395 
1396           /* Ignore this element if it fails to match all the regexps.  */
1397           {
1398             for (regexps = Vcompletion_regexp_list; CONSP (regexps);
1399                  regexps = XCDR (regexps))
1400               {
1401                 if (bindcount < 0) {
1402                   bindcount = SPECPDL_INDEX ();
1403                   specbind (Qcase_fold_search,
1404                             completion_ignore_case ? Qt : Qnil);
1405                 }
1406                 tem = Fstring_match (XCAR (regexps), eltstring, zero);
1407                 if (NILP (tem))
1408                   break;
1409               }
1410             if (CONSP (regexps))
1411               continue;
1412           }
1413 
1414           /* Ignore this element if there is a predicate
1415              and the predicate doesn't like it. */
1416 
1417           if (!NILP (predicate))
1418             {
1419               if (EQ (predicate, Qcommandp))
1420                 tem = Fcommandp (elt, Qnil);
1421               else
1422                 {
1423                   if (bindcount >= 0)
1424                     {
1425                       unbind_to (bindcount, Qnil);
1426                       bindcount = -1;
1427                     }
1428                   GCPRO4 (tail, string, eltstring, bestmatch);
1429                   tem = (type == hash_table
1430                          ? call2 (predicate, elt,
1431                                   HASH_VALUE (XHASH_TABLE (collection),
1432                                               index - 1))
1433                          : call1 (predicate, elt));
1434                   UNGCPRO;
1435                 }
1436               if (NILP (tem)) continue;
1437             }
1438 
1439           /* Update computation of how much all possible completions match */
1440 
1441           if (NILP (bestmatch))
1442             {
1443               matchcount = 1;
1444               bestmatch = eltstring;
1445               bestmatchsize = SCHARS (eltstring);
1446             }
1447           else
1448             {
1449               compare = min (bestmatchsize, SCHARS (eltstring));
1450               tem = Fcompare_strings (bestmatch, zero,
1451                                       make_number (compare),
1452                                       eltstring, zero,
1453                                       make_number (compare),
1454                                       completion_ignore_case ? Qt : Qnil);
1455               if (EQ (tem, Qt))
1456                 matchsize = compare;
1457               else if (XINT (tem) < 0)
1458                 matchsize = - XINT (tem) - 1;
1459               else
1460                 matchsize = XINT (tem) - 1;
1461 
1462               if (completion_ignore_case)
1463                 {
1464                   /* If this is an exact match except for case,
1465                      use it as the best match rather than one that is not an
1466                      exact match.  This way, we get the case pattern
1467                      of the actual match.  */
1468                   if ((matchsize == SCHARS (eltstring)
1469                        && matchsize < SCHARS (bestmatch))
1470                       ||
1471                       /* If there is more than one exact match ignoring case,
1472                          and one of them is exact including case,
1473                          prefer that one.  */
1474                       /* If there is no exact match ignoring case,
1475                          prefer a match that does not change the case
1476                          of the input.  */
1477                       ((matchsize == SCHARS (eltstring))
1478                        ==
1479                        (matchsize == SCHARS (bestmatch))
1480                        && (tem = Fcompare_strings (eltstring, zero,
1481                                                    make_number (SCHARS (string)),
1482                                                    string, zero,
1483                                                    Qnil,
1484                                                    Qnil),
1485                            EQ (Qt, tem))
1486                        && (tem = Fcompare_strings (bestmatch, zero,
1487                                                    make_number (SCHARS (string)),
1488                                                    string, zero,
1489                                                    Qnil,
1490                                                    Qnil),
1491                            ! EQ (Qt, tem))))
1492                     bestmatch = eltstring;
1493                 }
1494               if (bestmatchsize != SCHARS (eltstring)
1495                   || bestmatchsize != matchsize)
1496                 /* Don't count the same string multiple times.  */
1497                 matchcount++;
1498               bestmatchsize = matchsize;
1499               if (matchsize <= SCHARS (string)
1500                   /* If completion-ignore-case is non-nil, don't
1501                      short-circuit because we want to find the best
1502                      possible match *including* case differences.  */
1503                   && !completion_ignore_case
1504                   && matchcount > 1)
1505                 /* No need to look any further.  */
1506                 break;
1507             }
1508         }
1509     }
1510 
1511   if (bindcount >= 0) {
1512     unbind_to (bindcount, Qnil);
1513     bindcount = -1;
1514   }
1515 
1516   if (NILP (bestmatch))
1517     return Qnil;                /* No completions found */
1518   /* If we are ignoring case, and there is no exact match,
1519      and no additional text was supplied,
1520      don't change the case of what the user typed.  */
1521   if (completion_ignore_case && bestmatchsize == SCHARS (string)
1522       && SCHARS (bestmatch) > bestmatchsize)
1523     return minibuf_conform_representation (string, bestmatch);
1524 
1525   /* Return t if the supplied string is an exact match (counting case);
1526      it does not require any change to be made.  */
1527   if (matchcount == 1 && !NILP (Fequal (bestmatch, string)))
1528     return Qt;
1529 
1530   XSETFASTINT (zero, 0);                /* Else extract the part in which */
1531   XSETFASTINT (end, bestmatchsize);     /* all completions agree */
1532   return Fsubstring (bestmatch, zero, end);
1533 }
1534 
1535 DEFUN ("all-completions", Fall_completions, Sall_completions, 2, 4, 0,
1536        doc: /* Search for partial matches to STRING in COLLECTION.
1537 Test each of the possible completions specified by COLLECTION
1538 to see if it begins with STRING.  The possible completions may be
1539 strings or symbols.  Symbols are converted to strings before testing,
1540 see `symbol-name'.
1541 The value is a list of all the possible completions that match STRING.
1542 
1543 If COLLECTION is an alist, the keys (cars of elements) are the
1544 possible completions.  If an element is not a cons cell, then the
1545 element itself is the possible completion.
1546 If COLLECTION is a hash-table, all the keys that are strings or symbols
1547 are the possible completions.
1548 If COLLECTION is an obarray, the names of all symbols in the obarray
1549 are the possible completions.
1550 
1551 COLLECTION can also be a function to do the completion itself.
1552 It receives three arguments: the values STRING, PREDICATE and t.
1553 Whatever it returns becomes the value of `all-completions'.
1554 
1555 If optional third argument PREDICATE is non-nil,
1556 it is used to test each possible match.
1557 The match is a candidate only if PREDICATE returns non-nil.
1558 The argument given to PREDICATE is the alist element
1559 or the symbol from the obarray.  If COLLECTION is a hash-table,
1560 predicate is called with two arguments: the key and the value.
1561 Additionally to this predicate, `completion-regexp-list'
1562 is used to further constrain the set of candidates.
1563 
1564 An obsolete optional fourth argument HIDE-SPACES is still accepted for
1565 backward compatibility.  If non-nil, strings in COLLECTION that start
1566 with a space are ignored unless STRING itself starts with a space.  */)
1567      (string, collection, predicate, hide_spaces)
1568      Lisp_Object string, collection, predicate, hide_spaces;
1569 {
1570   Lisp_Object tail, elt, eltstring;
1571   Lisp_Object allmatches;
1572   int type = HASH_TABLE_P (collection) ? 3
1573     : VECTORP (collection) ? 2
1574     : NILP (collection) || (CONSP (collection)
1575                             && (!SYMBOLP (XCAR (collection))
1576                                 || NILP (XCAR (collection))));
1577   int index = 0, obsize = 0;
1578   int bindcount = -1;
1579   Lisp_Object bucket, tem, zero;
1580   struct gcpro gcpro1, gcpro2, gcpro3, gcpro4;
1581 
1582   CHECK_STRING (string);
1583   if (type == 0)
1584     return call3 (collection, string, predicate, Qt);
1585   allmatches = bucket = Qnil;
1586   zero = make_number (0);
1587 
1588   /* If COLLECTION is not a list, set TAIL just for gc pro.  */
1589   tail = collection;
1590   if (type == 2)
1591     {
1592       obsize = XVECTOR (collection)->size;
1593       bucket = XVECTOR (collection)->contents[index];
1594     }
1595 
1596   while (1)
1597     {
1598       /* Get the next element of the alist, obarray, or hash-table. */
1599       /* Exit the loop if the elements are all used up. */
1600       /* elt gets the alist element or symbol.
1601          eltstring gets the name to check as a completion. */
1602 
1603       if (type == 1)
1604         {
1605           if (!CONSP (tail))
1606             break;
1607           elt = XCAR (tail);
1608           eltstring = CONSP (elt) ? XCAR (elt) : elt;
1609           tail = XCDR (tail);
1610         }
1611       else if (type == 2)
1612         {
1613           if (!EQ (bucket, zero))
1614             {
1615               elt = bucket;
1616               eltstring = elt;
1617               if (XSYMBOL (bucket)->next)
1618                 XSETSYMBOL (bucket, XSYMBOL (bucket)->next);
1619               else
1620                 XSETFASTINT (bucket, 0);
1621             }
1622           else if (++index >= obsize)
1623             break;
1624           else
1625             {
1626               bucket = XVECTOR (collection)->contents[index];
1627               continue;
1628             }
1629         }
1630       else /* if (type == 3) */
1631         {
1632           while (index < HASH_TABLE_SIZE (XHASH_TABLE (collection))
1633                  && NILP (HASH_HASH (XHASH_TABLE (collection), index)))
1634             index++;
1635           if (index >= HASH_TABLE_SIZE (XHASH_TABLE (collection)))
1636             break;
1637           else
1638             elt = eltstring = HASH_KEY (XHASH_TABLE (collection), index++);
1639         }
1640 
1641       /* Is this element a possible completion? */
1642 
1643       if (SYMBOLP (eltstring))
1644         eltstring = Fsymbol_name (eltstring);
1645 
1646       if (STRINGP (eltstring)
1647           && SCHARS (string) <= SCHARS (eltstring)
1648           /* If HIDE_SPACES, reject alternatives that start with space
1649              unless the input starts with space.  */
1650           && (NILP (hide_spaces)
1651               || (SBYTES (string) > 0
1652                   && SREF (string, 0) == ' ')
1653               || SREF (eltstring, 0) != ' ')
1654           && (tem = Fcompare_strings (eltstring, zero,
1655                                       make_number (SCHARS (string)),
1656                                       string, zero,
1657                                       make_number (SCHARS (string)),
1658                                       completion_ignore_case ? Qt : Qnil),
1659               EQ (Qt, tem)))
1660         {
1661           /* Yes. */
1662           Lisp_Object regexps;
1663           Lisp_Object zero;
1664           XSETFASTINT (zero, 0);
1665 
1666           /* Ignore this element if it fails to match all the regexps.  */
1667           {
1668             for (regexps = Vcompletion_regexp_list; CONSP (regexps);
1669                  regexps = XCDR (regexps))
1670               {
1671                 if (bindcount < 0) {
1672                   bindcount = SPECPDL_INDEX ();
1673                   specbind (Qcase_fold_search,
1674                             completion_ignore_case ? Qt : Qnil);
1675                 }
1676                 tem = Fstring_match (XCAR (regexps), eltstring, zero);
1677                 if (NILP (tem))
1678                   break;
1679               }
1680             if (CONSP (regexps))
1681               continue;
1682           }
1683 
1684           /* Ignore this element if there is a predicate
1685              and the predicate doesn't like it. */
1686 
1687           if (!NILP (predicate))
1688             {
1689               if (EQ (predicate, Qcommandp))
1690                 tem = Fcommandp (elt, Qnil);
1691               else
1692                 {
1693                   if (bindcount >= 0) {
1694                     unbind_to (bindcount, Qnil);
1695                     bindcount = -1;
1696                   }
1697                   GCPRO4 (tail, eltstring, allmatches, string);
1698                   tem = type == 3
1699                     ? call2 (predicate, elt,
1700                              HASH_VALUE (XHASH_TABLE (collection), index - 1))
1701                     : call1 (predicate, elt);
1702                   UNGCPRO;
1703                 }
1704               if (NILP (tem)) continue;
1705             }
1706           /* Ok => put it on the list. */
1707           allmatches = Fcons (eltstring, allmatches);
1708         }
1709     }
1710 
1711   if (bindcount >= 0) {
1712     unbind_to (bindcount, Qnil);
1713     bindcount = -1;
1714   }
1715 
1716   return Fnreverse (allmatches);
1717 }
1718 
1719 DEFUN ("completing-read", Fcompleting_read, Scompleting_read, 2, 8, 0,
1720        doc: /* Read a string in the minibuffer, with completion.
1721 PROMPT is a string to prompt with; normally it ends in a colon and a space.
1722 COLLECTION can be a list of strings, an alist, an obarray or a hash table.
1723 COLLECTION can also be a function to do the completion itself.
1724 PREDICATE limits completion to a subset of COLLECTION.
1725 See `try-completion' and `all-completions' for more details
1726  on completion, COLLECTION, and PREDICATE.
1727 
1728 REQUIRE-MATCH can take the following values:
1729 - t means that the user is not allowed to exit unless
1730   the input is (or completes to) an element of COLLECTION or is null.
1731 - nil means that the user can exit with any input.
1732 - `confirm' means that the user can exit with any input, but she needs
1733   to confirm her choice if the input is not an element of COLLECTION.
1734 - `confirm-after-completion' means that the user can exit with any
1735   input, but she needs to confirm her choice if she called
1736   `minibuffer-complete' right before `minibuffer-complete-and-exit'
1737   and the input is not an element of COLLECTION.
1738 - anything else behaves like t except that typing RET does not exit if it
1739   does non-null completion.
1740 
1741 If the input is null, `completing-read' returns DEF, or the first element
1742 of the list of default values, or an empty string if DEF is nil,
1743 regardless of the value of REQUIRE-MATCH.
1744 
1745 If INITIAL-INPUT is non-nil, insert it in the minibuffer initially,
1746   with point positioned at the end.
1747   If it is (STRING . POSITION), the initial input is STRING, but point
1748   is placed at _zero-indexed_ position POSITION in STRING.  (*Note*
1749   that this is different from `read-from-minibuffer' and related
1750   functions, which use one-indexing for POSITION.)  This feature is
1751   deprecated--it is best to pass nil for INITIAL-INPUT and supply the
1752   default value DEF instead.  The user can yank the default value into
1753   the minibuffer easily using \\[next-history-element].
1754 
1755 HIST, if non-nil, specifies a history list and optionally the initial
1756   position in the list.  It can be a symbol, which is the history list
1757   variable to use, or it can be a cons cell (HISTVAR . HISTPOS).  In
1758   that case, HISTVAR is the history list variable to use, and HISTPOS
1759   is the initial position (the position in the list used by the
1760   minibuffer history commands).  For consistency, you should also
1761   specify that element of the history as the value of
1762   INITIAL-INPUT.  (This is the only case in which you should use
1763   INITIAL-INPUT instead of DEF.)  Positions are counted starting from
1764   1 at the beginning of the list.  The variable `history-length'
1765   controls the maximum length of a history list.
1766 
1767 DEF, if non-nil, is the default value or the list of default values.
1768 
1769 If INHERIT-INPUT-METHOD is non-nil, the minibuffer inherits
1770   the current input method and the setting of `enable-multibyte-characters'.
1771 
1772 Completion ignores case if the ambient value of
1773   `completion-ignore-case' is non-nil.  */)
1774      (prompt, collection, predicate, require_match, initial_input, hist, def, inherit_input_method)
1775      Lisp_Object prompt, collection, predicate, require_match, initial_input;
1776      Lisp_Object hist, def, inherit_input_method;
1777 {
1778   Lisp_Object val, histvar, histpos, position;
1779   Lisp_Object init;
1780   int pos = 0;
1781   int count = SPECPDL_INDEX ();
1782   struct gcpro gcpro1;
1783 
1784   init = initial_input;
1785   GCPRO1 (def);
1786 
1787   specbind (Qminibuffer_completion_table, collection);
1788   specbind (Qminibuffer_completion_predicate, predicate);
1789   specbind (Qminibuffer_completion_confirm,
1790             EQ (require_match, Qt) ? Qnil : require_match);
1791 
1792   position = Qnil;
1793   if (!NILP (init))
1794     {
1795       if (CONSP (init))
1796         {
1797           position = Fcdr (init);
1798           init = Fcar (init);
1799         }
1800       CHECK_STRING (init);
1801       if (!NILP (position))
1802         {
1803           CHECK_NUMBER (position);
1804           /* Convert to distance from end of input.  */
1805           pos = XINT (position) - SCHARS (init);
1806         }
1807     }
1808 
1809   if (SYMBOLP (hist))
1810     {
1811       histvar = hist;
1812       histpos = Qnil;
1813     }
1814   else
1815     {
1816       histvar = Fcar_safe (hist);
1817       histpos = Fcdr_safe (hist);
1818     }
1819   if (NILP (histvar))
1820     histvar = Qminibuffer_history;
1821   if (NILP (histpos))
1822     XSETFASTINT (histpos, 0);
1823 
1824   val = read_minibuf (NILP (require_match)
1825                       ? (NILP (Vminibuffer_completing_file_name)
1826                          || EQ (Vminibuffer_completing_file_name, Qlambda)
1827                          ? Vminibuffer_local_completion_map
1828                          : Vminibuffer_local_filename_completion_map)
1829                       : (NILP (Vminibuffer_completing_file_name)
1830                          || EQ (Vminibuffer_completing_file_name, Qlambda)
1831                          ? Vminibuffer_local_must_match_map
1832                          : Vminibuffer_local_filename_must_match_map),
1833                       init, prompt, make_number (pos), 0,
1834                       histvar, histpos, def, 0,
1835                       !NILP (inherit_input_method));
1836 
1837   if (STRINGP (val) && SCHARS (val) == 0 && ! NILP (def))
1838     val = CONSP (def) ? XCAR (def) : def;
1839 
1840   RETURN_UNGCPRO (unbind_to (count, val));
1841 }
1842 
1843 Lisp_Object Fassoc_string ();
1844 
1845 /* Test whether TXT is an exact completion.  */
1846 DEFUN ("test-completion", Ftest_completion, Stest_completion, 2, 3, 0,
1847        doc: /* Return non-nil if STRING is a valid completion.
1848 Takes the same arguments as `all-completions' and `try-completion'.
1849 If COLLECTION is a function, it is called with three arguments:
1850 the values STRING, PREDICATE and `lambda'.  */)
1851        (string, collection, predicate)
1852      Lisp_Object string, collection, predicate;
1853 {
1854   Lisp_Object regexps, tail, tem = Qnil;
1855   int i = 0;
1856 
1857   CHECK_STRING (string);
1858 
1859   if ((CONSP (collection)
1860        && (!SYMBOLP (XCAR (collection)) || NILP (XCAR (collection))))
1861       || NILP (collection))
1862     {
1863       tem = Fassoc_string (string, collection, completion_ignore_case ? Qt : Qnil);
1864       if (NILP (tem))
1865         return Qnil;
1866     }
1867   else if (VECTORP (collection))
1868     {
1869       /* Bypass intern-soft as that loses for nil.  */
1870       tem = oblookup (collection,
1871                       SDATA (string),
1872                       SCHARS (string),
1873                       SBYTES (string));
1874       if (!SYMBOLP (tem))
1875         {
1876           if (STRING_MULTIBYTE (string))
1877             string = Fstring_make_unibyte (string);
1878           else
1879             string = Fstring_make_multibyte (string);
1880 
1881           tem = oblookup (collection,
1882                           SDATA (string),
1883                           SCHARS (string),
1884                           SBYTES (string));
1885         }
1886 
1887       if (completion_ignore_case && !SYMBOLP (tem))
1888         {
1889           for (i = XVECTOR (collection)->size - 1; i >= 0; i--)
1890             {
1891               tail = XVECTOR (collection)->contents[i];
1892               if (SYMBOLP (tail))
1893                 while (1)
1894                   {
1895                     if (EQ((Fcompare_strings (string, make_number (0), Qnil,
1896                                               Fsymbol_name (tail),
1897                                               make_number (0) , Qnil, Qt)),
1898                            Qt))
1899                       {
1900                         tem = tail;
1901                         break;
1902                       }
1903                     if (XSYMBOL (tail)->next == 0)
1904                       break;
1905                     XSETSYMBOL (tail, XSYMBOL (tail)->next);
1906                   }
1907             }
1908         }
1909 
1910       if (!SYMBOLP (tem))
1911         return Qnil;
1912     }
1913   else if (HASH_TABLE_P (collection))
1914     {
1915       struct Lisp_Hash_Table *h = XHASH_TABLE (collection);
1916       i = hash_lookup (h, string, NULL);
1917       if (i >= 0)
1918         tem = HASH_KEY (h, i);
1919       else
1920         for (i = 0; i < HASH_TABLE_SIZE (h); ++i)
1921           if (!NILP (HASH_HASH (h, i)) &&
1922               EQ (Fcompare_strings (string, make_number (0), Qnil,
1923                                     HASH_KEY (h, i), make_number (0) , Qnil,
1924                                     completion_ignore_case ? Qt : Qnil),
1925                   Qt))
1926             {
1927               tem = HASH_KEY (h, i);
1928               break;
1929             }
1930       if (!STRINGP (tem))
1931         return Qnil;
1932     }
1933   else
1934     return call3 (collection, string, predicate, Qlambda);
1935 
1936   /* Reject this element if it fails to match all the regexps.  */
1937   if (CONSP (Vcompletion_regexp_list))
1938     {
1939       int count = SPECPDL_INDEX ();
1940       specbind (Qcase_fold_search, completion_ignore_case ? Qt : Qnil);
1941       for (regexps = Vcompletion_regexp_list; CONSP (regexps);
1942            regexps = XCDR (regexps))
1943         {
1944           if (NILP (Fstring_match (XCAR (regexps),
1945                                    SYMBOLP (tem) ? string : tem,
1946                                    Qnil)))
1947             return unbind_to (count, Qnil);
1948         }
1949       unbind_to (count, Qnil);
1950     }
1951 
1952   /* Finally, check the predicate.  */
1953   if (!NILP (predicate))
1954     {
1955       return HASH_TABLE_P (collection)
1956         ? call2 (predicate, tem, HASH_VALUE (XHASH_TABLE (collection), i))
1957         : call1 (predicate, tem);
1958     }
1959   else
1960     return Qt;
1961 }
1962 
1963 DEFUN ("internal-complete-buffer", Finternal_complete_buffer, Sinternal_complete_buffer, 3, 3, 0,
1964        doc: /* Perform completion on buffer names.
1965 If the argument FLAG is nil, invoke `try-completion', if it's t, invoke
1966 `all-completions', otherwise invoke `test-completion'.
1967 
1968 The arguments STRING and PREDICATE are as in `try-completion',
1969 `all-completions', and `test-completion'. */)
1970      (string, predicate, flag)
1971      Lisp_Object string, predicate, flag;
1972 {
1973   if (NILP (flag))
1974     return Ftry_completion (string, Vbuffer_alist, predicate);
1975   else if (EQ (flag, Qt))
1976     {
1977       Lisp_Object res = Fall_completions (string, Vbuffer_alist, predicate, Qnil);
1978       if (SCHARS (string) > 0)
1979         return res;
1980       else
1981         { /* Strip out internal buffers.  */
1982           Lisp_Object bufs = res;
1983           /* First, look for a non-internal buffer in `res'.  */
1984           while (CONSP (bufs) && SREF (XCAR (bufs), 0) == ' ')
1985             bufs = XCDR (bufs);
1986           if (NILP (bufs))
1987             /* All bufs in `res' are internal, so don't trip them out.  */
1988             return res;
1989           res = bufs;
1990           while (CONSP (XCDR (bufs)))
1991             if (SREF (XCAR (XCDR (bufs)), 0) == ' ')
1992               XSETCDR (bufs, XCDR (XCDR (bufs)));
1993             else
1994               bufs = XCDR (bufs);
1995           return res;
1996         }
1997     }
1998   else                          /* assume `lambda' */
1999     return Ftest_completion (string, Vbuffer_alist, predicate);
2000 }
2001 
2002 /* Like assoc but assumes KEY is a string, and ignores case if appropriate.  */
2003 
2004 DEFUN ("assoc-string", Fassoc_string, Sassoc_string, 2, 3, 0,
2005        doc: /* Like `assoc' but specifically for strings (and symbols).
2006 
2007 This returns the first element of LIST whose car matches the string or
2008 symbol KEY, or nil if no match exists.  When performing the
2009 comparison, symbols are first converted to strings, and unibyte
2010 strings to multibyte.  If the optional arg CASE-FOLD is non-nil, case
2011 is ignored.
2012 
2013 Unlike `assoc', KEY can also match an entry in LIST consisting of a
2014 single string, rather than a cons cell whose car is a string.  */)
2015        (key, list, case_fold)
2016      register Lisp_Object key;
2017      Lisp_Object list, case_fold;
2018 {
2019   register Lisp_Object tail;
2020 
2021   if (SYMBOLP (key))
2022     key = Fsymbol_name (key);
2023 
2024   for (tail = list; CONSP (tail); tail = XCDR (tail))
2025     {
2026       register Lisp_Object elt, tem, thiscar;
2027       elt = XCAR (tail);
2028       thiscar = CONSP (elt) ? XCAR (elt) : elt;
2029       if (SYMBOLP (thiscar))
2030         thiscar = Fsymbol_name (thiscar);
2031       else if (!STRINGP (thiscar))
2032         continue;
2033       tem = Fcompare_strings (thiscar, make_number (0), Qnil,
2034                               key, make_number (0), Qnil,
2035                               case_fold);
2036       if (EQ (tem, Qt))
2037         return elt;
2038       QUIT;
2039     }
2040   return Qnil;
2041 }
2042 
2043 
2044 DEFUN ("minibuffer-depth", Fminibuffer_depth, Sminibuffer_depth, 0, 0, 0,
2045        doc: /* Return current depth of activations of minibuffer, a nonnegative integer.  */)
2046      ()
2047 {
2048   return make_number (minibuf_level);
2049 }
2050 
2051 DEFUN ("minibuffer-prompt", Fminibuffer_prompt, Sminibuffer_prompt, 0, 0, 0,
2052        doc: /* Return the prompt string of the currently-active minibuffer.
2053 If no minibuffer is active, return nil.  */)
2054      ()
2055 {
2056   return Fcopy_sequence (minibuf_prompt);
2057 }
2058 
2059 
2060 void
2061 init_minibuf_once ()
2062 {
2063   Vminibuffer_list = Qnil;
2064   staticpro (&Vminibuffer_list);
2065 }
2066 
2067 void
2068 syms_of_minibuf ()
2069 {
2070   minibuf_level = 0;
2071   minibuf_prompt = Qnil;
2072   staticpro (&minibuf_prompt);
2073 
2074   minibuf_save_list = Qnil;
2075   staticpro (&minibuf_save_list);
2076 
2077   Qcompletion_ignore_case = intern_c_string ("completion-ignore-case");
2078   staticpro (&Qcompletion_ignore_case);
2079 
2080   Qread_file_name_internal = intern_c_string ("read-file-name-internal");
2081   staticpro (&Qread_file_name_internal);
2082 
2083   Qminibuffer_default = intern_c_string ("minibuffer-default");
2084   staticpro (&Qminibuffer_default);
2085   Fset (Qminibuffer_default, Qnil);
2086 
2087   Qminibuffer_completion_table = intern_c_string ("minibuffer-completion-table");
2088   staticpro (&Qminibuffer_completion_table);
2089 
2090   Qminibuffer_completion_confirm = intern_c_string ("minibuffer-completion-confirm");
2091   staticpro (&Qminibuffer_completion_confirm);
2092 
2093   Qminibuffer_completion_predicate = intern_c_string ("minibuffer-completion-predicate");
2094   staticpro (&Qminibuffer_completion_predicate);
2095 
2096   staticpro (&last_minibuf_string);
2097   last_minibuf_string = Qnil;
2098 
2099   Quser_variable_p = intern_c_string ("user-variable-p");
2100   staticpro (&Quser_variable_p);
2101 
2102   Qminibuffer_history = intern_c_string ("minibuffer-history");
2103   staticpro (&Qminibuffer_history);
2104 
2105   Qbuffer_name_history = intern_c_string ("buffer-name-history");
2106   staticpro (&Qbuffer_name_history);
2107   Fset (Qbuffer_name_history, Qnil);
2108 
2109   Qminibuffer_setup_hook = intern_c_string ("minibuffer-setup-hook");
2110   staticpro (&Qminibuffer_setup_hook);
2111 
2112   Qminibuffer_exit_hook = intern_c_string ("minibuffer-exit-hook");
2113   staticpro (&Qminibuffer_exit_hook);
2114 
2115   Qhistory_length = intern_c_string ("history-length");
2116   staticpro (&Qhistory_length);
2117 
2118   Qcurrent_input_method = intern_c_string ("current-input-method");
2119   staticpro (&Qcurrent_input_method);
2120 
2121   Qactivate_input_method = intern_c_string ("activate-input-method");
2122   staticpro (&Qactivate_input_method);
2123 
2124   Qcase_fold_search = intern_c_string ("case-fold-search");
2125   staticpro (&Qcase_fold_search);
2126 
2127   Qread_expression_history = intern_c_string ("read-expression-history");
2128   staticpro (&Qread_expression_history);
2129 
2130   DEFVAR_LISP ("read-buffer-function", &Vread_buffer_function,
2131                doc: /* If this is non-nil, `read-buffer' does its work by calling this function.  */);
2132   Vread_buffer_function = Qnil;
2133 
2134   DEFVAR_BOOL ("read-buffer-completion-ignore-case",
2135                &read_buffer_completion_ignore_case,
2136                doc: /* *Non-nil means completion ignores case when reading a buffer name.  */);
2137   read_buffer_completion_ignore_case = 0;
2138 
2139   DEFVAR_LISP ("minibuffer-setup-hook", &Vminibuffer_setup_hook,
2140                doc: /* Normal hook run just after entry to minibuffer.  */);
2141   Vminibuffer_setup_hook = Qnil;
2142 
2143   DEFVAR_LISP ("minibuffer-exit-hook", &Vminibuffer_exit_hook,
2144                doc: /* Normal hook run just after exit from minibuffer.  */);
2145   Vminibuffer_exit_hook = Qnil;
2146 
2147   DEFVAR_LISP ("history-length", &Vhistory_length,
2148                doc: /* *Maximum length for history lists before truncation takes place.
2149 A number means that length; t means infinite.  Truncation takes place
2150 just after a new element is inserted.  Setting the `history-length'
2151 property of a history variable overrides this default.  */);
2152   XSETFASTINT (Vhistory_length, 30);
2153 
2154   DEFVAR_BOOL ("history-delete-duplicates", &history_delete_duplicates,
2155                doc: /* *Non-nil means to delete duplicates in history.
2156 If set to t when adding a new history element, all previous identical
2157 elements are deleted from the history list.  */);
2158   history_delete_duplicates = 0;
2159 
2160   DEFVAR_LISP ("history-add-new-input", &Vhistory_add_new_input,
2161                doc: /* *Non-nil means to add new elements in history.
2162 If set to nil, minibuffer reading functions don't add new elements to the
2163 history list, so it is possible to do this afterwards by calling
2164 `add-to-history' explicitly.  */);
2165   Vhistory_add_new_input = Qt;
2166 
2167   DEFVAR_BOOL ("completion-ignore-case", &completion_ignore_case,
2168                doc: /* Non-nil means don't consider case significant in completion.
2169 For file-name completion, `read-file-name-completion-ignore-case'
2170 controls the behavior, rather than this variable.
2171 For buffer name completion, `read-buffer-completion-ignore-case'
2172 controls the behavior, rather than this variable.  */);
2173   completion_ignore_case = 0;
2174 
2175   DEFVAR_BOOL ("enable-recursive-minibuffers", &enable_recursive_minibuffers,
2176                doc: /* *Non-nil means to allow minibuffer commands while in the minibuffer.
2177 This variable makes a difference whenever the minibuffer window is active. */);
2178   enable_recursive_minibuffers = 0;
2179 
2180   DEFVAR_LISP ("minibuffer-completion-table", &Vminibuffer_completion_table,
2181                doc: /* Alist or obarray used for completion in the minibuffer.
2182 This becomes the ALIST argument to `try-completion' and `all-completions'.
2183 The value can also be a list of strings or a hash table.
2184 
2185 The value may alternatively be a function, which is given three arguments:
2186   STRING, the current buffer contents;
2187   PREDICATE, the predicate for filtering possible matches;
2188   CODE, which says what kind of things to do.
2189 CODE can be nil, t or `lambda':
2190   nil    -- return the best completion of STRING, or nil if there is none.
2191   t      -- return a list of all possible completions of STRING.
2192   lambda -- return t if STRING is a valid completion as it stands.  */);
2193   Vminibuffer_completion_table = Qnil;
2194 
2195   DEFVAR_LISP ("minibuffer-completion-predicate", &Vminibuffer_completion_predicate,
2196                doc: /* Within call to `completing-read', this holds the PREDICATE argument.  */);
2197   Vminibuffer_completion_predicate = Qnil;
2198 
2199   DEFVAR_LISP ("minibuffer-completion-confirm", &Vminibuffer_completion_confirm,
2200                doc: /* Whether to demand confirmation of completion before exiting minibuffer.
2201 If nil, confirmation is not required.
2202 If the value is `confirm', the user may exit with an input that is not
2203  a valid completion alternative, but Emacs asks for confirmation.
2204 If the value is `confirm-after-completion', the user may exit with an
2205  input that is not a valid completion alternative, but Emacs asks for
2206  confirmation if the user submitted the input right after any of the
2207  completion commands listed in `minibuffer-confirm-exit-commands'.  */);
2208   Vminibuffer_completion_confirm = Qnil;
2209 
2210   DEFVAR_LISP ("minibuffer-completing-file-name",
2211                &Vminibuffer_completing_file_name,
2212                doc: /* Non-nil means completing file names.  */);
2213   Vminibuffer_completing_file_name = Qnil;
2214 
2215   DEFVAR_LISP ("minibuffer-help-form", &Vminibuffer_help_form,
2216                doc: /* Value that `help-form' takes on inside the minibuffer.  */);
2217   Vminibuffer_help_form = Qnil;
2218 
2219   DEFVAR_LISP ("minibuffer-history-variable", &Vminibuffer_history_variable,
2220                doc: /* History list symbol to add minibuffer values to.
2221 Each string of minibuffer input, as it appears on exit from the minibuffer,
2222 is added with
2223   (set minibuffer-history-variable
2224   (cons STRING (symbol-value minibuffer-history-variable)))  */);
2225   XSETFASTINT (Vminibuffer_history_variable, 0);
2226 
2227   DEFVAR_LISP ("minibuffer-history-position", &Vminibuffer_history_position,
2228                doc: /* Current position of redoing in the history list.  */);
2229   Vminibuffer_history_position = Qnil;
2230 
2231   DEFVAR_BOOL ("minibuffer-auto-raise", &minibuffer_auto_raise,
2232                doc: /* *Non-nil means entering the minibuffer raises the minibuffer's frame.
2233 Some uses of the echo area also raise that frame (since they use it too).  */);
2234   minibuffer_auto_raise = 0;
2235 
2236   DEFVAR_LISP ("completion-regexp-list", &Vcompletion_regexp_list,
2237                doc: /* List of regexps that should restrict possible completions.
2238 The basic completion functions only consider a completion acceptable
2239 if it matches all regular expressions in this list, with
2240 `case-fold-search' bound to the value of `completion-ignore-case'.
2241 See Info node `(elisp)Basic Completion', for a description of these
2242 functions.  */);
2243   Vcompletion_regexp_list = Qnil;
2244 
2245   DEFVAR_BOOL ("minibuffer-allow-text-properties",
2246                &minibuffer_allow_text_properties,
2247                doc: /* Non-nil means `read-from-minibuffer' should not discard text properties.
2248 This also affects `read-string', but it does not affect `read-minibuffer',
2249 `read-no-blanks-input', or any of the functions that do minibuffer input
2250 with completion; they always discard text properties.  */);
2251   minibuffer_allow_text_properties = 0;
2252 
2253   DEFVAR_LISP ("minibuffer-prompt-properties", &Vminibuffer_prompt_properties,
2254                doc: /* Text properties that are added to minibuffer prompts.
2255 These are in addition to the basic `field' property, and stickiness
2256 properties.  */);
2257   /* We use `intern' here instead of Qread_only to avoid
2258      initialization-order problems.  */
2259   Vminibuffer_prompt_properties
2260     = Fcons (intern_c_string ("read-only"), Fcons (Qt, Qnil));
2261 
2262   DEFVAR_LISP ("read-expression-map", &Vread_expression_map,
2263                doc: /* Minibuffer keymap used for reading Lisp expressions.  */);
2264   Vread_expression_map = Qnil;
2265 
2266   defsubr (&Sset_minibuffer_window);
2267   defsubr (&Sread_from_minibuffer);
2268   defsubr (&Seval_minibuffer);
2269   defsubr (&Sread_minibuffer);
2270   defsubr (&Sread_string);
2271   defsubr (&Sread_command);
2272   defsubr (&Sread_variable);
2273   defsubr (&Sinternal_complete_buffer);
2274   defsubr (&Sread_buffer);
2275   defsubr (&Sread_no_blanks_input);
2276   defsubr (&Sminibuffer_depth);
2277   defsubr (&Sminibuffer_prompt);
2278 
2279   defsubr (&Sminibufferp);
2280   defsubr (&Sminibuffer_prompt_end);
2281   defsubr (&Sminibuffer_contents);
2282   defsubr (&Sminibuffer_contents_no_properties);
2283   defsubr (&Sminibuffer_completion_contents);
2284 
2285   defsubr (&Stry_completion);
2286   defsubr (&Sall_completions);
2287   defsubr (&Stest_completion);
2288   defsubr (&Sassoc_string);
2289   defsubr (&Scompleting_read);
2290 }
2291 
2292 /* arch-tag: 8f69b601-fba3-484c-a6dd-ceaee54a7a73
2293    (do not change this comment) */