TheGNUGeneralPublicLicenseisoftenshippedwithGNUsoftware,and isgenerallykeptinafilecalledCOPYINGorLICENSE.Ifyoudonot haveacopyofthelicense,writetotheFreeSoftwareFoundation,
51 Franklin Street, Fifth Floor, Boston, MA 02110-1335 USA. */ #define READLINE_LIBRARY
#ifdefined (HAVE_CONFIG_H) # include "config_readline.h" #endif
#include <sys/types.h> #include <fcntl.h> /* FreeBSD 5.3 will not declare u_int in sys/types.h, file.h needs it */ #ifdefined (HAVE_SYS_FILE_H) && !defined(__FreeBSD__) # include <sys/file.h> #endif
#ifdefined (HAVE_UNISTD_H) # include <unistd.h> #endif/* HAVE_UNISTD_H */
#ifdefined (HAVE_STDLIB_H) # include <stdlib.h> #else # include "ansi_stdlib.h" #endif/* HAVE_STDLIB_H */
/* Unix version of a hidden file. Could be different on other systems. */ #define HIDDEN_FILE(fname) ((fname)[0] == '.')
/* Most systems don't declare getpwent in <pwd.h> if _POSIX_SOURCE is
defined. */ #ifdefined (HAVE_GETPWENT) && (!defined (HAVE_GETPW_DECLS) || defined (_POSIX_SOURCE)) externstruct passwd *getpwent PARAMS((void)); #endif/* HAVE_GETPWENT && (!HAVE_GETPW_DECLS || _POSIX_SOURCE) */
/* If non-zero, then this is the address of a function to call when completingawordwouldnormallydisplaythelistofpossiblematches. Thisfunctioniscalledinsteadofactuallydoingthedisplay. Ittakesthreearguments:(char**matches,intnum_matches,intmax_length) whereMATCHESisthearrayofstringsthatmatched,NUM_MATCHESisthe numberofstringsinthatarray,andMAX_LENGTHisthelengthofthe
longest string in that array. */
rl_compdisp_func_t *rl_completion_display_matches_hook = (rl_compdisp_func_t *)NULL;
/* **************************************************************** */ /* */ /* Completion matching, from readline's point of view. */ /* */ /* **************************************************************** */
/* Variables known only to the readline library. */
/* If non-zero, non-unique completions always show the list of matches. */ int _rl_complete_show_all = 0;
/* If non-zero, non-unique completions show the list of matches, unless it
is not possible to do partial completion and modify the line. */ int _rl_complete_show_unmodified = 0;
/* If non-zero, completed directory names have a slash appended. */ int _rl_complete_mark_directories = 1;
/* If non-zero, the symlinked directory completion behavior introduced in readline-4.2aisdisabled,andsymlinksthatpointtodirectorieshave aslashappended(subjecttothevalueof_rl_complete_mark_directories).
This is user-settable via the mark-symlinked-directories variable. */ int _rl_complete_mark_symlink_dirs = 0;
/* If non-zero, completions are printed horizontally in alphabetical order,
like `ls -x'. */ int _rl_print_completions_horizontally;
/* Non-zero means that case is not significant in filename completion. */ #ifdefined (__MSDOS__) && !defined (__DJGPP__) int _rl_completion_case_fold = 1; #else int _rl_completion_case_fold; #endif
/* If non-zero, don't match hidden files (filenames beginning with a `.' on
Unix) when doing filename completion. */ int _rl_match_hidden_files = 1;
/* Global variables available to applications using readline. */
#ifdefined (VISIBLE_STATS) /* Non-zero means add an additional character to each filename displayed duringlistingcompletioniffrl_filename_completion_desiredwhichhelps
to indicate the type of file being listed. */ int rl_visible_stats = 0; #endif/* VISIBLE_STATS */
/* If non-zero, then this is the address of a function to call when completingonadirectoryname.Thefunctioniscalledwith
the address of a string (the current directory name) as an arg. */
rl_icppfunc_t *rl_directory_completion_hook = (rl_icppfunc_t *)NULL;
/* Non-zero means readline completion functions perform tilde expansion. */ int rl_complete_with_tilde_expansion = 0;
/* Pointer to the generator function for completion_matches (). NULLmeanstouserl_filename_completion_function(),thedefaultfilename
completer. */
rl_compentry_func_t *rl_completion_entry_function = (rl_compentry_func_t *)NULL;
/* Pointer to alternative function to create matches. FunctioniscalledwithTEXT,START,andEND. STARTandENDareindicesinRL_LINE_BUFFERsayingwhattheboundaries ofTEXTare. IfthisfunctionexistsandreturnsNULLthencallthevalueof rl_completion_entry_functiontotrytomatch,otherwiseusethe
array of strings returned. */
rl_completion_func_t *rl_attempted_completion_function = (rl_completion_func_t *)NULL;
/* Non-zero means to suppress normal filename completion after the
user-specified completion function has been called. */ int rl_attempted_completion_over = 0;
/* Set to a character indicating the type of completion being performed byrl_complete_internal,availableforusebyapplicationcompletion
functions. */ int rl_completion_type = 0;
/* Up to this many items will be displayed in response to a possible-completionscall.Afterthat,weasktheuserif sheissureshewantstoseethemall.Anegativevaluemeans
don't ask. */ int rl_completion_query_items = 100;
int _rl_page_completions = 1;
/* The basic list of characters that signal a break between words for the completerroutine.Thecontentsofthisvariableiswhatbreakswords
in the shell, i.e. " \t\n\"\\'`@$><=" */ constchar *rl_basic_word_break_characters = " \t\n\"\\'`@$><=;|&{("; /* }) */
/* List of basic quoting characters. */ constchar *rl_basic_quote_characters = "\"'";
/* The list of characters that signal a break between words for rl_complete_internal.Thedefaultlististhecontentsof
rl_basic_word_break_characters. */ /*const*/ char *rl_completer_word_break_characters = (/*const*/ char *)NULL;
/* Hook function to allow an application to set the completion word breakcharactersbeforereadlinebreaksuptheline.Allows
position-dependent word break characters. */
rl_cpvfunc_t *rl_completion_word_break_hook = (rl_cpvfunc_t *)NULL;
/* List of characters which can be used to quote a substring of the line. Completionoccursontheentiresubstring,andwithinthesubstring rl_completer_word_break_charactersaretreatedasanyothercharacter,
unless they also appear within this list. */ constchar *rl_completer_quote_characters = (constchar *)NULL;
/* List of characters that should be quoted in filenames by the completer. */ constchar *rl_filename_quote_characters = (constchar *)NULL;
/* List of characters that are word break characters, but should be left inTEXTwhenitispassedtothecompletionfunction.Theshelluses
this to help determine what kind of completing to do. */ constchar *rl_special_prefixes = (constchar *)NULL;
/* If non-zero, then disallow duplicates in the matches. */ int rl_ignore_completion_duplicates = 1;
/* Non-zero means that the results of the matches are to be treated asfilenames.ThisisALWAYSzeroonentry,andcanonlybechanged
within a completion entry finder function. */ int rl_filename_completion_desired = 0;
/* Non-zero means that the results of the matches are to be quoted using doublequotes(oranapplication-specificquotingmechanism)ifthe filenamecontainsanycharactersinrl_filename_quote_chars.Thisis ALWAYSnon-zeroonentry,andcanonlybechangedwithinacompletion
entry finder function. */ int rl_filename_quoting_desired = 1;
/* This function, if defined, is called by the completer when real filenamecompletionisdone,afterallthematchingnameshavebeen generated.Itispasseda(char**)knownasmatchesinthecodebelow. ItconsistsofaNULL-terminatedarrayofpointerstopotential matchingstrings.The1stelement(matches[0])isthemaximal substringthatiscommontoallmatches.Thisfunctioncanre-arrange thelistofmatchesasrequired,butallelementsofthearraymustbe free()'diftheyaredeleted.Themainintentofthisfunctionis
to implement FIGNORE a la SunOS csh. */
rl_compignore_func_t *rl_ignore_some_completions_function = (rl_compignore_func_t *)NULL;
/* Set to a function to quote a filename in an application-specific fashion. Calledwiththetexttoquote,thetypeofmatchfound(singleormultiple) andapointertothequotingcharactertobeused,whichthefunctioncan
reset if desired. */
rl_quote_func_t *rl_filename_quoting_function = rl_quote_filename;
/* Function to call to remove quoting characters from a filename. Called beforecompletionisattempted,sotheembeddedquotesdonotinterfere withmatchingnamesinthefilesystem.Readlinedoesn'tdoanything
with this; it's set only by applications. */
rl_dequote_func_t *rl_filename_dequoting_function = (rl_dequote_func_t *)NULL;
/* Function to call to decide whether or not a word break character is quoted.Ifacharacterisquoted,itdoesnotbreakwordsforthe
completer. */
rl_linebuf_func_t *rl_char_is_quoted_p = (rl_linebuf_func_t *)NULL;
/* If non-zero, the completion functions don't append anything except a possibleclosingquote.Thisissetto0byrl_complete_internaland
may be changed by an application-specific completion function. */ int rl_completion_suppress_append = 0;
/* Character appended to completed words when at the end of the line. The
default is a space. */ int rl_completion_append_character = ' ';
/* If non-zero, the completion functions don't append any closing quote. Thisissetto0byrl_complete_internalandmaybechangedbyan
application-specific completion function. */ int rl_completion_suppress_quote = 0;
/* Set to any quote character readline thinks it finds before any application
completion function is called. */ int rl_completion_quote_character;
/* Set to a non-zero value if readline found quoting anywhere in the word to
be completed; set before any application completion function is called. */ int rl_completion_found_quote;
/* If non-zero, a slash will be appended to completed filenames that are symboliclinkstodirectorynames,subjecttothevalueofthe mark-directoriesvariable(whichisuser-settable).Thisexistsso thatapplicationcompletionfunctionscanoverridetheuser'spreference (setviathemark-symlinked-directoriesvariable)ifappropriate. It'ssettothevalueof_rl_complete_mark_symlink_dirsin rl_complete_internalbeforeanyapplication-specificcompletion functioniscalled,sowithoutthatfunctiondoinganything,theuser's
preferences are honored. */ int rl_completion_mark_symlink_dirs;
/* If non-zero, inhibit completion (temporarily). */ int rl_inhibit_completion;
/* Variables local to this file. */
/* Local variable states what happened during the last completion attempt. */ staticint completion_changed_buffer;
/* Complete the word at or before point. You have supplied the function thatdoestheinitialsimplematchingselectionalgorithm(see
rl_completion_matches ()). The default is to do filename completion. */ int
rl_complete (ignore, invoking_key) int ignore, invoking_key;
{ if (rl_inhibit_completion) return (_rl_insert_char (ignore, invoking_key)); elseif (rl_last_func == rl_complete && !completion_changed_buffer) return (rl_complete_internal ('?')); elseif (_rl_complete_show_all) return (rl_complete_internal ('!')); elseif (_rl_complete_show_unmodified) return (rl_complete_internal ('@')); else return (rl_complete_internal (TAB));
}
/* List the possible completions. See description of rl_complete (). */ int
rl_possible_completions (ignore, invoking_key) int ignore __attribute__((unused)), invoking_key __attribute__((unused));
{ return (rl_complete_internal ('?'));
}
int
rl_insert_completions (ignore, invoking_key) int ignore __attribute__((unused)), invoking_key __attribute__((unused));
{ return (rl_complete_internal ('*'));
}
/* Return the correct value to pass to rl_complete_internal performing thesametestsasrl_complete.Thisallowsconsecutivecallstoan application'scompletionfunctiontolistpossiblecompletionsandfor anapplication-specificcompletionfunctiontohonorthe
show-all-if-ambiguous readline variable. */ int
rl_completion_mode (cfunc)
rl_command_func_t *cfunc;
{ if (rl_last_func == cfunc && !completion_changed_buffer) return'?'; elseif (_rl_complete_show_all) return'!'; elseif (_rl_complete_show_unmodified) return'@'; else return TAB;
}
/* Set default values for readline word completion. These are the variables
that application completion functions can change or inspect. */ staticvoid
set_completion_defaults (what_to_do) int what_to_do;
{ /* Only the completion entry function can change these. */
rl_filename_completion_desired = 0;
rl_filename_quoting_desired = 1;
rl_completion_type = what_to_do;
rl_completion_suppress_append = rl_completion_suppress_quote = 0;
/* The completion entry function may optionally change this. */
rl_completion_mark_symlink_dirs = _rl_complete_mark_symlink_dirs;
}
/* The user must press "y" or "n". Non-zero return means "y" pressed. */ staticint
get_y_or_n (for_pager) int for_pager;
{ int c;
for (;;)
{
RL_SETSTATE(RL_STATE_MOREINPUT);
c = rl_read_key ();
RL_UNSETSTATE(RL_STATE_MOREINPUT);
if (c == 'y' || c == 'Y' || c == ' ') return (1); if (c == 'n' || c == 'N' || c == RUBOUT) return (0); if (c == ABORT_CHAR)
_rl_abort_internal (); if (for_pager && (c == NEWLINE || c == RETURN)) return (2); if (for_pager && (c == 'q' || c == 'Q')) return (0);
rl_ding ();
}
}
staticint
_rl_internal_pager (lines) int lines;
{ int i;
fprintf (rl_outstream, "--More--");
fflush (rl_outstream);
i = get_y_or_n (1);
_rl_erase_entire_line (); if (i == 0) return -1; elseif (i == 2) return (lines - 1); else return0;
}
staticint
path_isdir (filename) constchar *filename;
{ struct stat finfo;
#ifdefined (VISIBLE_STATS) /* Return the character which best describes FILENAME. `@'forsymboliclinks `/'fordirectories `*'forexecutables `='forsockets `|'forFIFOs `%'forcharacterspecialdevices
`#' for block special devices */ staticint
stat_char (filename) char *filename;
{ struct stat finfo; int character, r;
#ifdefined (HAVE_LSTAT) && defined (S_ISLNK)
r = lstat (filename, &finfo); #else
r = stat (filename, &finfo); #endif
if (r == -1) return (0);
character = 0; if (S_ISDIR (finfo.st_mode))
character = '/'; #ifdefined (S_ISCHR) elseif (S_ISCHR (finfo.st_mode))
character = '%'; #endif/* S_ISCHR */ #ifdefined (S_ISBLK) elseif (S_ISBLK (finfo.st_mode))
character = '#'; #endif/* S_ISBLK */ #ifdefined (S_ISLNK) elseif (S_ISLNK (finfo.st_mode))
character = '@'; #endif/* S_ISLNK */ #ifdefined (S_ISSOCK) elseif (S_ISSOCK (finfo.st_mode))
character = '='; #endif/* S_ISSOCK */ #ifdefined (S_ISFIFO) elseif (S_ISFIFO (finfo.st_mode))
character = '|'; #endif elseif (S_ISREG (finfo.st_mode))
{ if (access (filename, X_OK) == 0)
character = '*';
} return (character);
} #endif/* VISIBLE_STATS */
/* Return the portion of PATHNAME that should be output when listing possiblecompletions.Ifwearehackingfilenamecompletion,we areonlyinterestedinthebasename,theportionfollowingthe finalslash.Otherwise,wereturnwhatwewerepassed.Since printingemptystringsisnotveryinformative,ifwe'redoing filenamecompletion,andthebasenameistheemptystring,welook forthepreviousslashandreturntheportionfollowingthat.If
there's no previous slash, we just return what we were passed. */ staticchar *
printable_part (pathname) char *pathname;
{ char *temp, *x;
if (rl_filename_completion_desired == 0) /* don't need to do anything */ return (pathname);
if (temp == 0 || *temp == '\0') return (pathname); /* If the basename is NULL, we might have a pathname like '/usr/src/'. Lookforapreviousslashand,ifoneisfound,returntheportion followingthatslash.Ifthere'snopreviousslash,justreturnthe
pathname we were passed. */ elseif (temp[1] == '\0')
{ for (x = temp - 1; x > pathname; x--) if (*x == '/') break; return ((*x == '/') ? x + 1 : pathname);
} else return ++temp;
}
/* Compute width of STRING when displayed on screen by print_filename */ staticint
fnwidth (string) constchar *string;
{ int width, pos; #ifdefined (HANDLE_MULTIBYTE)
mbstate_t ps; int left, w;
size_t clen; wchar_t wc;
/* Output TO_PRINT to rl_outstream. If VISIBLE_STATS is defined and we areusingit,checkforandoutputasinglecharacterfor`special'
filenames. Return the number of characters we output. */
#ifdefined (VISIBLE_STATS) if (rl_filename_completion_desired && (rl_visible_stats || _rl_complete_mark_directories)) #else if (rl_filename_completion_desired && _rl_complete_mark_directories) #endif
{ /* If to_print != full_pathname, to_print is the basename of the pathpassed.Inthiscase,wetrytoexpandthedirectory
name before checking for the stat character. */ if (to_print != full_pathname)
{ /* Terminate the directory name. */
c = to_print[-1];
to_print[-1] = '\0';
/* If setting the last slash in full_pathname to a NUL results in full_pathnamebeingtheemptystring,wearetryingtocomplete filesintherootdirectory.Ifwepassanullstringtothe bashdirectorycompletionhook,forexample,itwillexpandit
to the current directory. We just want the `/'. */ if (full_pathname == 0 || *full_pathname == 0)
dn = "/"; elseif (full_pathname[0] != '/')
dn = full_pathname; elseif (full_pathname[1] == 0)
dn = "//"; /* restore trailing slash to `//' */ elseif (full_pathname[1] == '/' && full_pathname[2] == 0)
dn = "/"; /* don't turn /// into // */ else
dn = full_pathname;
s = tilde_expand (dn); if (rl_directory_completion_hook)
(*rl_directory_completion_hook) (&s);
r = (char *)xmalloc (strlen (s) + 2);
*r = *rl_completer_quote_characters;
strcpy (r + 1, s); if (qcp)
*qcp = *rl_completer_quote_characters; return r;
}
/* Find the bounds of the current word for completion purposes, and leave rl_pointsettotheendoftheword.Thisfunctionskipsquoted substrings(charactersbetweenmatchedpairsofcharactersin rl_completer_quote_characters).Firstwetrytofindanunclosed quotedsubstringonwhichtodomatching.Ifoneisnotfound,weuse thewordbreakcharacterstofindtheboundariesofthecurrentword. Wecallanapplication-specificfunctiontodecidewhetherornota particularwordbreakcharacterisquoted;ifthatfunctionreturnsa non-zeroresult,thecharacterdoesnotbreakaword.Thisfunction returnstheopeningquotecharacterifwefoundanunclosedquoted substring,'\0'otherwise.FP,ifnon-null,issettoavaluesaying which(shell-like)quotecharacterswefound(singlequote,double quote,orbackslash)anywhereinthestring.DP,ifnon-null,issetto
the value of the delimiter character that caused a word break. */
char
_rl_find_completion_word (fp, dp) int *fp, *dp;
{ int scan, end, found_quote, delimiter, pass_next, isbrk; char quote_char, *brkchars;
brkchars = 0; if (rl_completion_word_break_hook)
brkchars = (*rl_completion_word_break_hook) (); if (brkchars == 0)
brkchars = rl_completer_word_break_characters;
if (rl_completer_quote_characters)
{ /* We have a list of characters which can be used in pairs to quotesubstringsforthecompleter.Trytofindthestart
of an unclosed quoted substring. */ /* FOUND_QUOTE is set so we know what kind of quotes we found. */ for (scan = pass_next = 0; scan < end; scan = MB_NEXTCHAR (rl_line_buffer, scan, 1, MB_FIND_ANY))
{ if (pass_next)
{
pass_next = 0; continue;
}
/* Shell-like semantics for single quotes -- don't allow backslash toquoteanythinginsinglequotes,especiallynottheclosing quote.Ifyoudon'tlikethis,takeoutthecheckonthevalue
of quote_char. */ if (quote_char != '\'' && rl_line_buffer[scan] == '\\')
{
pass_next = 1;
found_quote |= RL_QF_BACKSLASH; continue;
}
if (quote_char != '\0')
{ /* Ignore everything until the matching close quote char. */ if (rl_line_buffer[scan] == quote_char)
{ /* Found matching close. Abandon this substring. */
quote_char = '\0';
rl_point = end;
}
} elseif (strchr (rl_completer_quote_characters, rl_line_buffer[scan]))
{ /* Found start of a quoted substring. */
quote_char = rl_line_buffer[scan];
rl_point = scan + 1; /* Shell-like quoting conventions. */ if (quote_char == '\'')
found_quote |= RL_QF_SINGLE_QUOTE; elseif (quote_char == '"')
found_quote |= RL_QF_DOUBLE_QUOTE; else
found_quote |= RL_QF_OTHER_QUOTE;
}
}
}
if (rl_point == end && quote_char == '\0')
{ /* We didn't find an unclosed quoted substring upon which to do completion,sousethewordbreakcharacterstofindthe
substring on which to complete. */ while ((rl_point = MB_PREVCHAR (rl_line_buffer, rl_point, MB_FIND_ANY)))
{
scan = rl_line_buffer[rl_point];
if (strchr (brkchars, scan) == 0) continue;
/* Call the application-specific function to tell us whether
this word break character is quoted and should be skipped. */ if (rl_char_is_quoted_p && found_quote &&
(*rl_char_is_quoted_p) (rl_line_buffer, rl_point)) continue;
/* Convoluted code, but it avoids an n^2 algorithm with calls
to char_is_quoted. */ break;
}
}
/* If we are at an unquoted word break, then advance past it. */
scan = rl_line_buffer[rl_point];
/* If there is an application-specific function to say whether or not acharacterisquotedandwefoundaquotecharacter,letthat functiondecidewhetherornotacharacterisawordbreak,even ifitisfoundinrl_completer_word_break_characters.Don'tbother
if we're at the end of the line, though. */ if (scan)
{ if (rl_char_is_quoted_p)
isbrk = (found_quote == 0 ||
(*rl_char_is_quoted_p) (rl_line_buffer, rl_point) == 0) &&
strchr (brkchars, scan) != 0; else
isbrk = strchr (brkchars, scan) != 0;
if (isbrk)
{ /* If the character that caused the word break was a quoting
character, then remember it as the delimiter. */ if (rl_basic_quote_characters &&
strchr (rl_basic_quote_characters, scan) &&
(end - rl_point) > 1)
delimiter = scan;
/* If the character isn't needed to determine something special
about what kind of completion to perform, then advance past it. */ if (rl_special_prefixes == 0 || strchr (rl_special_prefixes, scan) == 0)
rl_point++;
}
}
if (fp)
*fp = found_quote; if (dp)
*dp = delimiter;
/* If the user wants to TRY to complete, but then wants to give upandusethedefaultcompletionfunction,theysetthe
variable rl_attempted_completion_function. */ if (rl_attempted_completion_function)
{
matches = (*rl_attempted_completion_function) (text, start, end);
/* Filter out duplicates in MATCHES. This frees up the strings in
MATCHES. */ staticchar **
remove_duplicate_matches (matches) char **matches;
{ char *lowest_common; int i, j, newlen; char dead_slot; char **temp_array;
/* Sort the items. */ for (i = 0; matches[i]; i++)
;
/* Sort the array without matches[0], since we need it to
stay in place no matter what. */ if (i)
qsort (matches+1, i-1, sizeof (char *), (QSFUNC *)_rl_qsort_string_compare);
/* Remember the lowest common denominator for it may be unique. */
lowest_common = savestring (matches[0]);
for (i = newlen = 0; matches[i + 1]; i++)
{ if (strcmp (matches[i], matches[i + 1]) == 0)
{
free (matches[i]);
matches[i] = (char *)&dead_slot;
} else
newlen++;
}
/* We have marked all the dead slots with (char *)&dead_slot.
Copy all the non-dead entries into a new array. */
temp_array = (char **)xmalloc ((3 + newlen) * sizeof (char *)); for (i = j = 1; matches[i]; i++)
{ if (matches[i] != (char *)&dead_slot)
temp_array[j++] = matches[i];
}
temp_array[j] = (char *)NULL;
if (matches[0] != (char *)&dead_slot)
free (matches[0]);
/* Place the lowest common denominator back in [0]. */
temp_array[0] = lowest_common;
/* If there is one string left, and it is identical to the lowestcommondenominator,thentheLCDisthestringto
insert. */ if (j == 2 && strcmp (temp_array[0], temp_array[1]) == 0)
{
free (temp_array[1]);
temp_array[1] = (char *)NULL;
} return (temp_array);
}
/* Find the common prefix of the list of matches, and put it into
matches[0]. */ staticint
compute_lcd_of_matches (match_list, matches, text) char **match_list; int matches; constchar *text;
{ registerint i, c1, c2, si; int low; /* Count of max-matched characters. */ char *dtext; /* dequoted TEXT, if needed */ #ifdefined (HANDLE_MULTIBYTE) int v;
mbstate_t ps1, ps2; wchar_t wc1, wc2; #endif
/* If only one match, just use that. Otherwise, compare each memberofthelistwiththenext,findingoutwherethey
stop matching. */ if (matches == 1)
{
match_list[0] = match_list[1];
match_list[1] = (char *)NULL; return1;
}
for (i = 1, low = 100000; i < matches; i++)
{ #ifdefined (HANDLE_MULTIBYTE) if (MB_CUR_MAX > 1 && rl_byte_oriented == 0)
{
memset (&ps1, 0, sizeof (mbstate_t));
memset (&ps2, 0, sizeof (mbstate_t));
} #endif if (_rl_completion_case_fold)
{ for (si = 0;
(c1 = _rl_to_lower(match_list[i][si])) &&
(c2 = _rl_to_lower(match_list[i + 1][si]));
si++) #ifdefined (HANDLE_MULTIBYTE) if (MB_CUR_MAX > 1 && rl_byte_oriented == 0)
{
v = mbrtowc (&wc1, match_list[i]+si, strlen (match_list[i]+si), &ps1);
mbrtowc (&wc2, match_list[i+1]+si, strlen (match_list[i+1]+si), &ps2);
wc1 = towlower (wc1);
wc2 = towlower (wc2); if (wc1 != wc2) break; elseif (v > 1)
si += v - 1;
} else #endif if (c1 != c2) break;
} else
{ for (si = 0;
(c1 = match_list[i][si]) &&
(c2 = match_list[i + 1][si]);
si++) #ifdefined (HANDLE_MULTIBYTE) if (MB_CUR_MAX > 1 && rl_byte_oriented == 0)
{
mbstate_t ps_back;
ps_back = ps1; if (!_rl_compare_chars (match_list[i], si, &ps1, match_list[i+1], si, &ps2)) break; elseif ((v = _rl_get_char_len (&match_list[i][si], &ps_back)) > 1)
si += v - 1;
} else #endif if (c1 != c2) break;
}
if (low > si)
low = si;
}
/* If there were multiple matches, but none matched up to even the firstcharacter,andtheusertypedsomething,usethatasthe
value of matches[0]. */ if (low == 0 && text && *text)
{
match_list[0] = (char *)xmalloc (strlen (text) + 1);
strcpy (match_list[0], text);
} else
{
match_list[0] = (char *)xmalloc (low + 1);
/* XXX - this might need changes in the presence of multibyte chars */
/* If we are ignoring case, try to preserve the case of the string
the user typed in the face of multiple matches differing in case. */ if (_rl_completion_case_fold)
{ /* We're making an assumption here: IFwe'recompletingfilenamesAND theapplicationhasdefinedafilenamedequotingfunctionAND wefoundaquotecharacterAND theapplicationhasrequestedfilenamequoting THEN weassumethatTEXTwasdequotedbeforecheckingagainst thefilesystemandneedstobedequotedherebeforewe checkagainstthelistofmatches
FI */
dtext = (char *)NULL; if (rl_filename_completion_desired &&
rl_filename_dequoting_function &&
rl_completion_found_quote &&
rl_filename_quoting_desired)
{
dtext = (*rl_filename_dequoting_function) ((char *)text, rl_completion_quote_character);
text = dtext;
}
/* sort the list to get consistent answers. */
qsort (match_list+1, matches, sizeof(char *), (QSFUNC *)_rl_qsort_string_compare);
si = strlen (text); if (si <= low)
{ for (i = 1; i <= matches; i++) if (strncmp (match_list[i], text, si) == 0)
{
strncpy (match_list[0], match_list[i], low); break;
} /* no casematch, use first entry */ if (i > matches)
strncpy (match_list[0], match_list[1], low);
} else /* otherwise, just use the text the user typed. */
strncpy (match_list[0], text, low);
staticint
postprocess_matches (matchesp, matching_filenames) char ***matchesp; int matching_filenames;
{ char *t, **matches, **temp_matches; int nmatch, i;
matches = *matchesp;
if (matches == 0) return0;
/* It seems to me that in all the cases we handle we would like toignoreduplicatepossiblilities.Scanforthetextto
insert being identical to the other completions. */ if (rl_ignore_completion_duplicates)
{
temp_matches = remove_duplicate_matches (matches);
free (matches);
matches = temp_matches;
}
/* If we are matching filenames, then here is our chance to docleverprocessingbyre-examiningthelist.Callthe ignorefunctionwiththearrayasaparameter.Itcan
munge the array, deleting matches as it desires. */ if (rl_ignore_some_completions_function && matching_filenames)
{ for (nmatch = 1; matches[nmatch]; nmatch++)
;
(void)(*rl_ignore_some_completions_function) (matches); if (matches == 0 || matches[0] == 0)
{
FREE (matches);
*matchesp = (char **)0; return0;
} else
{ /* If we removed some matches, recompute the common prefix. */ for (i = 1; matches[i]; i++)
; if (i > 1 && i < nmatch)
{
t = matches[0];
compute_lcd_of_matches (matches, i - 1, t);
FREE (t);
}
}
}
*matchesp = matches; return (1);
}
/* A convenience function for displaying a list of strings in columnarformatonreadline'soutputstream.MATCHESisthelist ofstrings,inargvformat,LENisthenumberofstringsinMATCHES,
and MAX is the length of the longest string in MATCHES. */ void
rl_display_match_list (matches, len, max) char **matches; int len, max;
{ int count, limit, printed_len, lines; int i, j, k, l; char *temp;
/* How many items of MAX length can we fit in the screen window? */
max += 2;
limit = _rl_screenwidth / max; if (limit != 1 && (limit * max == _rl_screenwidth))
limit--;
/* Avoid a possible floating exception. If max > _rl_screenwidth,
limit will be 0 and a divide-by-zero fault will result. */ if (limit == 0)
limit = 1;
/* How many iterations of the printing loop? */
count = (len + (limit - 1)) / limit;
/* Watch out for special case. If LEN is less than LIMIT, then justdotheinnerprintingloop.
0 < len <= limit implies count = 1. */
/* Sort the items if they are not already sorted. */ if (rl_ignore_completion_duplicates == 0)
qsort (matches + 1, len, sizeof (char *), (QSFUNC *)_rl_qsort_string_compare);
rl_crlf ();
lines = 0; if (_rl_print_completions_horizontally == 0)
{ /* Print the sorted items, up-and-down alphabetically, like ls. */ for (i = 1; i <= count; i++)
{ for (j = 0, l = i; j < limit; j++)
{ if (l > len || matches[l] == 0) break; else
{
temp = printable_part (matches[l]);
printed_len = print_filename (temp, matches[l]);
if (j + 1 < limit) for (k = 0; k < max - printed_len; k++)
putc (' ', rl_outstream);
}
l += count;
}
rl_crlf ();
lines++; if (_rl_page_completions && lines >= (_rl_screenheight - 1) && i < count)
{
lines = _rl_internal_pager (lines); if (lines < 0) return;
}
}
} else
{ /* Print the sorted items, across alphabetically, like ls -x. */ for (i = 1; matches[i]; i++)
{
temp = printable_part (matches[i]);
printed_len = print_filename (temp, matches[i]); /* Have we reached the end of this line? */ if (matches[i+1])
{ if (i && (limit > 1) && (i % limit) == 0)
{
rl_crlf ();
lines++; if (_rl_page_completions && lines >= _rl_screenheight - 1)
{
lines = _rl_internal_pager (lines); if (lines < 0) return;
}
} else for (k = 0; k < max - printed_len; k++)
putc (' ', rl_outstream);
}
}
rl_crlf ();
}
}
/* Display MATCHES, a list of matching filenames in argv format. This handlesthesimplecase--asinglematch--first.Ifthereismore thanonematch,wecomputethenumberofstringsinthelistandthe lengthofthelongeststring,whichwillbeneededbythedisplay function.Iftheapplicationwantstohandledisplayingthelistof matchesitself,itsetsRL_COMPLETION_DISPLAY_MATCHES_HOOKtothe addressofafunction,andwejustcallit.Ifwe'rehandlingthe displayourselves,wejustcallrl_display_match_list.Wealsocheck thatthelistofmatchesdoesn'texceedtheuser-settablethreshold, andasktheuserifhewantstoseethelistiftherearemorematches
than RL_COMPLETION_QUERY_ITEMS. */ staticvoid
display_matches (matches) char **matches;
{ int len, max, i; char *temp;
/* Move to the last visible line of a possibly-multiple-line command. */
_rl_move_vert (_rl_vis_botlin);
/* Handle simple case first. What if there is only one answer? */ if (matches[1] == 0)
{
temp = printable_part (matches[0]);
rl_crlf ();
print_filename (temp, matches[0]);
rl_crlf ();
/* There is more than one answer. Find out how many there are,
and find the maximum printed length of a single entry. */ for (max = 0, i = 1; matches[i]; i++)
{
temp = printable_part (matches[i]);
len = fnwidth (temp);
if (len > max)
max = len;
}
len = i - 1;
/* If the caller has defined a display hook, then call that now. */ if (rl_completion_display_matches_hook)
{
(*rl_completion_display_matches_hook) (matches, len, max); return;
}
/* If there are many items, then ask the user if she really wants to
see them all. */ if (rl_completion_query_items > 0 && len >= rl_completion_query_items)
{
rl_crlf ();
fprintf (rl_outstream, "Display all %d possibilities? (y or n)", len);
fflush (rl_outstream); if (get_y_or_n (0) == 0)
{
rl_crlf ();
staticchar *
make_quoted_replacement (match, mtype, qc) char *match; int mtype; char *qc; /* Pointer to quoting character, if any */
{ int should_quote, do_replace; char *replacement;
/* If we are doing completion on quoted substrings, and any matches containanyofthecompleter_word_break_characters,thenauto- maticallyprependthesubstringwithaquotecharacter(justpick thefirstonefromthelistofsuch)ifitdoesnotalreadybegin withaquotestring.FIXME:Needtoremoveanysuchautomatically insertedquotecharacterwhenitnolongerisnecessary,suchas ifwechangethestringwearecompletingonandthenewsetof
matches don't require a quoted substring. */
replacement = match;
should_quote = match && rl_completer_quote_characters &&
rl_filename_completion_desired &&
rl_filename_quoting_desired;
if (should_quote)
{ /* If there is a single match, see if we need to quote it. Thisalsocheckswhetherthecommonprefixofseveral
matches needs to be quoted. */
should_quote = rl_filename_quote_characters
? (_rl_strpbrk (match, rl_filename_quote_characters) != 0)
: 0;
do_replace = should_quote ? mtype : NO_MATCH; /* Quote the replacement, since we found an embedded
word break character in a potential match. */ if (do_replace != NO_MATCH && rl_filename_quoting_function)
replacement = (*rl_filename_quoting_function) (match, do_replace, qc);
} return (replacement);
}
for (i = 0; matches[i]; i++)
free (matches[i]);
free (matches);
}
/* Complete the word at or before point. WHAT_TO_DOsayswhattodowiththecompletion. `?'meanslistthepossiblecompletions. TABmeansdostandardcompletion. `*'meansinsertallofthepossiblecompletions. `!'meanstodostandardcompletion,andlistallpossiblecompletionsif thereismorethanone. `@'meanstodostandardcompletion,andlistallpossiblecompletionsif
there is more than one and partial completion is not possible. */ int
rl_complete_internal (what_to_do) int what_to_do;
{ char **matches;
rl_compentry_func_t *our_func; int start, end, delimiter, found_quote, i, nontrivial_lcd; char *text, *saved_line_buffer; char quote_char;
RL_SETSTATE(RL_STATE_COMPLETING);
set_completion_defaults (what_to_do);
saved_line_buffer = rl_line_buffer ? savestring (rl_line_buffer) : (char *)NULL;
our_func = rl_completion_entry_function
? rl_completion_entry_function
: rl_filename_completion_function; /* We now look backwards for the start of a filename/variable word. */
end = rl_point;
found_quote = delimiter = 0;
quote_char = '\0';
if (rl_point) /* This (possibly) changes rl_point. If it returns a non-zero char,
we know we have an open quote. */
quote_char = _rl_find_completion_word (&found_quote, &delimiter);
start = rl_point;
rl_point = end;
text = rl_copy_text (start, end);
matches = gen_completion_matches (text, start, end, our_func, found_quote, quote_char); /* nontrivial_lcd is set if the common prefix adds something to the word
being completed. */
nontrivial_lcd = matches && strcmp (text, matches[0]) != 0;
free (text);
/* If we are matching filenames, the attempted completion function will havesetrl_filename_completion_desiredtoanon-zerovalue.Thebasic
rl_filename_completion_function does this. */
i = rl_filename_completion_desired;
switch (what_to_do)
{ case TAB: case'!': case'@': /* Insert the first match with proper quoting. */ if (*matches[0])
insert_match (matches[0], start, matches[1] ? MULT_MATCH : SINGLE_MATCH, "e_char);
/* If there are more matches, ring the bell to indicate. Ifweareinvimode,Posix.2saystonotringthebell. Ifthe`show-all-if-ambiguous'variableisset,display allthematchesimmediately.Otherwise,ifthiswasthe onlymatch,andwearehackingfiles,checkthefileto seeifitwasadirectory.Ifso,andthe`mark-directories' variableisset,adda'/'tothename.Ifnot,andwe
are at the end of the line, then add a space. */ if (matches[1])
{ if (what_to_do == '!')
{
display_matches (matches); break;
} elseif (what_to_do == '@')
{ if (nontrivial_lcd == 0)
display_matches (matches); break;
} elseif (rl_editing_mode != vi_mode)
rl_ding (); /* There are other matches remaining. */
} else
append_to_match (matches[0], delimiter, quote_char, nontrivial_lcd);
default:
fprintf (stderr, "\r\nreadline: bad value %d for what_to_do in rl_complete\n", what_to_do);
rl_ding ();
FREE (saved_line_buffer);
RL_UNSETSTATE(RL_STATE_COMPLETING); return1;
}
_rl_free_match_list (matches);
/* Check to see if the line has changed through all of this manipulation. */ if (saved_line_buffer)
{
completion_changed_buffer = strcmp (rl_line_buffer, saved_line_buffer) != 0;
free (saved_line_buffer);
}
/* Return an array of (char *) which is a list of completions for TEXT. Iftherearenocompletions,returnaNULLpointer. ThefirstentryinthereturnedarrayisthesubstitutionforTEXT. Theremainingentriesarethepossiblecompletions. ThearrayisterminatedwithaNULLpointer.
ENTRY_FUNCTIONisafunctionoftwoargs,andreturnsa(char*). ThefirstargumentisTEXT. Thesecondisastateargument;itshouldbezeroonthefirstcall,and non-zeroonsubsequentcalls.ItreturnsaNULLpointertothecaller whentherearenomorematches.
*/ char **
rl_completion_matches (text, entry_function) constchar *text;
rl_compentry_func_t *entry_function;
{ /* Number of slots in match_list. */ int match_list_size;
/* The list of matches. */ char **match_list;
/* Number of matches actually found. */ int matches;
/* If there were any matches, then look through them finding out the
lowest common denominator. That then becomes match_list[0]. */ if (matches)
compute_lcd_of_matches (match_list, matches, text); else/* There were no matches. */
{
free (match_list);
match_list = (char **)NULL;
} return (match_list);
}
/* A completion function for usernames. TEXTcontainsapartialusernameprecededbyarandom
character (usually `~'). */ char *
rl_username_completion_function (text, state) constchar *text; int state;
{ #ifdefined (__WIN32__) || defined (__OPENNT) return (char *)NULL; #else/* !__WIN32__ && !__OPENNT) */ staticchar *username = (char *)NULL; staticstruct passwd *entry; staticint first_char, first_char_loc; char *value; #ifdefined (HAVE_GETPWENT) staticint namelen; #endif
#ifdefined (HAVE_GETPWENT) while (entry = getpwent ())
{ /* Null usernames should result in all users as possible completions. */ if (namelen == 0 || (STREQN (username, entry->pw_name, namelen))) break;
} #endif
/* Okay, now we write the entry_function for filename completion. In the generalcase.Notethatcompletionintheshellisalittledifferent becauseofallthepathnamesthatmustbefollowedwhenlookingupthe
completion for a command. */ char *
rl_filename_completion_function (text, state) constchar *text; int state;
{ static DIR *directory = (DIR *)NULL; staticchar *filename = (char *)NULL; staticchar *dirname = (char *)NULL; staticchar *users_dirname = (char *)NULL; staticint filename_len; char *temp; int dirlen; struct dirent *entry;
/* If we don't have any state, then do some initialization. */ if (state == 0)
{ /* If we were interrupted before closing the directory or reading
all of its contents, close it. */ if (directory)
{
closedir (directory);
directory = (DIR *)NULL;
}
FREE (dirname);
FREE (filename);
FREE (users_dirname);
filename = savestring (text); if (*text == 0)
text = ".";
dirname = savestring (text);
if (rl_directory_rewrite_hook)
(*rl_directory_rewrite_hook) (&dirname);
/* The directory completion hook should perform any necessary
dequoting. */ if (rl_directory_completion_hook && (*rl_directory_completion_hook) (&dirname))
{
free (users_dirname);
users_dirname = savestring (dirname);
} elseif (rl_completion_found_quote && rl_filename_dequoting_function)
{ /* delete single and double quotes */
temp = (*rl_filename_dequoting_function) (users_dirname, rl_completion_quote_character);
free (users_dirname);
users_dirname = temp;
}
directory = opendir (dirname);
/* Now dequote a non-null filename. */ if (filename && *filename && rl_completion_found_quote && rl_filename_dequoting_function)
{ /* delete single and double quotes */
temp = (*rl_filename_dequoting_function) (filename, rl_completion_quote_character);
free (filename);
filename = temp;
}
filename_len = strlen (filename);
rl_filename_completion_desired = 1;
}
/* At this point we should entertain the possibility of hacking wildcarded filenames,like/usr/man/man<WILD>/te<TAB>.Ifthedirectoryname containsglobbingcharacters,thenbuildanarrayofdirectories,and
then map over that list while completing. */ /* *** UNIMPLEMENTED *** */
/* Now that we have some state, we can read the directory. */
entry = (struct dirent *)NULL; while (directory && (entry = readdir (directory)))
{ /* Special case for no filename. If the user has disabled the `match-hidden-files'variable,skipfilenamesbeginningwith`.'.
All other entries except "." and ".." match. */ if (filename_len == 0)
{ if (_rl_match_hidden_files == 0 && HIDDEN_FILE (entry->d_name)) continue;
if (entry->d_name[0] != '.' ||
(entry->d_name[1] &&
(entry->d_name[1] != '.' || entry->d_name[2]))) break;
} else
{ /* Otherwise, if these match up to the length of filename, then
it is a match. */ if (_rl_completion_case_fold)
{ if ((_rl_to_lower (entry->d_name[0]) == _rl_to_lower (filename[0])) &&
(((int)D_NAMLEN (entry)) >= filename_len) &&
(_rl_strnicmp (filename, entry->d_name, filename_len) == 0)) break;
} else
{ if ((entry->d_name[0] == filename[0]) &&
(((int)D_NAMLEN (entry)) >= filename_len) &&
(strncmp (filename, entry->d_name, filename_len) == 0)) break;
}
}
}
if (entry == 0)
{ if (directory)
{
closedir (directory);
directory = (DIR *)NULL;
} if (dirname)
{
free (dirname);
dirname = (char *)NULL;
} if (filename)
{
free (filename);
filename = (char *)NULL;
} if (users_dirname)
{
free (users_dirname);
users_dirname = (char *)NULL;
}
return (char *)NULL;
} else
{ /* dirname && (strcmp (dirname, ".") != 0) */ if (dirname && (dirname[0] != '.' || dirname[1]))
{ if (rl_complete_with_tilde_expansion && *users_dirname == '~')
{
dirlen = strlen (dirname);
temp = (char *)xmalloc (2 + dirlen + D_NAMLEN (entry));
strcpy (temp, dirname); /* Canonicalization cuts off any final slash present. We
may need to add it back. */ if (dirname[dirlen - 1] != '/')
{
temp[dirlen++] = '/';
temp[dirlen] = '\0';
}
} else
{
dirlen = strlen (users_dirname);
temp = (char *)xmalloc (2 + dirlen + D_NAMLEN (entry));
strcpy (temp, users_dirname); /* Make sure that temp has a trailing slash here. */ if (users_dirname[dirlen - 1] != '/')
temp[dirlen++] = '/';
}
/* An initial implementation of a menu completion function a la tcsh. The firsttime(ifthelastreadlinecommandwasnotrl_menu_complete),we generatethelistofmatches.Thiscodeisverysimilartothecodein rl_complete_internal--thereshouldbeawaytocombinethetwo.Then, foreachiteminthelistofmatches,weinsertthematchinanundoable fashion,withtheappropriatecharacterappended(thishappensonthe secondandsubsequentconsecutivecallstorl_menu_complete).Whenwe hittheendofthematchlist,werestoretheoriginalunmatchedtext,
ring the bell, and reset the counter to zero. */ int
rl_menu_complete (count, ignore) int count, ignore __attribute__((unused));
{
rl_compentry_func_t *our_func; int matching_filenames, found_quote;
/* The first time through, we generate the list of matches and set things
up to insert them. */ if (rl_last_func != rl_menu_complete)
{ /* Clean up from previous call, if any. */
FREE (orig_text); if (matches)
_rl_free_match_list (matches);
/* We now look backwards for the start of a filename/variable word. */
orig_end = rl_point;
found_quote = delimiter = 0;
quote_char = '\0';
if (rl_point) /* This (possibly) changes rl_point. If it returns a non-zero char,
we know we have an open quote. */
quote_char = _rl_find_completion_word (&found_quote, &delimiter);
/* If we are matching filenames, the attempted completion function will havesetrl_filename_completion_desiredtoanon-zerovalue.Thebasic
rl_filename_completion_function does this. */
matching_filenames = rl_filename_completion_desired;
for (match_list_size = 0; matches[match_list_size]; match_list_size++)
; /* matches[0] is lcd if match_list_size > 1, but the circular buffer
code below should take care of it. */
}
/* Now we have the list of matches. Replace the text between rl_line_buffer[orig_start]andrl_line_buffer[rl_point]with
matches[match_list_index], and add any necessary closing char. */
¤ Die Informationen auf dieser Webseite wurden
nach bestem Wissen sorgfältig zusammengestellt. Es wird jedoch weder Vollständigkeit, noch Richtigkeit,
noch Qualität der bereit gestellten Informationen zugesichert.0.332Bemerkung:
(vorverarbeitet am 2026-10-08)
¤
Die Informationen auf dieser Webseite wurden
nach bestem Wissen sorgfältig zusammengestellt. Es wird jedoch weder Vollständigkeit, noch Richtigkeit,
noch Qualität der bereit gestellten Informationen zugesichert.
Bemerkung:
Die farbliche Syntaxdarstellung und die Messung sind noch experimentell.