File:  [ELWIX - Embedded LightWeight unIX -] / embedaddon / readline / complete.c
Revision 1.1.1.1 (vendor branch): download - view: text, annotated - select for diffs - revision graph
Wed Jul 30 08:16:45 2014 UTC (9 years, 11 months ago) by misho
Branches: readline, MAIN
CVS tags: v6_3p10_cross, v6_3p10, v6_3, p6, HEAD
readline 6.3

    1: /* complete.c -- filename completion for readline. */
    2: 
    3: /* Copyright (C) 1987-2012 Free Software Foundation, Inc.
    4: 
    5:    This file is part of the GNU Readline Library (Readline), a library
    6:    for reading lines of text with interactive input and history editing.
    7: 
    8:    Readline 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:    Readline 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 Readline.  If not, see <http://www.gnu.org/licenses/>.
   20: */
   21: 
   22: #define READLINE_LIBRARY
   23: 
   24: #if defined (HAVE_CONFIG_H)
   25: #  include <config.h>
   26: #endif
   27: 
   28: #include <sys/types.h>
   29: #include <fcntl.h>
   30: #if defined (HAVE_SYS_FILE_H)
   31: #  include <sys/file.h>
   32: #endif
   33: 
   34: #include <signal.h>
   35: 
   36: #if defined (HAVE_UNISTD_H)
   37: #  include <unistd.h>
   38: #endif /* HAVE_UNISTD_H */
   39: 
   40: #if defined (HAVE_STDLIB_H)
   41: #  include <stdlib.h>
   42: #else
   43: #  include "ansi_stdlib.h"
   44: #endif /* HAVE_STDLIB_H */
   45: 
   46: #include <stdio.h>
   47: 
   48: #include <errno.h>
   49: #if !defined (errno)
   50: extern int errno;
   51: #endif /* !errno */
   52: 
   53: #if defined (HAVE_PWD_H)
   54: #include <pwd.h>
   55: #endif
   56: 
   57: #include "posixdir.h"
   58: #include "posixstat.h"
   59: 
   60: /* System-specific feature definitions and include files. */
   61: #include "rldefs.h"
   62: #include "rlmbutil.h"
   63: 
   64: /* Some standard library routines. */
   65: #include "readline.h"
   66: #include "xmalloc.h"
   67: #include "rlprivate.h"
   68: 
   69: #if defined (COLOR_SUPPORT)
   70: #  include "colors.h"
   71: #endif
   72: 
   73: #ifdef __STDC__
   74: typedef int QSFUNC (const void *, const void *);
   75: #else
   76: typedef int QSFUNC ();
   77: #endif
   78: 
   79: #ifdef HAVE_LSTAT
   80: #  define LSTAT lstat
   81: #else
   82: #  define LSTAT stat
   83: #endif
   84: 
   85: /* Unix version of a hidden file.  Could be different on other systems. */
   86: #define HIDDEN_FILE(fname)	((fname)[0] == '.')
   87: 
   88: /* Most systems don't declare getpwent in <pwd.h> if _POSIX_SOURCE is
   89:    defined. */
   90: #if defined (HAVE_GETPWENT) && (!defined (HAVE_GETPW_DECLS) || defined (_POSIX_SOURCE))
   91: extern struct passwd *getpwent PARAMS((void));
   92: #endif /* HAVE_GETPWENT && (!HAVE_GETPW_DECLS || _POSIX_SOURCE) */
   93: 
   94: /* If non-zero, then this is the address of a function to call when
   95:    completing a word would normally display the list of possible matches.
   96:    This function is called instead of actually doing the display.
   97:    It takes three arguments: (char **matches, int num_matches, int max_length)
   98:    where MATCHES is the array of strings that matched, NUM_MATCHES is the
   99:    number of strings in that array, and MAX_LENGTH is the length of the
  100:    longest string in that array. */
  101: rl_compdisp_func_t *rl_completion_display_matches_hook = (rl_compdisp_func_t *)NULL;
  102: 
  103: #if defined (VISIBLE_STATS) || defined (COLOR_SUPPORT)
  104: #  if !defined (X_OK)
  105: #    define X_OK 1
  106: #  endif
  107: #endif
  108: 
  109: #if defined (VISIBLE_STATS)
  110: static int stat_char PARAMS((char *));
  111: #endif
  112: 
  113: #if defined (COLOR_SUPPORT)
  114: static int colored_stat_start PARAMS((char *));
  115: static void colored_stat_end PARAMS((void));
  116: #endif
  117: 
  118: static int path_isdir PARAMS((const char *));
  119: 
  120: static char *rl_quote_filename PARAMS((char *, int, char *));
  121: 
  122: static void _rl_complete_sigcleanup PARAMS((int, void *));
  123: 
  124: static void set_completion_defaults PARAMS((int));
  125: static int get_y_or_n PARAMS((int));
  126: static int _rl_internal_pager PARAMS((int));
  127: static char *printable_part PARAMS((char *));
  128: static int fnwidth PARAMS((const char *));
  129: static int fnprint PARAMS((const char *, int));
  130: static int print_filename PARAMS((char *, char *, int));
  131: 
  132: static char **gen_completion_matches PARAMS((char *, int, int, rl_compentry_func_t *, int, int));
  133: 
  134: static char **remove_duplicate_matches PARAMS((char **));
  135: static void insert_match PARAMS((char *, int, int, char *));
  136: static int append_to_match PARAMS((char *, int, int, int));
  137: static void insert_all_matches PARAMS((char **, int, char *));
  138: static int complete_fncmp PARAMS((const char *, int, const char *, int));
  139: static void display_matches PARAMS((char **));
  140: static int compute_lcd_of_matches PARAMS((char **, int, const char *));
  141: static int postprocess_matches PARAMS((char ***, int));
  142: static int complete_get_screenwidth PARAMS((void));
  143: 
  144: static char *make_quoted_replacement PARAMS((char *, int, char *));
  145: 
  146: /* **************************************************************** */
  147: /*								    */
  148: /*	Completion matching, from readline's point of view.	    */
  149: /*								    */
  150: /* **************************************************************** */
  151: 
  152: /* Variables known only to the readline library. */
  153: 
  154: /* If non-zero, non-unique completions always show the list of matches. */
  155: int _rl_complete_show_all = 0;
  156: 
  157: /* If non-zero, non-unique completions show the list of matches, unless it
  158:    is not possible to do partial completion and modify the line. */
  159: int _rl_complete_show_unmodified = 0;
  160: 
  161: /* If non-zero, completed directory names have a slash appended. */
  162: int _rl_complete_mark_directories = 1;
  163: 
  164: /* If non-zero, the symlinked directory completion behavior introduced in
  165:    readline-4.2a is disabled, and symlinks that point to directories have
  166:    a slash appended (subject to the value of _rl_complete_mark_directories).
  167:    This is user-settable via the mark-symlinked-directories variable. */
  168: int _rl_complete_mark_symlink_dirs = 0;
  169: 
  170: /* If non-zero, completions are printed horizontally in alphabetical order,
  171:    like `ls -x'. */
  172: int _rl_print_completions_horizontally;
  173: 
  174: /* Non-zero means that case is not significant in filename completion. */
  175: #if defined (__MSDOS__) && !defined (__DJGPP__)
  176: int _rl_completion_case_fold = 1;
  177: #else
  178: int _rl_completion_case_fold = 0;
  179: #endif
  180: 
  181: /* Non-zero means that `-' and `_' are equivalent when comparing filenames
  182:   for completion. */
  183: int _rl_completion_case_map = 0;
  184: 
  185: /* If zero, don't match hidden files (filenames beginning with a `.' on
  186:    Unix) when doing filename completion. */
  187: int _rl_match_hidden_files = 1;
  188: 
  189: /* Length in characters of a common prefix replaced with an ellipsis (`...')
  190:    when displaying completion matches.  Matches whose printable portion has
  191:    more than this number of displaying characters in common will have the common
  192:    display prefix replaced with an ellipsis. */
  193: int _rl_completion_prefix_display_length = 0;
  194: 
  195: /* The readline-private number of screen columns to use when displaying
  196:    matches.  If < 0 or > _rl_screenwidth, it is ignored. */
  197: int _rl_completion_columns = -1;
  198: 
  199: /* Global variables available to applications using readline. */
  200: 
  201: #if defined (VISIBLE_STATS)
  202: /* Non-zero means add an additional character to each filename displayed
  203:    during listing completion iff rl_filename_completion_desired which helps
  204:    to indicate the type of file being listed. */
  205: int rl_visible_stats = 0;
  206: #endif /* VISIBLE_STATS */
  207: 
  208: #if defined (COLOR_SUPPORT)
  209: /* Non-zero means to use colors to indicate file type when listing possible
  210:    completions.  The colors used are taken from $LS_COLORS, if set. */
  211: int _rl_colored_stats = 0;
  212: #endif
  213: 
  214: /* If non-zero, when completing in the middle of a word, don't insert
  215:    characters from the match that match characters following point in
  216:    the word.  This means, for instance, completing when the cursor is
  217:    after the `e' in `Makefile' won't result in `Makefilefile'. */
  218: int _rl_skip_completed_text = 0;
  219: 
  220: /* If non-zero, menu completion displays the common prefix first in the
  221:    cycle of possible completions instead of the last. */
  222: int _rl_menu_complete_prefix_first = 0;
  223: 
  224: /* If non-zero, then this is the address of a function to call when
  225:    completing on a directory name.  The function is called with
  226:    the address of a string (the current directory name) as an arg. */
  227: rl_icppfunc_t *rl_directory_completion_hook = (rl_icppfunc_t *)NULL;
  228: 
  229: rl_icppfunc_t *rl_directory_rewrite_hook = (rl_icppfunc_t *)NULL;
  230: 
  231: rl_icppfunc_t *rl_filename_stat_hook = (rl_icppfunc_t *)NULL;
  232: 
  233: /* If non-zero, this is the address of a function to call when reading
  234:    directory entries from the filesystem for completion and comparing
  235:    them to the partial word to be completed.  The function should
  236:    either return its first argument (if no conversion takes place) or
  237:    newly-allocated memory.  This can, for instance, convert filenames
  238:    between character sets for comparison against what's typed at the
  239:    keyboard.  The returned value is what is added to the list of
  240:    matches.  The second argument is the length of the filename to be
  241:    converted. */
  242: rl_dequote_func_t *rl_filename_rewrite_hook = (rl_dequote_func_t *)NULL;
  243: 
  244: /* Non-zero means readline completion functions perform tilde expansion. */
  245: int rl_complete_with_tilde_expansion = 0;
  246: 
  247: /* Pointer to the generator function for completion_matches ().
  248:    NULL means to use rl_filename_completion_function (), the default filename
  249:    completer. */
  250: rl_compentry_func_t *rl_completion_entry_function = (rl_compentry_func_t *)NULL;
  251: 
  252: /* Pointer to generator function for rl_menu_complete ().  NULL means to use
  253:    *rl_completion_entry_function (see above). */
  254: rl_compentry_func_t *rl_menu_completion_entry_function = (rl_compentry_func_t *)NULL;
  255: 
  256: /* Pointer to alternative function to create matches.
  257:    Function is called with TEXT, START, and END.
  258:    START and END are indices in RL_LINE_BUFFER saying what the boundaries
  259:    of TEXT are.
  260:    If this function exists and returns NULL then call the value of
  261:    rl_completion_entry_function to try to match, otherwise use the
  262:    array of strings returned. */
  263: rl_completion_func_t *rl_attempted_completion_function = (rl_completion_func_t *)NULL;
  264: 
  265: /* Non-zero means to suppress normal filename completion after the
  266:    user-specified completion function has been called. */
  267: int rl_attempted_completion_over = 0;
  268: 
  269: /* Set to a character indicating the type of completion being performed
  270:    by rl_complete_internal, available for use by application completion
  271:    functions. */
  272: int rl_completion_type = 0;
  273: 
  274: /* Up to this many items will be displayed in response to a
  275:    possible-completions call.  After that, we ask the user if
  276:    she is sure she wants to see them all.  A negative value means
  277:    don't ask. */
  278: int rl_completion_query_items = 100;
  279: 
  280: int _rl_page_completions = 1;
  281: 
  282: /* The basic list of characters that signal a break between words for the
  283:    completer routine.  The contents of this variable is what breaks words
  284:    in the shell, i.e. " \t\n\"\\'`@$><=" */
  285: const char *rl_basic_word_break_characters = " \t\n\"\\'`@$><=;|&{("; /* }) */
  286: 
  287: /* List of basic quoting characters. */
  288: const char *rl_basic_quote_characters = "\"'";
  289: 
  290: /* The list of characters that signal a break between words for
  291:    rl_complete_internal.  The default list is the contents of
  292:    rl_basic_word_break_characters.  */
  293: /*const*/ char *rl_completer_word_break_characters = (/*const*/ char *)NULL;
  294: 
  295: /* Hook function to allow an application to set the completion word
  296:    break characters before readline breaks up the line.  Allows
  297:    position-dependent word break characters. */
  298: rl_cpvfunc_t *rl_completion_word_break_hook = (rl_cpvfunc_t *)NULL;
  299: 
  300: /* List of characters which can be used to quote a substring of the line.
  301:    Completion occurs on the entire substring, and within the substring
  302:    rl_completer_word_break_characters are treated as any other character,
  303:    unless they also appear within this list. */
  304: const char *rl_completer_quote_characters = (const char *)NULL;
  305: 
  306: /* List of characters that should be quoted in filenames by the completer. */
  307: const char *rl_filename_quote_characters = (const char *)NULL;
  308: 
  309: /* List of characters that are word break characters, but should be left
  310:    in TEXT when it is passed to the completion function.  The shell uses
  311:    this to help determine what kind of completing to do. */
  312: const char *rl_special_prefixes = (const char *)NULL;
  313: 
  314: /* If non-zero, then disallow duplicates in the matches. */
  315: int rl_ignore_completion_duplicates = 1;
  316: 
  317: /* Non-zero means that the results of the matches are to be treated
  318:    as filenames.  This is ALWAYS zero on entry, and can only be changed
  319:    within a completion entry finder function. */
  320: int rl_filename_completion_desired = 0;
  321: 
  322: /* Non-zero means that the results of the matches are to be quoted using
  323:    double quotes (or an application-specific quoting mechanism) if the
  324:    filename contains any characters in rl_filename_quote_chars.  This is
  325:    ALWAYS non-zero on entry, and can only be changed within a completion
  326:    entry finder function. */
  327: int rl_filename_quoting_desired = 1;
  328: 
  329: /* This function, if defined, is called by the completer when real
  330:    filename completion is done, after all the matching names have been
  331:    generated. It is passed a (char**) known as matches in the code below.
  332:    It consists of a NULL-terminated array of pointers to potential
  333:    matching strings.  The 1st element (matches[0]) is the maximal
  334:    substring that is common to all matches. This function can re-arrange
  335:    the list of matches as required, but all elements of the array must be
  336:    free()'d if they are deleted. The main intent of this function is
  337:    to implement FIGNORE a la SunOS csh. */
  338: rl_compignore_func_t *rl_ignore_some_completions_function = (rl_compignore_func_t *)NULL;
  339: 
  340: /* Set to a function to quote a filename in an application-specific fashion.
  341:    Called with the text to quote, the type of match found (single or multiple)
  342:    and a pointer to the quoting character to be used, which the function can
  343:    reset if desired. */
  344: rl_quote_func_t *rl_filename_quoting_function = rl_quote_filename;
  345:          
  346: /* Function to call to remove quoting characters from a filename.  Called
  347:    before completion is attempted, so the embedded quotes do not interfere
  348:    with matching names in the file system.  Readline doesn't do anything
  349:    with this; it's set only by applications. */
  350: rl_dequote_func_t *rl_filename_dequoting_function = (rl_dequote_func_t *)NULL;
  351: 
  352: /* Function to call to decide whether or not a word break character is
  353:    quoted.  If a character is quoted, it does not break words for the
  354:    completer. */
  355: rl_linebuf_func_t *rl_char_is_quoted_p = (rl_linebuf_func_t *)NULL;
  356: 
  357: /* If non-zero, the completion functions don't append anything except a
  358:    possible closing quote.  This is set to 0 by rl_complete_internal and
  359:    may be changed by an application-specific completion function. */
  360: int rl_completion_suppress_append = 0;
  361: 
  362: /* Character appended to completed words when at the end of the line.  The
  363:    default is a space. */
  364: int rl_completion_append_character = ' ';
  365: 
  366: /* If non-zero, the completion functions don't append any closing quote.
  367:    This is set to 0 by rl_complete_internal and may be changed by an
  368:    application-specific completion function. */
  369: int rl_completion_suppress_quote = 0;
  370: 
  371: /* Set to any quote character readline thinks it finds before any application
  372:    completion function is called. */
  373: int rl_completion_quote_character;
  374: 
  375: /* Set to a non-zero value if readline found quoting anywhere in the word to
  376:    be completed; set before any application completion function is called. */
  377: int rl_completion_found_quote;
  378: 
  379: /* If non-zero, a slash will be appended to completed filenames that are
  380:    symbolic links to directory names, subject to the value of the
  381:    mark-directories variable (which is user-settable).  This exists so
  382:    that application completion functions can override the user's preference
  383:    (set via the mark-symlinked-directories variable) if appropriate.
  384:    It's set to the value of _rl_complete_mark_symlink_dirs in
  385:    rl_complete_internal before any application-specific completion
  386:    function is called, so without that function doing anything, the user's
  387:    preferences are honored. */
  388: int rl_completion_mark_symlink_dirs;
  389: 
  390: /* If non-zero, inhibit completion (temporarily). */
  391: int rl_inhibit_completion;
  392: 
  393: /* Set to the last key used to invoke one of the completion functions */
  394: int rl_completion_invoking_key;
  395: 
  396: /* If non-zero, sort the completion matches.  On by default. */
  397: int rl_sort_completion_matches = 1;
  398: 
  399: /* Variables local to this file. */
  400: 
  401: /* Local variable states what happened during the last completion attempt. */
  402: static int completion_changed_buffer;
  403: 
  404: /* The result of the query to the user about displaying completion matches */
  405: static int completion_y_or_n;
  406: 
  407: /*************************************/
  408: /*				     */
  409: /*    Bindable completion functions  */
  410: /*				     */
  411: /*************************************/
  412: 
  413: /* Complete the word at or before point.  You have supplied the function
  414:    that does the initial simple matching selection algorithm (see
  415:    rl_completion_matches ()).  The default is to do filename completion. */
  416: int
  417: rl_complete (ignore, invoking_key)
  418:      int ignore, invoking_key;
  419: {
  420:   rl_completion_invoking_key = invoking_key;
  421: 
  422:   if (rl_inhibit_completion)
  423:     return (_rl_insert_char (ignore, invoking_key));
  424:   else if (rl_last_func == rl_complete && !completion_changed_buffer)
  425:     return (rl_complete_internal ('?'));
  426:   else if (_rl_complete_show_all)
  427:     return (rl_complete_internal ('!'));
  428:   else if (_rl_complete_show_unmodified)
  429:     return (rl_complete_internal ('@'));
  430:   else
  431:     return (rl_complete_internal (TAB));
  432: }
  433: 
  434: /* List the possible completions.  See description of rl_complete (). */
  435: int
  436: rl_possible_completions (ignore, invoking_key)
  437:      int ignore, invoking_key;
  438: {
  439:   rl_completion_invoking_key = invoking_key;
  440:   return (rl_complete_internal ('?'));
  441: }
  442: 
  443: int
  444: rl_insert_completions (ignore, invoking_key)
  445:      int ignore, invoking_key;
  446: {
  447:   rl_completion_invoking_key = invoking_key;
  448:   return (rl_complete_internal ('*'));
  449: }
  450: 
  451: /* Return the correct value to pass to rl_complete_internal performing
  452:    the same tests as rl_complete.  This allows consecutive calls to an
  453:    application's completion function to list possible completions and for
  454:    an application-specific completion function to honor the
  455:    show-all-if-ambiguous readline variable. */
  456: int
  457: rl_completion_mode (cfunc)
  458:      rl_command_func_t *cfunc;
  459: {
  460:   if (rl_last_func == cfunc && !completion_changed_buffer)
  461:     return '?';
  462:   else if (_rl_complete_show_all)
  463:     return '!';
  464:   else if (_rl_complete_show_unmodified)
  465:     return '@';
  466:   else
  467:     return TAB;
  468: }
  469: 
  470: /************************************/
  471: /*				    */
  472: /*    Completion utility functions  */
  473: /*				    */
  474: /************************************/
  475: 
  476: /* Reset readline state on a signal or other event. */
  477: void
  478: _rl_reset_completion_state ()
  479: {
  480:   rl_completion_found_quote = 0;
  481:   rl_completion_quote_character = 0;
  482: }
  483: 
  484: static void
  485: _rl_complete_sigcleanup (sig, ptr)
  486:      int sig;
  487:      void *ptr;
  488: {
  489:   if (sig == SIGINT)	/* XXX - for now */
  490:     _rl_free_match_list ((char **)ptr);
  491: }
  492: 
  493: /* Set default values for readline word completion.  These are the variables
  494:    that application completion functions can change or inspect. */
  495: static void
  496: set_completion_defaults (what_to_do)
  497:      int what_to_do;
  498: {
  499:   /* Only the completion entry function can change these. */
  500:   rl_filename_completion_desired = 0;
  501:   rl_filename_quoting_desired = 1;
  502:   rl_completion_type = what_to_do;
  503:   rl_completion_suppress_append = rl_completion_suppress_quote = 0;
  504:   rl_completion_append_character = ' ';
  505: 
  506:   /* The completion entry function may optionally change this. */
  507:   rl_completion_mark_symlink_dirs = _rl_complete_mark_symlink_dirs;
  508: }
  509: 
  510: /* The user must press "y" or "n". Non-zero return means "y" pressed. */
  511: static int
  512: get_y_or_n (for_pager)
  513:      int for_pager;
  514: {
  515:   int c;
  516: 
  517:   /* For now, disable pager in callback mode, until we later convert to state
  518:      driven functions.  Have to wait until next major version to add new
  519:      state definition, since it will change value of RL_STATE_DONE. */
  520: #if defined (READLINE_CALLBACKS)
  521:   if (RL_ISSTATE (RL_STATE_CALLBACK))
  522:     return 1;
  523: #endif
  524: 
  525:   for (;;)
  526:     {
  527:       RL_SETSTATE(RL_STATE_MOREINPUT);
  528:       c = rl_read_key ();
  529:       RL_UNSETSTATE(RL_STATE_MOREINPUT);
  530: 
  531:       if (c == 'y' || c == 'Y' || c == ' ')
  532: 	return (1);
  533:       if (c == 'n' || c == 'N' || c == RUBOUT)
  534: 	return (0);
  535:       if (c == ABORT_CHAR || c < 0)
  536: 	_rl_abort_internal ();
  537:       if (for_pager && (c == NEWLINE || c == RETURN))
  538: 	return (2);
  539:       if (for_pager && (c == 'q' || c == 'Q'))
  540: 	return (0);
  541:       rl_ding ();
  542:     }
  543: }
  544: 
  545: static int
  546: _rl_internal_pager (lines)
  547:      int lines;
  548: {
  549:   int i;
  550: 
  551:   fprintf (rl_outstream, "--More--");
  552:   fflush (rl_outstream);
  553:   i = get_y_or_n (1);
  554:   _rl_erase_entire_line ();
  555:   if (i == 0)
  556:     return -1;
  557:   else if (i == 2)
  558:     return (lines - 1);
  559:   else
  560:     return 0;
  561: }
  562: 
  563: static int
  564: path_isdir (filename)
  565:      const char *filename;
  566: {
  567:   struct stat finfo;
  568: 
  569:   return (stat (filename, &finfo) == 0 && S_ISDIR (finfo.st_mode));
  570: }
  571: 
  572: #if defined (VISIBLE_STATS)
  573: /* Return the character which best describes FILENAME.
  574:      `@' for symbolic links
  575:      `/' for directories
  576:      `*' for executables
  577:      `=' for sockets
  578:      `|' for FIFOs
  579:      `%' for character special devices
  580:      `#' for block special devices */
  581: static int
  582: stat_char (filename)
  583:      char *filename;
  584: {
  585:   struct stat finfo;
  586:   int character, r;
  587:   char *f;
  588:   const char *fn;
  589: 
  590:   /* Short-circuit a //server on cygwin, since that will always behave as
  591:      a directory. */
  592: #if __CYGWIN__
  593:   if (filename[0] == '/' && filename[1] == '/' && strchr (filename+2, '/') == 0)
  594:     return '/';
  595: #endif
  596: 
  597:   f = 0;
  598:   if (rl_filename_stat_hook)
  599:     {
  600:       f = savestring (filename);
  601:       (*rl_filename_stat_hook) (&f);
  602:       fn = f;
  603:     }
  604:   else
  605:     fn = filename;
  606:     
  607: #if defined (HAVE_LSTAT) && defined (S_ISLNK)
  608:   r = lstat (fn, &finfo);
  609: #else
  610:   r = stat (fn, &finfo);
  611: #endif
  612: 
  613:   if (r == -1)
  614:     return (0);
  615: 
  616:   character = 0;
  617:   if (S_ISDIR (finfo.st_mode))
  618:     character = '/';
  619: #if defined (S_ISCHR)
  620:   else if (S_ISCHR (finfo.st_mode))
  621:     character = '%';
  622: #endif /* S_ISCHR */
  623: #if defined (S_ISBLK)
  624:   else if (S_ISBLK (finfo.st_mode))
  625:     character = '#';
  626: #endif /* S_ISBLK */
  627: #if defined (S_ISLNK)
  628:   else if (S_ISLNK (finfo.st_mode))
  629:     character = '@';
  630: #endif /* S_ISLNK */
  631: #if defined (S_ISSOCK)
  632:   else if (S_ISSOCK (finfo.st_mode))
  633:     character = '=';
  634: #endif /* S_ISSOCK */
  635: #if defined (S_ISFIFO)
  636:   else if (S_ISFIFO (finfo.st_mode))
  637:     character = '|';
  638: #endif
  639:   else if (S_ISREG (finfo.st_mode))
  640:     {
  641:       if (access (filename, X_OK) == 0)
  642: 	character = '*';
  643:     }
  644: 
  645:   free (f);
  646:   return (character);
  647: }
  648: #endif /* VISIBLE_STATS */
  649: 
  650: #if defined (COLOR_SUPPORT)
  651: static int
  652: colored_stat_start (filename)
  653:      char *filename;
  654: {
  655:   _rl_set_normal_color ();
  656:   return (_rl_print_color_indicator (filename));
  657: }
  658: 
  659: static void
  660: colored_stat_end ()
  661: {
  662:   _rl_prep_non_filename_text ();
  663:   _rl_put_indicator (&_rl_color_indicator[C_CLR_TO_EOL]);
  664: }
  665: #endif
  666: 
  667: /* Return the portion of PATHNAME that should be output when listing
  668:    possible completions.  If we are hacking filename completion, we
  669:    are only interested in the basename, the portion following the
  670:    final slash.  Otherwise, we return what we were passed.  Since
  671:    printing empty strings is not very informative, if we're doing
  672:    filename completion, and the basename is the empty string, we look
  673:    for the previous slash and return the portion following that.  If
  674:    there's no previous slash, we just return what we were passed. */
  675: static char *
  676: printable_part (pathname)
  677:       char *pathname;
  678: {
  679:   char *temp, *x;
  680: 
  681:   if (rl_filename_completion_desired == 0)	/* don't need to do anything */
  682:     return (pathname);
  683: 
  684:   temp = strrchr (pathname, '/');
  685: #if defined (__MSDOS__)
  686:   if (temp == 0 && ISALPHA ((unsigned char)pathname[0]) && pathname[1] == ':')
  687:     temp = pathname + 1;
  688: #endif
  689: 
  690:   if (temp == 0 || *temp == '\0')
  691:     return (pathname);
  692:   /* If the basename is NULL, we might have a pathname like '/usr/src/'.
  693:      Look for a previous slash and, if one is found, return the portion
  694:      following that slash.  If there's no previous slash, just return the
  695:      pathname we were passed. */
  696:   else if (temp[1] == '\0')
  697:     {
  698:       for (x = temp - 1; x > pathname; x--)
  699:         if (*x == '/')
  700:           break;
  701:       return ((*x == '/') ? x + 1 : pathname);
  702:     }
  703:   else
  704:     return ++temp;
  705: }
  706: 
  707: /* Compute width of STRING when displayed on screen by print_filename */
  708: static int
  709: fnwidth (string)
  710:      const char *string;
  711: {
  712:   int width, pos;
  713: #if defined (HANDLE_MULTIBYTE)
  714:   mbstate_t ps;
  715:   int left, w;
  716:   size_t clen;
  717:   wchar_t wc;
  718: 
  719:   left = strlen (string) + 1;
  720:   memset (&ps, 0, sizeof (mbstate_t));
  721: #endif
  722: 
  723:   width = pos = 0;
  724:   while (string[pos])
  725:     {
  726:       if (CTRL_CHAR (string[pos]) || string[pos] == RUBOUT)
  727: 	{
  728: 	  width += 2;
  729: 	  pos++;
  730: 	}
  731:       else
  732: 	{
  733: #if defined (HANDLE_MULTIBYTE)
  734: 	  clen = mbrtowc (&wc, string + pos, left - pos, &ps);
  735: 	  if (MB_INVALIDCH (clen))
  736: 	    {
  737: 	      width++;
  738: 	      pos++;
  739: 	      memset (&ps, 0, sizeof (mbstate_t));
  740: 	    }
  741: 	  else if (MB_NULLWCH (clen))
  742: 	    break;
  743: 	  else
  744: 	    {
  745: 	      pos += clen;
  746: 	      w = WCWIDTH (wc);
  747: 	      width += (w >= 0) ? w : 1;
  748: 	    }
  749: #else
  750: 	  width++;
  751: 	  pos++;
  752: #endif
  753: 	}
  754:     }
  755: 
  756:   return width;
  757: }
  758: 
  759: #define ELLIPSIS_LEN	3
  760: 
  761: static int
  762: fnprint (to_print, prefix_bytes)
  763:      const char *to_print;
  764:      int prefix_bytes;
  765: {
  766:   int printed_len, w;
  767:   const char *s;
  768: #if defined (HANDLE_MULTIBYTE)
  769:   mbstate_t ps;
  770:   const char *end;
  771:   size_t tlen;
  772:   int width;
  773:   wchar_t wc;
  774: 
  775:   end = to_print + strlen (to_print) + 1;
  776:   memset (&ps, 0, sizeof (mbstate_t));
  777: #endif
  778: 
  779:   printed_len = 0;
  780: 
  781:   /* Don't print only the ellipsis if the common prefix is one of the
  782:      possible completions */
  783:   if (to_print[prefix_bytes] == '\0')
  784:     prefix_bytes = 0;
  785: 
  786:   if (prefix_bytes)
  787:     {
  788:       char ellipsis;
  789: 
  790:       ellipsis = (to_print[prefix_bytes] == '.') ? '_' : '.';
  791:       for (w = 0; w < ELLIPSIS_LEN; w++)
  792: 	putc (ellipsis, rl_outstream);
  793:       printed_len = ELLIPSIS_LEN;
  794:     }
  795: 
  796:   s = to_print + prefix_bytes;
  797:   while (*s)
  798:     {
  799:       if (CTRL_CHAR (*s))
  800:         {
  801:           putc ('^', rl_outstream);
  802:           putc (UNCTRL (*s), rl_outstream);
  803:           printed_len += 2;
  804:           s++;
  805: #if defined (HANDLE_MULTIBYTE)
  806: 	  memset (&ps, 0, sizeof (mbstate_t));
  807: #endif
  808:         }
  809:       else if (*s == RUBOUT)
  810: 	{
  811: 	  putc ('^', rl_outstream);
  812: 	  putc ('?', rl_outstream);
  813: 	  printed_len += 2;
  814: 	  s++;
  815: #if defined (HANDLE_MULTIBYTE)
  816: 	  memset (&ps, 0, sizeof (mbstate_t));
  817: #endif
  818: 	}
  819:       else
  820: 	{
  821: #if defined (HANDLE_MULTIBYTE)
  822: 	  tlen = mbrtowc (&wc, s, end - s, &ps);
  823: 	  if (MB_INVALIDCH (tlen))
  824: 	    {
  825: 	      tlen = 1;
  826: 	      width = 1;
  827: 	      memset (&ps, 0, sizeof (mbstate_t));
  828: 	    }
  829: 	  else if (MB_NULLWCH (tlen))
  830: 	    break;
  831: 	  else
  832: 	    {
  833: 	      w = WCWIDTH (wc);
  834: 	      width = (w >= 0) ? w : 1;
  835: 	    }
  836: 	  fwrite (s, 1, tlen, rl_outstream);
  837: 	  s += tlen;
  838: 	  printed_len += width;
  839: #else
  840: 	  putc (*s, rl_outstream);
  841: 	  s++;
  842: 	  printed_len++;
  843: #endif
  844: 	}
  845:     }
  846: 
  847:   return printed_len;
  848: }
  849: 
  850: /* Output TO_PRINT to rl_outstream.  If VISIBLE_STATS is defined and we
  851:    are using it, check for and output a single character for `special'
  852:    filenames.  Return the number of characters we output. */
  853: 
  854: static int
  855: print_filename (to_print, full_pathname, prefix_bytes)
  856:      char *to_print, *full_pathname;
  857:      int prefix_bytes;
  858: {
  859:   int printed_len, extension_char, slen, tlen;
  860:   char *s, c, *new_full_pathname, *dn;
  861: 
  862:   extension_char = 0;
  863: #if defined (COLOR_SUPPORT)
  864:   /* Defer printing if we want to prefix with a color indicator */
  865:   if (_rl_colored_stats == 0 || rl_filename_completion_desired == 0)
  866: #endif
  867:     printed_len = fnprint (to_print, prefix_bytes);
  868: 
  869:   if (rl_filename_completion_desired && (
  870: #if defined (VISIBLE_STATS)
  871:      rl_visible_stats ||
  872: #endif
  873: #if defined (COLOR_SUPPORT)
  874:      _rl_colored_stats ||
  875: #endif
  876:      _rl_complete_mark_directories))
  877:     {
  878:       /* If to_print != full_pathname, to_print is the basename of the
  879: 	 path passed.  In this case, we try to expand the directory
  880: 	 name before checking for the stat character. */
  881:       if (to_print != full_pathname)
  882: 	{
  883: 	  /* Terminate the directory name. */
  884: 	  c = to_print[-1];
  885: 	  to_print[-1] = '\0';
  886: 
  887: 	  /* If setting the last slash in full_pathname to a NUL results in
  888: 	     full_pathname being the empty string, we are trying to complete
  889: 	     files in the root directory.  If we pass a null string to the
  890: 	     bash directory completion hook, for example, it will expand it
  891: 	     to the current directory.  We just want the `/'. */
  892: 	  if (full_pathname == 0 || *full_pathname == 0)
  893: 	    dn = "/";
  894: 	  else if (full_pathname[0] != '/')
  895: 	    dn = full_pathname;
  896: 	  else if (full_pathname[1] == 0)
  897: 	    dn = "//";		/* restore trailing slash to `//' */
  898: 	  else if (full_pathname[1] == '/' && full_pathname[2] == 0)
  899: 	    dn = "/";		/* don't turn /// into // */
  900: 	  else
  901: 	    dn = full_pathname;
  902: 	  s = tilde_expand (dn);
  903: 	  if (rl_directory_completion_hook)
  904: 	    (*rl_directory_completion_hook) (&s);
  905: 
  906: 	  slen = strlen (s);
  907: 	  tlen = strlen (to_print);
  908: 	  new_full_pathname = (char *)xmalloc (slen + tlen + 2);
  909: 	  strcpy (new_full_pathname, s);
  910: 	  if (s[slen - 1] == '/')
  911: 	    slen--;
  912: 	  else
  913: 	    new_full_pathname[slen] = '/';
  914: 	  new_full_pathname[slen] = '/';
  915: 	  strcpy (new_full_pathname + slen + 1, to_print);
  916: 
  917: #if defined (VISIBLE_STATS)
  918: 	  if (rl_visible_stats)
  919: 	    extension_char = stat_char (new_full_pathname);
  920: 	  else
  921: #endif
  922: 	  if (_rl_complete_mark_directories)
  923: 	    {
  924: 	      dn = 0;
  925: 	      if (rl_directory_completion_hook == 0 && rl_filename_stat_hook)
  926: 		{
  927: 		  dn = savestring (new_full_pathname);
  928: 		  (*rl_filename_stat_hook) (&dn);
  929: 		  free (new_full_pathname);
  930: 		  new_full_pathname = dn;
  931: 		}
  932: 	      if (path_isdir (new_full_pathname))
  933: 		extension_char = '/';
  934: 	    }
  935: 
  936: #if defined (COLOR_SUPPORT)
  937: 	  if (_rl_colored_stats)
  938: 	    {
  939: 	      colored_stat_start (new_full_pathname);
  940: 	      printed_len = fnprint (to_print, prefix_bytes);
  941: 	      colored_stat_end ();
  942: 	    }
  943: #endif
  944: 
  945: 	  xfree (new_full_pathname);
  946: 	  to_print[-1] = c;
  947: 	}
  948:       else
  949: 	{
  950: 	  s = tilde_expand (full_pathname);
  951: #if defined (VISIBLE_STATS)
  952: 	  if (rl_visible_stats)
  953: 	    extension_char = stat_char (s);
  954: 	  else
  955: #endif
  956: 	    if (_rl_complete_mark_directories && path_isdir (s))
  957: 	      extension_char = '/';
  958: 
  959: #if defined (COLOR_SUPPORT)
  960: 	  if (_rl_colored_stats)
  961: 	    {
  962: 	      colored_stat_start (s);
  963: 	      printed_len = fnprint (to_print, prefix_bytes);
  964: 	      colored_stat_end ();
  965: 	    }
  966: #endif
  967: 
  968: 	}
  969: 
  970:       xfree (s);
  971:       if (extension_char)
  972: 	{
  973: 	  putc (extension_char, rl_outstream);
  974: 	  printed_len++;
  975: 	}
  976:     }
  977: 
  978:   return printed_len;
  979: }
  980: 
  981: static char *
  982: rl_quote_filename (s, rtype, qcp)
  983:      char *s;
  984:      int rtype;
  985:      char *qcp;
  986: {
  987:   char *r;
  988: 
  989:   r = (char *)xmalloc (strlen (s) + 2);
  990:   *r = *rl_completer_quote_characters;
  991:   strcpy (r + 1, s);
  992:   if (qcp)
  993:     *qcp = *rl_completer_quote_characters;
  994:   return r;
  995: }
  996: 
  997: /* Find the bounds of the current word for completion purposes, and leave
  998:    rl_point set to the end of the word.  This function skips quoted
  999:    substrings (characters between matched pairs of characters in
 1000:    rl_completer_quote_characters).  First we try to find an unclosed
 1001:    quoted substring on which to do matching.  If one is not found, we use
 1002:    the word break characters to find the boundaries of the current word.
 1003:    We call an application-specific function to decide whether or not a
 1004:    particular word break character is quoted; if that function returns a
 1005:    non-zero result, the character does not break a word.  This function
 1006:    returns the opening quote character if we found an unclosed quoted
 1007:    substring, '\0' otherwise.  FP, if non-null, is set to a value saying
 1008:    which (shell-like) quote characters we found (single quote, double
 1009:    quote, or backslash) anywhere in the string.  DP, if non-null, is set to
 1010:    the value of the delimiter character that caused a word break. */
 1011: 
 1012: char
 1013: _rl_find_completion_word (fp, dp)
 1014:      int *fp, *dp;
 1015: {
 1016:   int scan, end, found_quote, delimiter, pass_next, isbrk;
 1017:   char quote_char, *brkchars;
 1018: 
 1019:   end = rl_point;
 1020:   found_quote = delimiter = 0;
 1021:   quote_char = '\0';
 1022: 
 1023:   brkchars = 0;
 1024:   if (rl_completion_word_break_hook)
 1025:     brkchars = (*rl_completion_word_break_hook) ();
 1026:   if (brkchars == 0)
 1027:     brkchars = rl_completer_word_break_characters;
 1028: 
 1029:   if (rl_completer_quote_characters)
 1030:     {
 1031:       /* We have a list of characters which can be used in pairs to
 1032: 	 quote substrings for the completer.  Try to find the start
 1033: 	 of an unclosed quoted substring. */
 1034:       /* FOUND_QUOTE is set so we know what kind of quotes we found. */
 1035:       for (scan = pass_next = 0; scan < end; scan = MB_NEXTCHAR (rl_line_buffer, scan, 1, MB_FIND_ANY))
 1036: 	{
 1037: 	  if (pass_next)
 1038: 	    {
 1039: 	      pass_next = 0;
 1040: 	      continue;
 1041: 	    }
 1042: 
 1043: 	  /* Shell-like semantics for single quotes -- don't allow backslash
 1044: 	     to quote anything in single quotes, especially not the closing
 1045: 	     quote.  If you don't like this, take out the check on the value
 1046: 	     of quote_char. */
 1047: 	  if (quote_char != '\'' && rl_line_buffer[scan] == '\\')
 1048: 	    {
 1049: 	      pass_next = 1;
 1050: 	      found_quote |= RL_QF_BACKSLASH;
 1051: 	      continue;
 1052: 	    }
 1053: 
 1054: 	  if (quote_char != '\0')
 1055: 	    {
 1056: 	      /* Ignore everything until the matching close quote char. */
 1057: 	      if (rl_line_buffer[scan] == quote_char)
 1058: 		{
 1059: 		  /* Found matching close.  Abandon this substring. */
 1060: 		  quote_char = '\0';
 1061: 		  rl_point = end;
 1062: 		}
 1063: 	    }
 1064: 	  else if (strchr (rl_completer_quote_characters, rl_line_buffer[scan]))
 1065: 	    {
 1066: 	      /* Found start of a quoted substring. */
 1067: 	      quote_char = rl_line_buffer[scan];
 1068: 	      rl_point = scan + 1;
 1069: 	      /* Shell-like quoting conventions. */
 1070: 	      if (quote_char == '\'')
 1071: 		found_quote |= RL_QF_SINGLE_QUOTE;
 1072: 	      else if (quote_char == '"')
 1073: 		found_quote |= RL_QF_DOUBLE_QUOTE;
 1074: 	      else
 1075: 		found_quote |= RL_QF_OTHER_QUOTE;      
 1076: 	    }
 1077: 	}
 1078:     }
 1079: 
 1080:   if (rl_point == end && quote_char == '\0')
 1081:     {
 1082:       /* We didn't find an unclosed quoted substring upon which to do
 1083:          completion, so use the word break characters to find the
 1084:          substring on which to complete. */
 1085:       while (rl_point = MB_PREVCHAR (rl_line_buffer, rl_point, MB_FIND_ANY))
 1086: 	{
 1087: 	  scan = rl_line_buffer[rl_point];
 1088: 
 1089: 	  if (strchr (brkchars, scan) == 0)
 1090: 	    continue;
 1091: 
 1092: 	  /* Call the application-specific function to tell us whether
 1093: 	     this word break character is quoted and should be skipped. */
 1094: 	  if (rl_char_is_quoted_p && found_quote &&
 1095: 	      (*rl_char_is_quoted_p) (rl_line_buffer, rl_point))
 1096: 	    continue;
 1097: 
 1098: 	  /* Convoluted code, but it avoids an n^2 algorithm with calls
 1099: 	     to char_is_quoted. */
 1100: 	  break;
 1101: 	}
 1102:     }
 1103: 
 1104:   /* If we are at an unquoted word break, then advance past it. */
 1105:   scan = rl_line_buffer[rl_point];
 1106: 
 1107:   /* If there is an application-specific function to say whether or not
 1108:      a character is quoted and we found a quote character, let that
 1109:      function decide whether or not a character is a word break, even
 1110:      if it is found in rl_completer_word_break_characters.  Don't bother
 1111:      if we're at the end of the line, though. */
 1112:   if (scan)
 1113:     {
 1114:       if (rl_char_is_quoted_p)
 1115: 	isbrk = (found_quote == 0 ||
 1116: 		(*rl_char_is_quoted_p) (rl_line_buffer, rl_point) == 0) &&
 1117: 		strchr (brkchars, scan) != 0;
 1118:       else
 1119: 	isbrk = strchr (brkchars, scan) != 0;
 1120: 
 1121:       if (isbrk)
 1122: 	{
 1123: 	  /* If the character that caused the word break was a quoting
 1124: 	     character, then remember it as the delimiter. */
 1125: 	  if (rl_basic_quote_characters &&
 1126: 	      strchr (rl_basic_quote_characters, scan) &&
 1127: 	      (end - rl_point) > 1)
 1128: 	    delimiter = scan;
 1129: 
 1130: 	  /* If the character isn't needed to determine something special
 1131: 	     about what kind of completion to perform, then advance past it. */
 1132: 	  if (rl_special_prefixes == 0 || strchr (rl_special_prefixes, scan) == 0)
 1133: 	    rl_point++;
 1134: 	}
 1135:     }
 1136: 
 1137:   if (fp)
 1138:     *fp = found_quote;
 1139:   if (dp)
 1140:     *dp = delimiter;
 1141: 
 1142:   return (quote_char);
 1143: }
 1144: 
 1145: static char **
 1146: gen_completion_matches (text, start, end, our_func, found_quote, quote_char)
 1147:      char *text;
 1148:      int start, end;
 1149:      rl_compentry_func_t *our_func;
 1150:      int found_quote, quote_char;
 1151: {
 1152:   char **matches;
 1153: 
 1154:   rl_completion_found_quote = found_quote;
 1155:   rl_completion_quote_character = quote_char;
 1156: 
 1157:   /* If the user wants to TRY to complete, but then wants to give
 1158:      up and use the default completion function, they set the
 1159:      variable rl_attempted_completion_function. */
 1160:   if (rl_attempted_completion_function)
 1161:     {
 1162:       matches = (*rl_attempted_completion_function) (text, start, end);
 1163:       if (RL_SIG_RECEIVED())
 1164: 	{
 1165: 	  _rl_free_match_list (matches);
 1166: 	  matches = 0;
 1167: 	  RL_CHECK_SIGNALS ();
 1168: 	}
 1169: 
 1170:       if (matches || rl_attempted_completion_over)
 1171: 	{
 1172: 	  rl_attempted_completion_over = 0;
 1173: 	  return (matches);
 1174: 	}
 1175:     }
 1176: 
 1177:   /* XXX -- filename dequoting moved into rl_filename_completion_function */
 1178: 
 1179:   /* rl_completion_matches will check for signals as well to avoid a long
 1180:      delay while reading a directory. */
 1181:   matches = rl_completion_matches (text, our_func);
 1182:   if (RL_SIG_RECEIVED())
 1183:     {
 1184:       _rl_free_match_list (matches);
 1185:       matches = 0;
 1186:       RL_CHECK_SIGNALS ();
 1187:     }
 1188:   return matches;  
 1189: }
 1190: 
 1191: /* Filter out duplicates in MATCHES.  This frees up the strings in
 1192:    MATCHES. */
 1193: static char **
 1194: remove_duplicate_matches (matches)
 1195:      char **matches;
 1196: {
 1197:   char *lowest_common;
 1198:   int i, j, newlen;
 1199:   char dead_slot;
 1200:   char **temp_array;
 1201: 
 1202:   /* Sort the items. */
 1203:   for (i = 0; matches[i]; i++)
 1204:     ;
 1205: 
 1206:   /* Sort the array without matches[0], since we need it to
 1207:      stay in place no matter what. */
 1208:   if (i && rl_sort_completion_matches)
 1209:     qsort (matches+1, i-1, sizeof (char *), (QSFUNC *)_rl_qsort_string_compare);
 1210: 
 1211:   /* Remember the lowest common denominator for it may be unique. */
 1212:   lowest_common = savestring (matches[0]);
 1213: 
 1214:   for (i = newlen = 0; matches[i + 1]; i++)
 1215:     {
 1216:       if (strcmp (matches[i], matches[i + 1]) == 0)
 1217: 	{
 1218: 	  xfree (matches[i]);
 1219: 	  matches[i] = (char *)&dead_slot;
 1220: 	}
 1221:       else
 1222: 	newlen++;
 1223:     }
 1224: 
 1225:   /* We have marked all the dead slots with (char *)&dead_slot.
 1226:      Copy all the non-dead entries into a new array. */
 1227:   temp_array = (char **)xmalloc ((3 + newlen) * sizeof (char *));
 1228:   for (i = j = 1; matches[i]; i++)
 1229:     {
 1230:       if (matches[i] != (char *)&dead_slot)
 1231: 	temp_array[j++] = matches[i];
 1232:     }
 1233:   temp_array[j] = (char *)NULL;
 1234: 
 1235:   if (matches[0] != (char *)&dead_slot)
 1236:     xfree (matches[0]);
 1237: 
 1238:   /* Place the lowest common denominator back in [0]. */
 1239:   temp_array[0] = lowest_common;
 1240: 
 1241:   /* If there is one string left, and it is identical to the
 1242:      lowest common denominator, then the LCD is the string to
 1243:      insert. */
 1244:   if (j == 2 && strcmp (temp_array[0], temp_array[1]) == 0)
 1245:     {
 1246:       xfree (temp_array[1]);
 1247:       temp_array[1] = (char *)NULL;
 1248:     }
 1249:   return (temp_array);
 1250: }
 1251: 
 1252: /* Find the common prefix of the list of matches, and put it into
 1253:    matches[0]. */
 1254: static int
 1255: compute_lcd_of_matches (match_list, matches, text)
 1256:      char **match_list;
 1257:      int matches;
 1258:      const char *text;
 1259: {
 1260:   register int i, c1, c2, si;
 1261:   int low;		/* Count of max-matched characters. */
 1262:   int lx;
 1263:   char *dtext;		/* dequoted TEXT, if needed */
 1264: #if defined (HANDLE_MULTIBYTE)
 1265:   int v;
 1266:   size_t v1, v2;
 1267:   mbstate_t ps1, ps2;
 1268:   wchar_t wc1, wc2;
 1269: #endif
 1270: 
 1271:   /* If only one match, just use that.  Otherwise, compare each
 1272:      member of the list with the next, finding out where they
 1273:      stop matching. */
 1274:   if (matches == 1)
 1275:     {
 1276:       match_list[0] = match_list[1];
 1277:       match_list[1] = (char *)NULL;
 1278:       return 1;
 1279:     }
 1280: 
 1281:   for (i = 1, low = 100000; i < matches; i++)
 1282:     {
 1283: #if defined (HANDLE_MULTIBYTE)
 1284:       if (MB_CUR_MAX > 1 && rl_byte_oriented == 0)
 1285: 	{
 1286: 	  memset (&ps1, 0, sizeof (mbstate_t));
 1287: 	  memset (&ps2, 0, sizeof (mbstate_t));
 1288: 	}
 1289: #endif
 1290:       if (_rl_completion_case_fold)
 1291: 	{
 1292: 	  for (si = 0;
 1293: 	       (c1 = _rl_to_lower(match_list[i][si])) &&
 1294: 	       (c2 = _rl_to_lower(match_list[i + 1][si]));
 1295: 	       si++)
 1296: #if defined (HANDLE_MULTIBYTE)
 1297: 	    if (MB_CUR_MAX > 1 && rl_byte_oriented == 0)
 1298: 	      {
 1299: 		v1 = mbrtowc(&wc1, match_list[i]+si, strlen (match_list[i]+si), &ps1);
 1300: 		v2 = mbrtowc (&wc2, match_list[i+1]+si, strlen (match_list[i+1]+si), &ps2);
 1301: 		if (MB_INVALIDCH (v1) || MB_INVALIDCH (v2))
 1302: 		  {
 1303: 		    if (c1 != c2)	/* do byte comparison */
 1304: 		      break;
 1305: 		    continue;
 1306: 		  }
 1307: 		wc1 = towlower (wc1);
 1308: 		wc2 = towlower (wc2);
 1309: 		if (wc1 != wc2)
 1310: 		  break;
 1311: 		else if (v1 > 1)
 1312: 		  si += v1 - 1;
 1313: 	      }
 1314: 	    else
 1315: #endif
 1316: 	    if (c1 != c2)
 1317: 	      break;
 1318: 	}
 1319:       else
 1320: 	{
 1321: 	  for (si = 0;
 1322: 	       (c1 = match_list[i][si]) &&
 1323: 	       (c2 = match_list[i + 1][si]);
 1324: 	       si++)
 1325: #if defined (HANDLE_MULTIBYTE)
 1326: 	    if (MB_CUR_MAX > 1 && rl_byte_oriented == 0)
 1327: 	      {
 1328: 		mbstate_t ps_back;
 1329: 		ps_back = ps1;
 1330: 		if (!_rl_compare_chars (match_list[i], si, &ps1, match_list[i+1], si, &ps2))
 1331: 		  break;
 1332: 		else if ((v = _rl_get_char_len (&match_list[i][si], &ps_back)) > 1)
 1333: 		  si += v - 1;
 1334: 	      }
 1335: 	    else
 1336: #endif
 1337: 	    if (c1 != c2)
 1338: 	      break;
 1339: 	}
 1340: 
 1341:       if (low > si)
 1342: 	low = si;
 1343:     }
 1344: 
 1345:   /* If there were multiple matches, but none matched up to even the
 1346:      first character, and the user typed something, use that as the
 1347:      value of matches[0]. */
 1348:   if (low == 0 && text && *text)
 1349:     {
 1350:       match_list[0] = (char *)xmalloc (strlen (text) + 1);
 1351:       strcpy (match_list[0], text);
 1352:     }
 1353:   else
 1354:     {
 1355:       match_list[0] = (char *)xmalloc (low + 1);
 1356: 
 1357:       /* XXX - this might need changes in the presence of multibyte chars */
 1358: 
 1359:       /* If we are ignoring case, try to preserve the case of the string
 1360: 	 the user typed in the face of multiple matches differing in case. */
 1361:       if (_rl_completion_case_fold)
 1362: 	{
 1363: 	  /* We're making an assumption here:
 1364: 		IF we're completing filenames AND
 1365: 		   the application has defined a filename dequoting function AND
 1366: 		   we found a quote character AND
 1367: 		   the application has requested filename quoting
 1368: 		THEN
 1369: 		   we assume that TEXT was dequoted before checking against
 1370: 		   the file system and needs to be dequoted here before we
 1371: 		   check against the list of matches
 1372: 		FI */
 1373: 	  dtext = (char *)NULL;
 1374: 	  if (rl_filename_completion_desired &&
 1375: 	      rl_filename_dequoting_function &&
 1376: 	      rl_completion_found_quote &&
 1377: 	      rl_filename_quoting_desired)
 1378: 	    {
 1379: 	      dtext = (*rl_filename_dequoting_function) ((char *)text, rl_completion_quote_character);
 1380: 	      text = dtext;
 1381: 	    }
 1382: 
 1383: 	  /* sort the list to get consistent answers. */
 1384: 	  qsort (match_list+1, matches, sizeof(char *), (QSFUNC *)_rl_qsort_string_compare);
 1385: 
 1386: 	  si = strlen (text);
 1387: 	  lx = (si <= low) ? si : low;	/* check shorter of text and matches */
 1388: 	  /* Try to preserve the case of what the user typed in the presence of
 1389: 	     multiple matches: check each match for something that matches
 1390: 	     what the user typed taking case into account; use it up to common
 1391: 	     length of matches if one is found.  If not, just use first match. */
 1392: 	  for (i = 1; i <= matches; i++)
 1393: 	    if (strncmp (match_list[i], text, lx) == 0)
 1394: 	      {
 1395: 		strncpy (match_list[0], match_list[i], low);
 1396: 		break;
 1397: 	      }
 1398: 	  /* no casematch, use first entry */
 1399: 	  if (i > matches)
 1400: 	    strncpy (match_list[0], match_list[1], low);
 1401: 
 1402: 	  FREE (dtext);
 1403: 	}
 1404:       else
 1405:         strncpy (match_list[0], match_list[1], low);
 1406: 
 1407:       match_list[0][low] = '\0';
 1408:     }
 1409: 
 1410:   return matches;
 1411: }
 1412: 
 1413: static int
 1414: postprocess_matches (matchesp, matching_filenames)
 1415:      char ***matchesp;
 1416:      int matching_filenames;
 1417: {
 1418:   char *t, **matches, **temp_matches;
 1419:   int nmatch, i;
 1420: 
 1421:   matches = *matchesp;
 1422: 
 1423:   if (matches == 0)
 1424:     return 0;
 1425: 
 1426:   /* It seems to me that in all the cases we handle we would like
 1427:      to ignore duplicate possibilities.  Scan for the text to
 1428:      insert being identical to the other completions. */
 1429:   if (rl_ignore_completion_duplicates)
 1430:     {
 1431:       temp_matches = remove_duplicate_matches (matches);
 1432:       xfree (matches);
 1433:       matches = temp_matches;
 1434:     }
 1435: 
 1436:   /* If we are matching filenames, then here is our chance to
 1437:      do clever processing by re-examining the list.  Call the
 1438:      ignore function with the array as a parameter.  It can
 1439:      munge the array, deleting matches as it desires. */
 1440:   if (rl_ignore_some_completions_function && matching_filenames)
 1441:     {
 1442:       for (nmatch = 1; matches[nmatch]; nmatch++)
 1443: 	;
 1444:       (void)(*rl_ignore_some_completions_function) (matches);
 1445:       if (matches == 0 || matches[0] == 0)
 1446: 	{
 1447: 	  FREE (matches);
 1448: 	  *matchesp = (char **)0;
 1449: 	  return 0;
 1450:         }
 1451:       else
 1452: 	{
 1453: 	  /* If we removed some matches, recompute the common prefix. */
 1454: 	  for (i = 1; matches[i]; i++)
 1455: 	    ;
 1456: 	  if (i > 1 && i < nmatch)
 1457: 	    {
 1458: 	      t = matches[0];
 1459: 	      compute_lcd_of_matches (matches, i - 1, t);
 1460: 	      FREE (t);
 1461: 	    }
 1462: 	}
 1463:     }
 1464: 
 1465:   *matchesp = matches;
 1466:   return (1);
 1467: }
 1468: 
 1469: static int
 1470: complete_get_screenwidth ()
 1471: {
 1472:   int cols;
 1473:   char *envcols;
 1474: 
 1475:   cols = _rl_completion_columns;
 1476:   if (cols >= 0 && cols <= _rl_screenwidth)
 1477:     return cols;
 1478:   envcols = getenv ("COLUMNS");
 1479:   if (envcols && *envcols)
 1480:     cols = atoi (envcols);
 1481:   if (cols >= 0 && cols <= _rl_screenwidth)
 1482:     return cols;
 1483:   return _rl_screenwidth;
 1484: }
 1485: 
 1486: /* A convenience function for displaying a list of strings in
 1487:    columnar format on readline's output stream.  MATCHES is the list
 1488:    of strings, in argv format, LEN is the number of strings in MATCHES,
 1489:    and MAX is the length of the longest string in MATCHES. */
 1490: void
 1491: rl_display_match_list (matches, len, max)
 1492:      char **matches;
 1493:      int len, max;
 1494: {
 1495:   int count, limit, printed_len, lines, cols;
 1496:   int i, j, k, l, common_length, sind;
 1497:   char *temp, *t;
 1498: 
 1499:   /* Find the length of the prefix common to all items: length as displayed
 1500:      characters (common_length) and as a byte index into the matches (sind) */
 1501:   common_length = sind = 0;
 1502:   if (_rl_completion_prefix_display_length > 0)
 1503:     {
 1504:       t = printable_part (matches[0]);
 1505:       temp = strrchr (t, '/');
 1506:       common_length = temp ? fnwidth (temp) : fnwidth (t);
 1507:       sind = temp ? strlen (temp) : strlen (t);
 1508: 
 1509:       if (common_length > _rl_completion_prefix_display_length && common_length > ELLIPSIS_LEN)
 1510: 	max -= common_length - ELLIPSIS_LEN;
 1511:       else
 1512: 	common_length = sind = 0;
 1513:     }
 1514: 
 1515:   /* How many items of MAX length can we fit in the screen window? */
 1516:   cols = complete_get_screenwidth ();
 1517:   max += 2;
 1518:   limit = cols / max;
 1519:   if (limit != 1 && (limit * max == cols))
 1520:     limit--;
 1521: 
 1522:   /* If cols == 0, limit will end up -1 */
 1523:   if (cols < _rl_screenwidth && limit < 0)
 1524:     limit = 1;
 1525: 
 1526:   /* Avoid a possible floating exception.  If max > cols,
 1527:      limit will be 0 and a divide-by-zero fault will result. */
 1528:   if (limit == 0)
 1529:     limit = 1;
 1530: 
 1531:   /* How many iterations of the printing loop? */
 1532:   count = (len + (limit - 1)) / limit;
 1533: 
 1534:   /* Watch out for special case.  If LEN is less than LIMIT, then
 1535:      just do the inner printing loop.
 1536: 	   0 < len <= limit  implies  count = 1. */
 1537: 
 1538:   /* Sort the items if they are not already sorted. */
 1539:   if (rl_ignore_completion_duplicates == 0 && rl_sort_completion_matches)
 1540:     qsort (matches + 1, len, sizeof (char *), (QSFUNC *)_rl_qsort_string_compare);
 1541: 
 1542:   rl_crlf ();
 1543: 
 1544:   lines = 0;
 1545:   if (_rl_print_completions_horizontally == 0)
 1546:     {
 1547:       /* Print the sorted items, up-and-down alphabetically, like ls. */
 1548:       for (i = 1; i <= count; i++)
 1549: 	{
 1550: 	  for (j = 0, l = i; j < limit; j++)
 1551: 	    {
 1552: 	      if (l > len || matches[l] == 0)
 1553: 		break;
 1554: 	      else
 1555: 		{
 1556: 		  temp = printable_part (matches[l]);
 1557: 		  printed_len = print_filename (temp, matches[l], sind);
 1558: 
 1559: 		  if (j + 1 < limit)
 1560: 		    for (k = 0; k < max - printed_len; k++)
 1561: 		      putc (' ', rl_outstream);
 1562: 		}
 1563: 	      l += count;
 1564: 	    }
 1565: 	  rl_crlf ();
 1566: 	  lines++;
 1567: 	  if (_rl_page_completions && lines >= (_rl_screenheight - 1) && i < count)
 1568: 	    {
 1569: 	      lines = _rl_internal_pager (lines);
 1570: 	      if (lines < 0)
 1571: 		return;
 1572: 	    }
 1573: 	}
 1574:     }
 1575:   else
 1576:     {
 1577:       /* Print the sorted items, across alphabetically, like ls -x. */
 1578:       for (i = 1; matches[i]; i++)
 1579: 	{
 1580: 	  temp = printable_part (matches[i]);
 1581: 	  printed_len = print_filename (temp, matches[i], sind);
 1582: 	  /* Have we reached the end of this line? */
 1583: 	  if (matches[i+1])
 1584: 	    {
 1585: 	      if (limit == 1 || (i && (limit > 1) && (i % limit) == 0))
 1586: 		{
 1587: 		  rl_crlf ();
 1588: 		  lines++;
 1589: 		  if (_rl_page_completions && lines >= _rl_screenheight - 1)
 1590: 		    {
 1591: 		      lines = _rl_internal_pager (lines);
 1592: 		      if (lines < 0)
 1593: 			return;
 1594: 		    }
 1595: 		}
 1596: 	      else
 1597: 		for (k = 0; k < max - printed_len; k++)
 1598: 		  putc (' ', rl_outstream);
 1599: 	    }
 1600: 	}
 1601:       rl_crlf ();
 1602:     }
 1603: }
 1604: 
 1605: /* Display MATCHES, a list of matching filenames in argv format.  This
 1606:    handles the simple case -- a single match -- first.  If there is more
 1607:    than one match, we compute the number of strings in the list and the
 1608:    length of the longest string, which will be needed by the display
 1609:    function.  If the application wants to handle displaying the list of
 1610:    matches itself, it sets RL_COMPLETION_DISPLAY_MATCHES_HOOK to the
 1611:    address of a function, and we just call it.  If we're handling the
 1612:    display ourselves, we just call rl_display_match_list.  We also check
 1613:    that the list of matches doesn't exceed the user-settable threshold,
 1614:    and ask the user if he wants to see the list if there are more matches
 1615:    than RL_COMPLETION_QUERY_ITEMS. */
 1616: static void
 1617: display_matches (matches)
 1618:      char **matches;
 1619: {
 1620:   int len, max, i;
 1621:   char *temp;
 1622: 
 1623:   /* Move to the last visible line of a possibly-multiple-line command. */
 1624:   _rl_move_vert (_rl_vis_botlin);
 1625: 
 1626:   /* Handle simple case first.  What if there is only one answer? */
 1627:   if (matches[1] == 0)
 1628:     {
 1629:       temp = printable_part (matches[0]);
 1630:       rl_crlf ();
 1631:       print_filename (temp, matches[0], 0);
 1632:       rl_crlf ();
 1633: 
 1634:       rl_forced_update_display ();
 1635:       rl_display_fixed = 1;
 1636: 
 1637:       return;
 1638:     }
 1639: 
 1640:   /* There is more than one answer.  Find out how many there are,
 1641:      and find the maximum printed length of a single entry. */
 1642:   for (max = 0, i = 1; matches[i]; i++)
 1643:     {
 1644:       temp = printable_part (matches[i]);
 1645:       len = fnwidth (temp);
 1646: 
 1647:       if (len > max)
 1648: 	max = len;
 1649:     }
 1650: 
 1651:   len = i - 1;
 1652: 
 1653:   /* If the caller has defined a display hook, then call that now. */
 1654:   if (rl_completion_display_matches_hook)
 1655:     {
 1656:       (*rl_completion_display_matches_hook) (matches, len, max);
 1657:       return;
 1658:     }
 1659: 	
 1660:   /* If there are many items, then ask the user if she really wants to
 1661:      see them all. */
 1662:   if (rl_completion_query_items > 0 && len >= rl_completion_query_items)
 1663:     {
 1664:       rl_crlf ();
 1665:       fprintf (rl_outstream, "Display all %d possibilities? (y or n)", len);
 1666:       fflush (rl_outstream);
 1667:       if ((completion_y_or_n = get_y_or_n (0)) == 0)
 1668: 	{
 1669: 	  rl_crlf ();
 1670: 
 1671: 	  rl_forced_update_display ();
 1672: 	  rl_display_fixed = 1;
 1673: 
 1674: 	  return;
 1675: 	}
 1676:     }
 1677: 
 1678:   rl_display_match_list (matches, len, max);
 1679: 
 1680:   rl_forced_update_display ();
 1681:   rl_display_fixed = 1;
 1682: }
 1683: 
 1684: static char *
 1685: make_quoted_replacement (match, mtype, qc)
 1686:      char *match;
 1687:      int mtype;
 1688:      char *qc;	/* Pointer to quoting character, if any */
 1689: {
 1690:   int should_quote, do_replace;
 1691:   char *replacement;
 1692: 
 1693:   /* If we are doing completion on quoted substrings, and any matches
 1694:      contain any of the completer_word_break_characters, then auto-
 1695:      matically prepend the substring with a quote character (just pick
 1696:      the first one from the list of such) if it does not already begin
 1697:      with a quote string.  FIXME: Need to remove any such automatically
 1698:      inserted quote character when it no longer is necessary, such as
 1699:      if we change the string we are completing on and the new set of
 1700:      matches don't require a quoted substring. */
 1701:   replacement = match;
 1702: 
 1703:   should_quote = match && rl_completer_quote_characters &&
 1704: 			rl_filename_completion_desired &&
 1705: 			rl_filename_quoting_desired;
 1706: 
 1707:   if (should_quote)
 1708:     should_quote = should_quote && (!qc || !*qc ||
 1709: 		     (rl_completer_quote_characters && strchr (rl_completer_quote_characters, *qc)));
 1710: 
 1711:   if (should_quote)
 1712:     {
 1713:       /* If there is a single match, see if we need to quote it.
 1714:          This also checks whether the common prefix of several
 1715: 	 matches needs to be quoted. */
 1716:       should_quote = rl_filename_quote_characters
 1717: 			? (_rl_strpbrk (match, rl_filename_quote_characters) != 0)
 1718: 			: 0;
 1719: 
 1720:       do_replace = should_quote ? mtype : NO_MATCH;
 1721:       /* Quote the replacement, since we found an embedded
 1722: 	 word break character in a potential match. */
 1723:       if (do_replace != NO_MATCH && rl_filename_quoting_function)
 1724: 	replacement = (*rl_filename_quoting_function) (match, do_replace, qc);
 1725:     }
 1726:   return (replacement);
 1727: }
 1728: 
 1729: static void
 1730: insert_match (match, start, mtype, qc)
 1731:      char *match;
 1732:      int start, mtype;
 1733:      char *qc;
 1734: {
 1735:   char *replacement, *r;
 1736:   char oqc;
 1737:   int end, rlen;
 1738: 
 1739:   oqc = qc ? *qc : '\0';
 1740:   replacement = make_quoted_replacement (match, mtype, qc);
 1741: 
 1742:   /* Now insert the match. */
 1743:   if (replacement)
 1744:     {
 1745:       rlen = strlen (replacement);
 1746:       /* Don't double an opening quote character. */
 1747:       if (qc && *qc && start && rl_line_buffer[start - 1] == *qc &&
 1748: 	    replacement[0] == *qc)
 1749: 	start--;
 1750:       /* If make_quoted_replacement changed the quoting character, remove
 1751: 	 the opening quote and insert the (fully-quoted) replacement. */
 1752:       else if (qc && (*qc != oqc) && start && rl_line_buffer[start - 1] == oqc &&
 1753: 	    replacement[0] != oqc)
 1754: 	start--;
 1755:       end = rl_point - 1;
 1756:       /* Don't double a closing quote character */
 1757:       if (qc && *qc && end && rl_line_buffer[rl_point] == *qc && replacement[rlen - 1] == *qc)
 1758:         end++;
 1759:       if (_rl_skip_completed_text)
 1760: 	{
 1761: 	  r = replacement;
 1762: 	  while (start < rl_end && *r && rl_line_buffer[start] == *r)
 1763: 	    {
 1764: 	      start++;
 1765: 	      r++;
 1766: 	    }
 1767: 	  if (start <= end || *r)
 1768: 	    _rl_replace_text (r, start, end);
 1769: 	  rl_point = start + strlen (r);
 1770: 	}
 1771:       else
 1772: 	_rl_replace_text (replacement, start, end);
 1773:       if (replacement != match)
 1774:         xfree (replacement);
 1775:     }
 1776: }
 1777: 
 1778: /* Append any necessary closing quote and a separator character to the
 1779:    just-inserted match.  If the user has specified that directories
 1780:    should be marked by a trailing `/', append one of those instead.  The
 1781:    default trailing character is a space.  Returns the number of characters
 1782:    appended.  If NONTRIVIAL_MATCH is set, we test for a symlink (if the OS
 1783:    has them) and don't add a suffix for a symlink to a directory.  A
 1784:    nontrivial match is one that actually adds to the word being completed.
 1785:    The variable rl_completion_mark_symlink_dirs controls this behavior
 1786:    (it's initially set to the what the user has chosen, indicated by the
 1787:    value of _rl_complete_mark_symlink_dirs, but may be modified by an
 1788:    application's completion function). */
 1789: static int
 1790: append_to_match (text, delimiter, quote_char, nontrivial_match)
 1791:      char *text;
 1792:      int delimiter, quote_char, nontrivial_match;
 1793: {
 1794:   char temp_string[4], *filename, *fn;
 1795:   int temp_string_index, s;
 1796:   struct stat finfo;
 1797: 
 1798:   temp_string_index = 0;
 1799:   if (quote_char && rl_point && rl_completion_suppress_quote == 0 &&
 1800:       rl_line_buffer[rl_point - 1] != quote_char)
 1801:     temp_string[temp_string_index++] = quote_char;
 1802: 
 1803:   if (delimiter)
 1804:     temp_string[temp_string_index++] = delimiter;
 1805:   else if (rl_completion_suppress_append == 0 && rl_completion_append_character)
 1806:     temp_string[temp_string_index++] = rl_completion_append_character;
 1807: 
 1808:   temp_string[temp_string_index++] = '\0';
 1809: 
 1810:   if (rl_filename_completion_desired)
 1811:     {
 1812:       filename = tilde_expand (text);
 1813:       if (rl_filename_stat_hook)
 1814:         {
 1815:           fn = savestring (filename);
 1816: 	  (*rl_filename_stat_hook) (&fn);
 1817: 	  xfree (filename);
 1818: 	  filename = fn;
 1819:         }
 1820:       s = (nontrivial_match && rl_completion_mark_symlink_dirs == 0)
 1821: 		? LSTAT (filename, &finfo)
 1822: 		: stat (filename, &finfo);
 1823:       if (s == 0 && S_ISDIR (finfo.st_mode))
 1824: 	{
 1825: 	  if (_rl_complete_mark_directories /* && rl_completion_suppress_append == 0 */)
 1826: 	    {
 1827: 	      /* This is clumsy.  Avoid putting in a double slash if point
 1828: 		 is at the end of the line and the previous character is a
 1829: 		 slash. */
 1830: 	      if (rl_point && rl_line_buffer[rl_point] == '\0' && rl_line_buffer[rl_point - 1] == '/')
 1831: 		;
 1832: 	      else if (rl_line_buffer[rl_point] != '/')
 1833: 		rl_insert_text ("/");
 1834: 	    }
 1835: 	}
 1836: #ifdef S_ISLNK
 1837:       /* Don't add anything if the filename is a symlink and resolves to a
 1838: 	 directory. */
 1839:       else if (s == 0 && S_ISLNK (finfo.st_mode) && path_isdir (filename))
 1840: 	;
 1841: #endif
 1842:       else
 1843: 	{
 1844: 	  if (rl_point == rl_end && temp_string_index)
 1845: 	    rl_insert_text (temp_string);
 1846: 	}
 1847:       xfree (filename);
 1848:     }
 1849:   else
 1850:     {
 1851:       if (rl_point == rl_end && temp_string_index)
 1852: 	rl_insert_text (temp_string);
 1853:     }
 1854: 
 1855:   return (temp_string_index);
 1856: }
 1857: 
 1858: static void
 1859: insert_all_matches (matches, point, qc)
 1860:      char **matches;
 1861:      int point;
 1862:      char *qc;
 1863: {
 1864:   int i;
 1865:   char *rp;
 1866: 
 1867:   rl_begin_undo_group ();
 1868:   /* remove any opening quote character; make_quoted_replacement will add
 1869:      it back. */
 1870:   if (qc && *qc && point && rl_line_buffer[point - 1] == *qc)
 1871:     point--;
 1872:   rl_delete_text (point, rl_point);
 1873:   rl_point = point;
 1874: 
 1875:   if (matches[1])
 1876:     {
 1877:       for (i = 1; matches[i]; i++)
 1878: 	{
 1879: 	  rp = make_quoted_replacement (matches[i], SINGLE_MATCH, qc);
 1880: 	  rl_insert_text (rp);
 1881: 	  rl_insert_text (" ");
 1882: 	  if (rp != matches[i])
 1883: 	    xfree (rp);
 1884: 	}
 1885:     }
 1886:   else
 1887:     {
 1888:       rp = make_quoted_replacement (matches[0], SINGLE_MATCH, qc);
 1889:       rl_insert_text (rp);
 1890:       rl_insert_text (" ");
 1891:       if (rp != matches[0])
 1892: 	xfree (rp);
 1893:     }
 1894:   rl_end_undo_group ();
 1895: }
 1896: 
 1897: void
 1898: _rl_free_match_list (matches)
 1899:      char **matches;
 1900: {
 1901:   register int i;
 1902: 
 1903:   if (matches == 0)
 1904:     return;
 1905: 
 1906:   for (i = 0; matches[i]; i++)
 1907:     xfree (matches[i]);
 1908:   xfree (matches);
 1909: }
 1910: 
 1911: /* Complete the word at or before point.
 1912:    WHAT_TO_DO says what to do with the completion.
 1913:    `?' means list the possible completions.
 1914:    TAB means do standard completion.
 1915:    `*' means insert all of the possible completions.
 1916:    `!' means to do standard completion, and list all possible completions if
 1917:    there is more than one.
 1918:    `@' means to do standard completion, and list all possible completions if
 1919:    there is more than one and partial completion is not possible. */
 1920: int
 1921: rl_complete_internal (what_to_do)
 1922:      int what_to_do;
 1923: {
 1924:   char **matches;
 1925:   rl_compentry_func_t *our_func;
 1926:   int start, end, delimiter, found_quote, i, nontrivial_lcd;
 1927:   char *text, *saved_line_buffer;
 1928:   char quote_char;
 1929: #if 1
 1930:   int tlen, mlen;
 1931: #endif
 1932: 
 1933:   RL_SETSTATE(RL_STATE_COMPLETING);
 1934: 
 1935:   set_completion_defaults (what_to_do);
 1936: 
 1937:   saved_line_buffer = rl_line_buffer ? savestring (rl_line_buffer) : (char *)NULL;
 1938:   our_func = rl_completion_entry_function
 1939: 		? rl_completion_entry_function
 1940: 		: rl_filename_completion_function;
 1941:   /* We now look backwards for the start of a filename/variable word. */
 1942:   end = rl_point;
 1943:   found_quote = delimiter = 0;
 1944:   quote_char = '\0';
 1945: 
 1946:   if (rl_point)
 1947:     /* This (possibly) changes rl_point.  If it returns a non-zero char,
 1948:        we know we have an open quote. */
 1949:     quote_char = _rl_find_completion_word (&found_quote, &delimiter);
 1950: 
 1951:   start = rl_point;
 1952:   rl_point = end;
 1953: 
 1954:   text = rl_copy_text (start, end);
 1955:   matches = gen_completion_matches (text, start, end, our_func, found_quote, quote_char);
 1956:   /* nontrivial_lcd is set if the common prefix adds something to the word
 1957:      being completed. */
 1958:   nontrivial_lcd = matches && strcmp (text, matches[0]) != 0;
 1959:   if (what_to_do == '!' || what_to_do == '@')
 1960:     tlen = strlen (text);
 1961:   xfree (text);
 1962: 
 1963:   if (matches == 0)
 1964:     {
 1965:       rl_ding ();
 1966:       FREE (saved_line_buffer);
 1967:       completion_changed_buffer = 0;
 1968:       RL_UNSETSTATE(RL_STATE_COMPLETING);
 1969:       _rl_reset_completion_state ();
 1970:       return (0);
 1971:     }
 1972: 
 1973:   /* If we are matching filenames, the attempted completion function will
 1974:      have set rl_filename_completion_desired to a non-zero value.  The basic
 1975:      rl_filename_completion_function does this. */
 1976:   i = rl_filename_completion_desired;
 1977: 
 1978:   if (postprocess_matches (&matches, i) == 0)
 1979:     {
 1980:       rl_ding ();
 1981:       FREE (saved_line_buffer);
 1982:       completion_changed_buffer = 0;
 1983:       RL_UNSETSTATE(RL_STATE_COMPLETING);
 1984:       _rl_reset_completion_state ();
 1985:       return (0);
 1986:     }
 1987: 
 1988:   switch (what_to_do)
 1989:     {
 1990:     case TAB:
 1991:     case '!':
 1992:     case '@':
 1993:       /* Insert the first match with proper quoting. */
 1994:       if (what_to_do == TAB)
 1995:         {
 1996:           if (*matches[0])
 1997: 	    insert_match (matches[0], start, matches[1] ? MULT_MATCH : SINGLE_MATCH, &quote_char);
 1998:         }
 1999:       else if (*matches[0] && matches[1] == 0)
 2000: 	/* should we perform the check only if there are multiple matches? */
 2001: 	insert_match (matches[0], start, matches[1] ? MULT_MATCH : SINGLE_MATCH, &quote_char);
 2002:       else if (*matches[0])	/* what_to_do != TAB && multiple matches */
 2003: 	{
 2004: 	  mlen = *matches[0] ? strlen (matches[0]) : 0;
 2005: 	  if (mlen >= tlen)
 2006: 	    insert_match (matches[0], start, matches[1] ? MULT_MATCH : SINGLE_MATCH, &quote_char);
 2007: 	}
 2008: 
 2009:       /* If there are more matches, ring the bell to indicate.
 2010: 	 If we are in vi mode, Posix.2 says to not ring the bell.
 2011: 	 If the `show-all-if-ambiguous' variable is set, display
 2012: 	 all the matches immediately.  Otherwise, if this was the
 2013: 	 only match, and we are hacking files, check the file to
 2014: 	 see if it was a directory.  If so, and the `mark-directories'
 2015: 	 variable is set, add a '/' to the name.  If not, and we
 2016: 	 are at the end of the line, then add a space.  */
 2017:       if (matches[1])
 2018: 	{
 2019: 	  if (what_to_do == '!')
 2020: 	    {
 2021: 	      display_matches (matches);
 2022: 	      break;
 2023: 	    }
 2024: 	  else if (what_to_do == '@')
 2025: 	    {
 2026: 	      if (nontrivial_lcd == 0)
 2027: 		display_matches (matches);
 2028: 	      break;
 2029: 	    }
 2030: 	  else if (rl_editing_mode != vi_mode)
 2031: 	    rl_ding ();	/* There are other matches remaining. */
 2032: 	}
 2033:       else
 2034: 	append_to_match (matches[0], delimiter, quote_char, nontrivial_lcd);
 2035: 
 2036:       break;
 2037: 
 2038:     case '*':
 2039:       insert_all_matches (matches, start, &quote_char);
 2040:       break;
 2041: 
 2042:     case '?':
 2043:       if (rl_completion_display_matches_hook == 0)
 2044: 	{
 2045: 	  _rl_sigcleanup = _rl_complete_sigcleanup;
 2046: 	  _rl_sigcleanarg = matches;
 2047: 	}
 2048:       display_matches (matches);
 2049:       _rl_sigcleanup = 0;
 2050:       _rl_sigcleanarg = 0;
 2051:       break;
 2052: 
 2053:     default:
 2054:       _rl_ttymsg ("bad value %d for what_to_do in rl_complete", what_to_do);
 2055:       rl_ding ();
 2056:       FREE (saved_line_buffer);
 2057:       RL_UNSETSTATE(RL_STATE_COMPLETING);
 2058:       _rl_free_match_list (matches);
 2059:       _rl_reset_completion_state ();
 2060:       return 1;
 2061:     }
 2062: 
 2063:   _rl_free_match_list (matches);
 2064: 
 2065:   /* Check to see if the line has changed through all of this manipulation. */
 2066:   if (saved_line_buffer)
 2067:     {
 2068:       completion_changed_buffer = strcmp (rl_line_buffer, saved_line_buffer) != 0;
 2069:       xfree (saved_line_buffer);
 2070:     }
 2071: 
 2072:   RL_UNSETSTATE(RL_STATE_COMPLETING);
 2073:   _rl_reset_completion_state ();
 2074:   return 0;
 2075: }
 2076: 
 2077: /***************************************************************/
 2078: /*							       */
 2079: /*  Application-callable completion match generator functions  */
 2080: /*							       */
 2081: /***************************************************************/
 2082: 
 2083: /* Return an array of (char *) which is a list of completions for TEXT.
 2084:    If there are no completions, return a NULL pointer.
 2085:    The first entry in the returned array is the substitution for TEXT.
 2086:    The remaining entries are the possible completions.
 2087:    The array is terminated with a NULL pointer.
 2088: 
 2089:    ENTRY_FUNCTION is a function of two args, and returns a (char *).
 2090:      The first argument is TEXT.
 2091:      The second is a state argument; it should be zero on the first call, and
 2092:      non-zero on subsequent calls.  It returns a NULL pointer to the caller
 2093:      when there are no more matches.
 2094:  */
 2095: char **
 2096: rl_completion_matches (text, entry_function)
 2097:      const char *text;
 2098:      rl_compentry_func_t *entry_function;
 2099: {
 2100:   register int i;
 2101: 
 2102:   /* Number of slots in match_list. */
 2103:   int match_list_size;
 2104: 
 2105:   /* The list of matches. */
 2106:   char **match_list;
 2107: 
 2108:   /* Number of matches actually found. */
 2109:   int matches;
 2110: 
 2111:   /* Temporary string binder. */
 2112:   char *string;
 2113: 
 2114:   matches = 0;
 2115:   match_list_size = 10;
 2116:   match_list = (char **)xmalloc ((match_list_size + 1) * sizeof (char *));
 2117:   match_list[1] = (char *)NULL;
 2118: 
 2119:   while (string = (*entry_function) (text, matches))
 2120:     {
 2121:       if (RL_SIG_RECEIVED ())
 2122: 	{
 2123: 	  /* Start at 1 because we don't set matches[0] in this function.
 2124: 	     Only free the list members if we're building match list from
 2125: 	     rl_filename_completion_function, since we know that doesn't
 2126: 	     free the strings it returns. */
 2127: 	  if (entry_function == rl_filename_completion_function)
 2128: 	    {
 2129: 	      for (i = 1; match_list[i]; i++)
 2130: 		xfree (match_list[i]);
 2131: 	    }
 2132: 	  xfree (match_list);
 2133: 	  match_list = 0;
 2134: 	  match_list_size = 0;
 2135: 	  matches = 0;
 2136: 	  RL_CHECK_SIGNALS ();
 2137: 	}
 2138: 
 2139:       if (matches + 1 >= match_list_size)
 2140: 	match_list = (char **)xrealloc
 2141: 	  (match_list, ((match_list_size += 10) + 1) * sizeof (char *));
 2142: 
 2143:       if (match_list == 0)
 2144: 	return (match_list);
 2145: 
 2146:       match_list[++matches] = string;
 2147:       match_list[matches + 1] = (char *)NULL;
 2148:     }
 2149: 
 2150:   /* If there were any matches, then look through them finding out the
 2151:      lowest common denominator.  That then becomes match_list[0]. */
 2152:   if (matches)
 2153:     compute_lcd_of_matches (match_list, matches, text);
 2154:   else				/* There were no matches. */
 2155:     {
 2156:       xfree (match_list);
 2157:       match_list = (char **)NULL;
 2158:     }
 2159:   return (match_list);
 2160: }
 2161: 
 2162: /* A completion function for usernames.
 2163:    TEXT contains a partial username preceded by a random
 2164:    character (usually `~').  */
 2165: char *
 2166: rl_username_completion_function (text, state)
 2167:      const char *text;
 2168:      int state;
 2169: {
 2170: #if defined (__WIN32__) || defined (__OPENNT)
 2171:   return (char *)NULL;
 2172: #else /* !__WIN32__ && !__OPENNT) */
 2173:   static char *username = (char *)NULL;
 2174:   static struct passwd *entry;
 2175:   static int namelen, first_char, first_char_loc;
 2176:   char *value;
 2177: 
 2178:   if (state == 0)
 2179:     {
 2180:       FREE (username);
 2181: 
 2182:       first_char = *text;
 2183:       first_char_loc = first_char == '~';
 2184: 
 2185:       username = savestring (&text[first_char_loc]);
 2186:       namelen = strlen (username);
 2187: #if defined (HAVE_GETPWENT)
 2188:       setpwent ();
 2189: #endif
 2190:     }
 2191: 
 2192: #if defined (HAVE_GETPWENT)
 2193:   while (entry = getpwent ())
 2194:     {
 2195:       /* Null usernames should result in all users as possible completions. */
 2196:       if (namelen == 0 || (STREQN (username, entry->pw_name, namelen)))
 2197: 	break;
 2198:     }
 2199: #endif
 2200: 
 2201:   if (entry == 0)
 2202:     {
 2203: #if defined (HAVE_GETPWENT)
 2204:       endpwent ();
 2205: #endif
 2206:       return ((char *)NULL);
 2207:     }
 2208:   else
 2209:     {
 2210:       value = (char *)xmalloc (2 + strlen (entry->pw_name));
 2211: 
 2212:       *value = *text;
 2213: 
 2214:       strcpy (value + first_char_loc, entry->pw_name);
 2215: 
 2216:       if (first_char == '~')
 2217: 	rl_filename_completion_desired = 1;
 2218: 
 2219:       return (value);
 2220:     }
 2221: #endif /* !__WIN32__ && !__OPENNT */
 2222: }
 2223: 
 2224: /* Return non-zero if CONVFN matches FILENAME up to the length of FILENAME
 2225:    (FILENAME_LEN).  If _rl_completion_case_fold is set, compare without
 2226:    regard to the alphabetic case of characters.  If
 2227:    _rl_completion_case_map is set, make `-' and `_' equivalent.  CONVFN is
 2228:    the possibly-converted directory entry; FILENAME is what the user typed. */
 2229: static int
 2230: complete_fncmp (convfn, convlen, filename, filename_len)
 2231:      const char *convfn;
 2232:      int convlen;
 2233:      const char *filename;
 2234:      int filename_len;
 2235: {
 2236:   register char *s1, *s2;
 2237:   int d, len;
 2238: #if defined (HANDLE_MULTIBYTE)
 2239:   size_t v1, v2;
 2240:   mbstate_t ps1, ps2;
 2241:   wchar_t wc1, wc2;
 2242: #endif
 2243: 
 2244: #if defined (HANDLE_MULTIBYTE)
 2245:   memset (&ps1, 0, sizeof (mbstate_t));
 2246:   memset (&ps2, 0, sizeof (mbstate_t));
 2247: #endif
 2248: 
 2249:   if (filename_len == 0)
 2250:     return 1;
 2251:   if (convlen < filename_len)
 2252:     return 0;
 2253: 
 2254:   len = filename_len;
 2255:   s1 = (char *)convfn;
 2256:   s2 = (char *)filename;
 2257: 
 2258:   /* Otherwise, if these match up to the length of filename, then
 2259:      it is a match. */
 2260:   if (_rl_completion_case_fold && _rl_completion_case_map)
 2261:     {
 2262:       /* Case-insensitive comparison treating _ and - as equivalent */
 2263: #if defined (HANDLE_MULTIBYTE)
 2264:       if (MB_CUR_MAX > 1 && rl_byte_oriented == 0)
 2265: 	{
 2266: 	  do
 2267: 	    {
 2268: 	      v1 = mbrtowc (&wc1, s1, convlen, &ps1);
 2269: 	      v2 = mbrtowc (&wc2, s2, filename_len, &ps2);
 2270: 	      if (v1 == 0 && v2 == 0)
 2271: 		return 1;
 2272: 	      else if (MB_INVALIDCH (v1) || MB_INVALIDCH (v2))
 2273: 		{
 2274: 		  if (*s1 != *s2)		/* do byte comparison */
 2275: 		    return 0;
 2276: 		  else if ((*s1 == '-' || *s1 == '_') && (*s2 == '-' || *s2 == '_'))
 2277: 		    return 0;
 2278: 		  s1++; s2++; len--;
 2279: 		  continue;
 2280: 		}
 2281: 	      wc1 = towlower (wc1);
 2282: 	      wc2 = towlower (wc2);
 2283: 	      s1 += v1;
 2284: 	      s2 += v1;
 2285: 	      len -= v1;
 2286: 	      if ((wc1 == L'-' || wc1 == L'_') && (wc2 == L'-' || wc2 == L'_'))
 2287: 	        continue;
 2288: 	      if (wc1 != wc2)
 2289: 		return 0;
 2290: 	    }
 2291: 	  while (len != 0);
 2292: 	}
 2293:       else
 2294: #endif
 2295: 	{
 2296: 	do
 2297: 	  {
 2298: 	    d = _rl_to_lower (*s1) - _rl_to_lower (*s2);
 2299: 	    /* *s1 == [-_] && *s2 == [-_] */
 2300: 	    if ((*s1 == '-' || *s1 == '_') && (*s2 == '-' || *s2 == '_'))
 2301: 	      d = 0;
 2302: 	    if (d != 0)
 2303: 	      return 0;
 2304: 	    s1++; s2++;	/* already checked convlen >= filename_len */
 2305: 	  }
 2306: 	while (--len != 0);
 2307: 	}
 2308: 
 2309:       return 1;
 2310:     }
 2311:   else if (_rl_completion_case_fold)
 2312:     {
 2313: #if defined (HANDLE_MULTIBYTE)
 2314:       if (MB_CUR_MAX > 1 && rl_byte_oriented == 0)
 2315: 	{
 2316: 	  do
 2317: 	    {
 2318: 	      v1 = mbrtowc (&wc1, s1, convlen, &ps1);
 2319: 	      v2 = mbrtowc (&wc2, s2, filename_len, &ps2);
 2320: 	      if (v1 == 0 && v2 == 0)
 2321: 		return 1;
 2322: 	      else if (MB_INVALIDCH (v1) || MB_INVALIDCH (v2))
 2323: 		{
 2324: 		  if (*s1 != *s2)		/* do byte comparison */
 2325: 		    return 0;
 2326: 		  s1++; s2++; len--;
 2327: 		  continue;
 2328: 		}
 2329: 	      wc1 = towlower (wc1);
 2330: 	      wc2 = towlower (wc2);
 2331: 	      if (wc1 != wc2)
 2332: 		return 0;
 2333: 	      s1 += v1;
 2334: 	      s2 += v1;
 2335: 	      len -= v1;
 2336: 	    }
 2337: 	  while (len != 0);
 2338: 	  return 1;
 2339: 	}
 2340:       else
 2341: #endif
 2342:       if ((_rl_to_lower (convfn[0]) == _rl_to_lower (filename[0])) &&
 2343: 	  (convlen >= filename_len) &&
 2344: 	  (_rl_strnicmp (filename, convfn, filename_len) == 0))
 2345: 	return 1;
 2346:     }
 2347:   else
 2348:     {
 2349:       if ((convfn[0] == filename[0]) &&
 2350: 	  (convlen >= filename_len) &&
 2351: 	  (strncmp (filename, convfn, filename_len) == 0))
 2352: 	return 1;
 2353:     }
 2354:   return 0;
 2355: }
 2356: 
 2357: /* Okay, now we write the entry_function for filename completion.  In the
 2358:    general case.  Note that completion in the shell is a little different
 2359:    because of all the pathnames that must be followed when looking up the
 2360:    completion for a command. */
 2361: char *
 2362: rl_filename_completion_function (text, state)
 2363:      const char *text;
 2364:      int state;
 2365: {
 2366:   static DIR *directory = (DIR *)NULL;
 2367:   static char *filename = (char *)NULL;
 2368:   static char *dirname = (char *)NULL;
 2369:   static char *users_dirname = (char *)NULL;
 2370:   static int filename_len;
 2371:   char *temp, *dentry, *convfn;
 2372:   int dirlen, dentlen, convlen;
 2373:   struct dirent *entry;
 2374: 
 2375:   /* If we don't have any state, then do some initialization. */
 2376:   if (state == 0)
 2377:     {
 2378:       /* If we were interrupted before closing the directory or reading
 2379: 	 all of its contents, close it. */
 2380:       if (directory)
 2381: 	{
 2382: 	  closedir (directory);
 2383: 	  directory = (DIR *)NULL;
 2384: 	}
 2385:       FREE (dirname);
 2386:       FREE (filename);
 2387:       FREE (users_dirname);
 2388: 
 2389:       filename = savestring (text);
 2390:       if (*text == 0)
 2391: 	text = ".";
 2392:       dirname = savestring (text);
 2393: 
 2394:       temp = strrchr (dirname, '/');
 2395: 
 2396: #if defined (__MSDOS__)
 2397:       /* special hack for //X/... */
 2398:       if (dirname[0] == '/' && dirname[1] == '/' && ISALPHA ((unsigned char)dirname[2]) && dirname[3] == '/')
 2399:         temp = strrchr (dirname + 3, '/');
 2400: #endif
 2401: 
 2402:       if (temp)
 2403: 	{
 2404: 	  strcpy (filename, ++temp);
 2405: 	  *temp = '\0';
 2406: 	}
 2407: #if defined (__MSDOS__)
 2408:       /* searches from current directory on the drive */
 2409:       else if (ISALPHA ((unsigned char)dirname[0]) && dirname[1] == ':')
 2410:         {
 2411:           strcpy (filename, dirname + 2);
 2412:           dirname[2] = '\0';
 2413:         }
 2414: #endif
 2415:       else
 2416: 	{
 2417: 	  dirname[0] = '.';
 2418: 	  dirname[1] = '\0';
 2419: 	}
 2420: 
 2421:       /* We aren't done yet.  We also support the "~user" syntax. */
 2422: 
 2423:       /* Save the version of the directory that the user typed, dequoting
 2424: 	 it if necessary. */
 2425:       if (rl_completion_found_quote && rl_filename_dequoting_function)
 2426: 	users_dirname = (*rl_filename_dequoting_function) (dirname, rl_completion_quote_character);
 2427:       else
 2428: 	users_dirname = savestring (dirname);
 2429: 
 2430:       if (*dirname == '~')
 2431: 	{
 2432: 	  temp = tilde_expand (dirname);
 2433: 	  xfree (dirname);
 2434: 	  dirname = temp;
 2435: 	}
 2436: 
 2437:       /* We have saved the possibly-dequoted version of the directory name
 2438: 	 the user typed.  Now transform the directory name we're going to
 2439: 	 pass to opendir(2).  The directory rewrite hook modifies only the
 2440: 	 directory name; the directory completion hook modifies both the
 2441: 	 directory name passed to opendir(2) and the version the user
 2442: 	 typed.  Both the directory completion and rewrite hooks should perform
 2443: 	 any necessary dequoting.  The hook functions return 1 if they modify
 2444: 	 the directory name argument.  If either hook returns 0, it should
 2445: 	 not modify the directory name pointer passed as an argument. */
 2446:       if (rl_directory_rewrite_hook)
 2447: 	(*rl_directory_rewrite_hook) (&dirname);
 2448:       else if (rl_directory_completion_hook && (*rl_directory_completion_hook) (&dirname))
 2449: 	{
 2450: 	  xfree (users_dirname);
 2451: 	  users_dirname = savestring (dirname);
 2452: 	}
 2453:       else if (rl_completion_found_quote && rl_filename_dequoting_function)
 2454: 	{
 2455: 	  /* delete single and double quotes */
 2456: 	  xfree (dirname);
 2457: 	  dirname = savestring (users_dirname);
 2458: 	}
 2459:       directory = opendir (dirname);
 2460: 
 2461:       /* Now dequote a non-null filename.  FILENAME will not be NULL, but may
 2462: 	 be empty. */
 2463:       if (*filename && rl_completion_found_quote && rl_filename_dequoting_function)
 2464: 	{
 2465: 	  /* delete single and double quotes */
 2466: 	  temp = (*rl_filename_dequoting_function) (filename, rl_completion_quote_character);
 2467: 	  xfree (filename);
 2468: 	  filename = temp;
 2469: 	}
 2470:       filename_len = strlen (filename);
 2471: 
 2472:       rl_filename_completion_desired = 1;
 2473:     }
 2474: 
 2475:   /* At this point we should entertain the possibility of hacking wildcarded
 2476:      filenames, like /usr/man/man<WILD>/te<TAB>.  If the directory name
 2477:      contains globbing characters, then build an array of directories, and
 2478:      then map over that list while completing. */
 2479:   /* *** UNIMPLEMENTED *** */
 2480: 
 2481:   /* Now that we have some state, we can read the directory. */
 2482: 
 2483:   entry = (struct dirent *)NULL;
 2484:   while (directory && (entry = readdir (directory)))
 2485:     {
 2486:       convfn = dentry = entry->d_name;
 2487:       convlen = dentlen = D_NAMLEN (entry);
 2488: 
 2489:       if (rl_filename_rewrite_hook)
 2490: 	{
 2491: 	  convfn = (*rl_filename_rewrite_hook) (dentry, dentlen);
 2492: 	  convlen = (convfn == dentry) ? dentlen : strlen (convfn);
 2493: 	}
 2494: 
 2495:       /* Special case for no filename.  If the user has disabled the
 2496:          `match-hidden-files' variable, skip filenames beginning with `.'.
 2497: 	 All other entries except "." and ".." match. */
 2498:       if (filename_len == 0)
 2499: 	{
 2500: 	  if (_rl_match_hidden_files == 0 && HIDDEN_FILE (convfn))
 2501: 	    continue;
 2502: 
 2503: 	  if (convfn[0] != '.' ||
 2504: 	       (convfn[1] && (convfn[1] != '.' || convfn[2])))
 2505: 	    break;
 2506: 	}
 2507:       else
 2508: 	{
 2509: 	  if (complete_fncmp (convfn, convlen, filename, filename_len))
 2510: 	    break;
 2511: 	}
 2512:     }
 2513: 
 2514:   if (entry == 0)
 2515:     {
 2516:       if (directory)
 2517: 	{
 2518: 	  closedir (directory);
 2519: 	  directory = (DIR *)NULL;
 2520: 	}
 2521:       if (dirname)
 2522: 	{
 2523: 	  xfree (dirname);
 2524: 	  dirname = (char *)NULL;
 2525: 	}
 2526:       if (filename)
 2527: 	{
 2528: 	  xfree (filename);
 2529: 	  filename = (char *)NULL;
 2530: 	}
 2531:       if (users_dirname)
 2532: 	{
 2533: 	  xfree (users_dirname);
 2534: 	  users_dirname = (char *)NULL;
 2535: 	}
 2536: 
 2537:       return (char *)NULL;
 2538:     }
 2539:   else
 2540:     {
 2541:       /* dirname && (strcmp (dirname, ".") != 0) */
 2542:       if (dirname && (dirname[0] != '.' || dirname[1]))
 2543: 	{
 2544: 	  if (rl_complete_with_tilde_expansion && *users_dirname == '~')
 2545: 	    {
 2546: 	      dirlen = strlen (dirname);
 2547: 	      temp = (char *)xmalloc (2 + dirlen + D_NAMLEN (entry));
 2548: 	      strcpy (temp, dirname);
 2549: 	      /* Canonicalization cuts off any final slash present.  We
 2550: 		 may need to add it back. */
 2551: 	      if (dirname[dirlen - 1] != '/')
 2552: 	        {
 2553: 	          temp[dirlen++] = '/';
 2554: 	          temp[dirlen] = '\0';
 2555: 	        }
 2556: 	    }
 2557: 	  else
 2558: 	    {
 2559: 	      dirlen = strlen (users_dirname);
 2560: 	      temp = (char *)xmalloc (2 + dirlen + D_NAMLEN (entry));
 2561: 	      strcpy (temp, users_dirname);
 2562: 	      /* Make sure that temp has a trailing slash here. */
 2563: 	      if (users_dirname[dirlen - 1] != '/')
 2564: 		temp[dirlen++] = '/';
 2565: 	    }
 2566: 
 2567: 	  strcpy (temp + dirlen, convfn);
 2568: 	}
 2569:       else
 2570: 	temp = savestring (convfn);
 2571: 
 2572:       if (convfn != dentry)
 2573: 	xfree (convfn);
 2574: 
 2575:       return (temp);
 2576:     }
 2577: }
 2578: 
 2579: /* An initial implementation of a menu completion function a la tcsh.  The
 2580:    first time (if the last readline command was not rl_old_menu_complete), we
 2581:    generate the list of matches.  This code is very similar to the code in
 2582:    rl_complete_internal -- there should be a way to combine the two.  Then,
 2583:    for each item in the list of matches, we insert the match in an undoable
 2584:    fashion, with the appropriate character appended (this happens on the
 2585:    second and subsequent consecutive calls to rl_old_menu_complete).  When we
 2586:    hit the end of the match list, we restore the original unmatched text,
 2587:    ring the bell, and reset the counter to zero. */
 2588: int
 2589: rl_old_menu_complete (count, invoking_key)
 2590:      int count, invoking_key;
 2591: {
 2592:   rl_compentry_func_t *our_func;
 2593:   int matching_filenames, found_quote;
 2594: 
 2595:   static char *orig_text;
 2596:   static char **matches = (char **)0;
 2597:   static int match_list_index = 0;
 2598:   static int match_list_size = 0;
 2599:   static int orig_start, orig_end;
 2600:   static char quote_char;
 2601:   static int delimiter;
 2602: 
 2603:   /* The first time through, we generate the list of matches and set things
 2604:      up to insert them. */
 2605:   if (rl_last_func != rl_old_menu_complete)
 2606:     {
 2607:       /* Clean up from previous call, if any. */
 2608:       FREE (orig_text);
 2609:       if (matches)
 2610: 	_rl_free_match_list (matches);
 2611: 
 2612:       match_list_index = match_list_size = 0;
 2613:       matches = (char **)NULL;
 2614: 
 2615:       rl_completion_invoking_key = invoking_key;
 2616: 
 2617:       RL_SETSTATE(RL_STATE_COMPLETING);
 2618: 
 2619:       /* Only the completion entry function can change these. */
 2620:       set_completion_defaults ('%');
 2621: 
 2622:       our_func = rl_menu_completion_entry_function;
 2623:       if (our_func == 0)
 2624: 	our_func = rl_completion_entry_function
 2625: 			? rl_completion_entry_function
 2626: 			: rl_filename_completion_function;
 2627: 
 2628:       /* We now look backwards for the start of a filename/variable word. */
 2629:       orig_end = rl_point;
 2630:       found_quote = delimiter = 0;
 2631:       quote_char = '\0';
 2632: 
 2633:       if (rl_point)
 2634: 	/* This (possibly) changes rl_point.  If it returns a non-zero char,
 2635: 	   we know we have an open quote. */
 2636: 	quote_char = _rl_find_completion_word (&found_quote, &delimiter);
 2637: 
 2638:       orig_start = rl_point;
 2639:       rl_point = orig_end;
 2640: 
 2641:       orig_text = rl_copy_text (orig_start, orig_end);
 2642:       matches = gen_completion_matches (orig_text, orig_start, orig_end,
 2643: 					our_func, found_quote, quote_char);
 2644: 
 2645:       /* If we are matching filenames, the attempted completion function will
 2646: 	 have set rl_filename_completion_desired to a non-zero value.  The basic
 2647: 	 rl_filename_completion_function does this. */
 2648:       matching_filenames = rl_filename_completion_desired;
 2649: 
 2650:       if (matches == 0 || postprocess_matches (&matches, matching_filenames) == 0)
 2651: 	{
 2652: 	  rl_ding ();
 2653: 	  FREE (matches);
 2654: 	  matches = (char **)0;
 2655: 	  FREE (orig_text);
 2656: 	  orig_text = (char *)0;
 2657: 	  completion_changed_buffer = 0;
 2658: 	  RL_UNSETSTATE(RL_STATE_COMPLETING);
 2659: 	  return (0);
 2660: 	}
 2661: 
 2662:       RL_UNSETSTATE(RL_STATE_COMPLETING);
 2663: 
 2664:       for (match_list_size = 0; matches[match_list_size]; match_list_size++)
 2665:         ;
 2666:       /* matches[0] is lcd if match_list_size > 1, but the circular buffer
 2667: 	 code below should take care of it. */
 2668: 
 2669:       if (match_list_size > 1 && _rl_complete_show_all)
 2670: 	display_matches (matches);
 2671:     }
 2672: 
 2673:   /* Now we have the list of matches.  Replace the text between
 2674:      rl_line_buffer[orig_start] and rl_line_buffer[rl_point] with
 2675:      matches[match_list_index], and add any necessary closing char. */
 2676: 
 2677:   if (matches == 0 || match_list_size == 0) 
 2678:     {
 2679:       rl_ding ();
 2680:       FREE (matches);
 2681:       matches = (char **)0;
 2682:       completion_changed_buffer = 0;
 2683:       return (0);
 2684:     }
 2685: 
 2686:   match_list_index += count;
 2687:   if (match_list_index < 0)
 2688:     {
 2689:       while (match_list_index < 0)
 2690: 	match_list_index += match_list_size;
 2691:     }
 2692:   else
 2693:     match_list_index %= match_list_size;
 2694: 
 2695:   if (match_list_index == 0 && match_list_size > 1)
 2696:     {
 2697:       rl_ding ();
 2698:       insert_match (orig_text, orig_start, MULT_MATCH, &quote_char);
 2699:     }
 2700:   else
 2701:     {
 2702:       insert_match (matches[match_list_index], orig_start, SINGLE_MATCH, &quote_char);
 2703:       append_to_match (matches[match_list_index], delimiter, quote_char,
 2704: 		       strcmp (orig_text, matches[match_list_index]));
 2705:     }
 2706: 
 2707:   completion_changed_buffer = 1;
 2708:   return (0);
 2709: }
 2710: 
 2711: int
 2712: rl_menu_complete (count, ignore)
 2713:      int count, ignore;
 2714: {
 2715:   rl_compentry_func_t *our_func;
 2716:   int matching_filenames, found_quote;
 2717: 
 2718:   static char *orig_text;
 2719:   static char **matches = (char **)0;
 2720:   static int match_list_index = 0;
 2721:   static int match_list_size = 0;
 2722:   static int nontrivial_lcd = 0;
 2723:   static int full_completion = 0;	/* set to 1 if menu completion should reinitialize on next call */
 2724:   static int orig_start, orig_end;
 2725:   static char quote_char;
 2726:   static int delimiter, cstate;
 2727: 
 2728:   /* The first time through, we generate the list of matches and set things
 2729:      up to insert them. */
 2730:   if ((rl_last_func != rl_menu_complete && rl_last_func != rl_backward_menu_complete) || full_completion)
 2731:     {
 2732:       /* Clean up from previous call, if any. */
 2733:       FREE (orig_text);
 2734:       if (matches)
 2735: 	_rl_free_match_list (matches);
 2736: 
 2737:       match_list_index = match_list_size = 0;
 2738:       matches = (char **)NULL;
 2739: 
 2740:       full_completion = 0;
 2741: 
 2742:       RL_SETSTATE(RL_STATE_COMPLETING);
 2743: 
 2744:       /* Only the completion entry function can change these. */
 2745:       set_completion_defaults ('%');
 2746: 
 2747:       our_func = rl_menu_completion_entry_function;
 2748:       if (our_func == 0)
 2749: 	our_func = rl_completion_entry_function
 2750: 			? rl_completion_entry_function
 2751: 			: rl_filename_completion_function;
 2752: 
 2753:       /* We now look backwards for the start of a filename/variable word. */
 2754:       orig_end = rl_point;
 2755:       found_quote = delimiter = 0;
 2756:       quote_char = '\0';
 2757: 
 2758:       if (rl_point)
 2759: 	/* This (possibly) changes rl_point.  If it returns a non-zero char,
 2760: 	   we know we have an open quote. */
 2761: 	quote_char = _rl_find_completion_word (&found_quote, &delimiter);
 2762: 
 2763:       orig_start = rl_point;
 2764:       rl_point = orig_end;
 2765: 
 2766:       orig_text = rl_copy_text (orig_start, orig_end);
 2767:       matches = gen_completion_matches (orig_text, orig_start, orig_end,
 2768: 					our_func, found_quote, quote_char);
 2769: 
 2770:       nontrivial_lcd = matches && strcmp (orig_text, matches[0]) != 0;
 2771: 
 2772:       /* If we are matching filenames, the attempted completion function will
 2773: 	 have set rl_filename_completion_desired to a non-zero value.  The basic
 2774: 	 rl_filename_completion_function does this. */
 2775:       matching_filenames = rl_filename_completion_desired;
 2776: 
 2777:       if (matches == 0 || postprocess_matches (&matches, matching_filenames) == 0)
 2778: 	{
 2779: 	  rl_ding ();
 2780: 	  FREE (matches);
 2781: 	  matches = (char **)0;
 2782: 	  FREE (orig_text);
 2783: 	  orig_text = (char *)0;
 2784: 	  completion_changed_buffer = 0;
 2785: 	  RL_UNSETSTATE(RL_STATE_COMPLETING);
 2786: 	  return (0);
 2787: 	}
 2788: 
 2789:       RL_UNSETSTATE(RL_STATE_COMPLETING);
 2790: 
 2791:       for (match_list_size = 0; matches[match_list_size]; match_list_size++)
 2792:         ;
 2793: 
 2794:       if (match_list_size == 0) 
 2795: 	{
 2796: 	  rl_ding ();
 2797: 	  FREE (matches);
 2798: 	  matches = (char **)0;
 2799: 	  match_list_index = 0;
 2800: 	  completion_changed_buffer = 0;
 2801: 	  return (0);
 2802:         }
 2803: 
 2804:       /* matches[0] is lcd if match_list_size > 1, but the circular buffer
 2805: 	 code below should take care of it. */
 2806:       if (*matches[0])
 2807: 	{
 2808: 	  insert_match (matches[0], orig_start, matches[1] ? MULT_MATCH : SINGLE_MATCH, &quote_char);
 2809: 	  orig_end = orig_start + strlen (matches[0]);
 2810: 	  completion_changed_buffer = STREQ (orig_text, matches[0]) == 0;
 2811: 	}
 2812: 
 2813:       if (match_list_size > 1 && _rl_complete_show_all)
 2814: 	{
 2815: 	  display_matches (matches);
 2816: 	  /* If there are so many matches that the user has to be asked
 2817: 	     whether or not he wants to see the matches, menu completion
 2818: 	     is unwieldy. */
 2819: 	  if (rl_completion_query_items > 0 && match_list_size >= rl_completion_query_items)
 2820: 	    {
 2821: 	      rl_ding ();
 2822: 	      FREE (matches);
 2823: 	      matches = (char **)0;
 2824: 	      full_completion = 1;
 2825: 	      return (0);
 2826: 	    }
 2827: 	  else if (_rl_menu_complete_prefix_first)
 2828: 	    {
 2829: 	      rl_ding ();
 2830: 	      return (0);
 2831: 	    }
 2832: 	}
 2833:       else if (match_list_size <= 1)
 2834: 	{
 2835: 	  append_to_match (matches[0], delimiter, quote_char, nontrivial_lcd);
 2836: 	  full_completion = 1;
 2837: 	  return (0);
 2838: 	}
 2839:       else if (_rl_menu_complete_prefix_first && match_list_size > 1)
 2840: 	{
 2841: 	  rl_ding ();
 2842: 	  return (0);
 2843: 	}
 2844:     }
 2845: 
 2846:   /* Now we have the list of matches.  Replace the text between
 2847:      rl_line_buffer[orig_start] and rl_line_buffer[rl_point] with
 2848:      matches[match_list_index], and add any necessary closing char. */
 2849: 
 2850:   if (matches == 0 || match_list_size == 0) 
 2851:     {
 2852:       rl_ding ();
 2853:       FREE (matches);
 2854:       matches = (char **)0;
 2855:       completion_changed_buffer = 0;
 2856:       return (0);
 2857:     }
 2858: 
 2859:   match_list_index += count;
 2860:   if (match_list_index < 0)
 2861:     {
 2862:       while (match_list_index < 0)
 2863: 	match_list_index += match_list_size;
 2864:     }
 2865:   else
 2866:     match_list_index %= match_list_size;
 2867: 
 2868:   if (match_list_index == 0 && match_list_size > 1)
 2869:     {
 2870:       rl_ding ();
 2871:       insert_match (matches[0], orig_start, MULT_MATCH, &quote_char);
 2872:     }
 2873:   else
 2874:     {
 2875:       insert_match (matches[match_list_index], orig_start, SINGLE_MATCH, &quote_char);
 2876:       append_to_match (matches[match_list_index], delimiter, quote_char,
 2877: 		       strcmp (orig_text, matches[match_list_index]));
 2878:     }
 2879: 
 2880:   completion_changed_buffer = 1;
 2881:   return (0);
 2882: }
 2883: 
 2884: int
 2885: rl_backward_menu_complete (count, key)
 2886:      int count, key;
 2887: {
 2888:   /* Positive arguments to backward-menu-complete translate into negative
 2889:      arguments for menu-complete, and vice versa. */
 2890:   return (rl_menu_complete (-count, key));
 2891: }

FreeBSD-CVSweb <freebsd-cvsweb@FreeBSD.org>