tw.parse.c revision 69408
1/* $Header: /src/pub/tcsh/tw.parse.c,v 3.89 2000/11/11 23:03:40 christos Exp $ */
2/*
3 * tw.parse.c: Everyone has taken a shot in this futile effort to
4 *	       lexically analyze a csh line... Well we cannot good
5 *	       a job as good as sh.lex.c; but we try. Amazing that
6 *	       it works considering how many hands have touched this code
7 */
8/*-
9 * Copyright (c) 1980, 1991 The Regents of the University of California.
10 * All rights reserved.
11 *
12 * Redistribution and use in source and binary forms, with or without
13 * modification, are permitted provided that the following conditions
14 * are met:
15 * 1. Redistributions of source code must retain the above copyright
16 *    notice, this list of conditions and the following disclaimer.
17 * 2. Redistributions in binary form must reproduce the above copyright
18 *    notice, this list of conditions and the following disclaimer in the
19 *    documentation and/or other materials provided with the distribution.
20 * 3. All advertising materials mentioning features or use of this software
21 *    must display the following acknowledgement:
22 *	This product includes software developed by the University of
23 *	California, Berkeley and its contributors.
24 * 4. Neither the name of the University nor the names of its contributors
25 *    may be used to endorse or promote products derived from this software
26 *    without specific prior written permission.
27 *
28 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
29 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
30 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
31 * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
32 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
33 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
34 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
35 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
36 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
37 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
38 * SUCH DAMAGE.
39 */
40#include "sh.h"
41
42RCSID("$Id: tw.parse.c,v 3.89 2000/11/11 23:03:40 christos Exp $")
43
44#include "tw.h"
45#include "ed.h"
46#include "tc.h"
47
48#ifdef WINNT_NATIVE
49#include "nt.const.h"
50#endif /* WINNT_NATIVE */
51#define EVEN(x) (((x) & 1) != 1)
52
53#define DOT_NONE	0	/* Don't display dot files		*/
54#define DOT_NOT		1	/* Don't display dot or dot-dot		*/
55#define DOT_ALL		2	/* Display all dot files		*/
56
57/*  TW_NONE,	       TW_COMMAND,     TW_VARIABLE,    TW_LOGNAME,	*/
58/*  TW_FILE,	       TW_DIRECTORY,   TW_VARLIST,     TW_USER,		*/
59/*  TW_COMPLETION,     TW_ALIAS,       TW_SHELLVAR,    TW_ENVVAR,	*/
60/*  TW_BINDING,        TW_WORDLIST,    TW_LIMIT,       TW_SIGNAL	*/
61/*  TW_JOB,	       TW_EXPLAIN,     TW_TEXT,	       TW_GRPNAME	*/
62static void (*tw_start_entry[]) __P((DIR *, Char *)) = {
63    tw_file_start,     tw_cmd_start,   tw_var_start,   tw_logname_start,
64    tw_file_start,     tw_file_start,  tw_vl_start,    tw_logname_start,
65    tw_complete_start, tw_alias_start, tw_var_start,   tw_var_start,
66    tw_bind_start,     tw_wl_start,    tw_limit_start, tw_sig_start,
67    tw_job_start,      tw_file_start,  tw_file_start,  tw_grpname_start
68};
69
70static Char * (*tw_next_entry[]) __P((Char *, int *)) = {
71    tw_file_next,      tw_cmd_next,    tw_var_next,    tw_logname_next,
72    tw_file_next,      tw_file_next,   tw_var_next,    tw_logname_next,
73    tw_var_next,       tw_var_next,    tw_shvar_next,  tw_envvar_next,
74    tw_bind_next,      tw_wl_next,     tw_limit_next,  tw_sig_next,
75    tw_job_next,       tw_file_next,   tw_file_next,   tw_grpname_next
76};
77
78static void (*tw_end_entry[]) __P((void)) = {
79    tw_dir_end,        tw_dir_end,     tw_dir_end,    tw_logname_end,
80    tw_dir_end,        tw_dir_end,     tw_dir_end,    tw_logname_end,
81    tw_dir_end,        tw_dir_end,     tw_dir_end,    tw_dir_end,
82    tw_dir_end,        tw_dir_end,     tw_dir_end,    tw_dir_end,
83    tw_dir_end,	       tw_dir_end,     tw_dir_end,    tw_grpname_end
84};
85
86/* #define TDEBUG */
87
88/* Set to TRUE if recexact is set and an exact match is found
89 * along with other, longer, matches.
90 */
91
92int curchoice = -1;
93
94int match_unique_match = FALSE;
95int non_unique_match = FALSE;
96static bool SearchNoDirErr = 0;	/* t_search returns -2 if dir is unreadable */
97
98/* state so if a completion is interrupted, the input line doesn't get
99   nuked */
100int InsideCompletion = 0;
101
102/* do the expand or list on the command line -- SHOULD BE REPLACED */
103
104extern Char NeedsRedraw;	/* from ed.h */
105extern int Tty_raw_mode;
106extern int TermH;		/* from the editor routines */
107extern int lbuffed;		/* from sh.print.c */
108
109static	void	 extract_dir_and_name	__P((Char *, Char *, Char *));
110static	int	 insert_meta		__P((Char *, Char *, Char *, bool));
111static	Char	*tilde			__P((Char *, Char *));
112#ifndef __MVS__
113static  int      expand_dir		__P((Char *, Char *, DIR  **, COMMAND));
114#endif
115static	bool	 nostat			__P((Char *));
116static	Char	 filetype		__P((Char *, Char *));
117static	int	 t_glob			__P((Char ***, int));
118static	int	 c_glob			__P((Char ***));
119static	int	 is_prefix		__P((Char *, Char *));
120static	int	 is_prefixmatch		__P((Char *, Char *, int));
121static	int	 is_suffix		__P((Char *, Char *));
122static	int	 recognize		__P((Char *, Char *, int, int, int));
123static	int	 ignored		__P((Char *));
124static	int	 isadirectory		__P((Char *, Char *));
125#ifndef __MVS__
126static  int      tw_collect_items	__P((COMMAND, int, Char *, Char *,
127					     Char *, Char *, int));
128static  int      tw_collect		__P((COMMAND, int, Char *, Char *,
129					     Char **, Char *, int, DIR *));
130#endif
131static	Char 	 tw_suffix		__P((int, Char *, Char *, Char *,
132					     Char *));
133static	void 	 tw_fixword		__P((int, Char *, Char *, Char *, int));
134static	void	 tw_list_items		__P((int, int, int));
135static 	void	 add_scroll_tab		__P((Char *));
136static 	void 	 choose_scroll_tab	__P((Char **, int));
137static	void	 free_scroll_tab	__P((void));
138static	int	 find_rows		__P((Char *[], int, int));
139
140#ifdef notdef
141/*
142 * If we find a set command, then we break a=b to a= and word becomes
143 * b else, we don't break a=b. [don't use that; splits words badly and
144 * messes up tw_complete()]
145 */
146#define isaset(c, w) ((w)[-1] == '=' && \
147		      ((c)[0] == 's' && (c)[1] == 'e' && (c)[2] == 't' && \
148		       ((c[3] == ' ' || (c)[3] == '\t'))))
149#endif
150
151#define QLINESIZE (INBUFSIZE + 1)
152
153/* TRUE if character must be quoted */
154#define tricky(w) (cmap(w, _META | _DOL | _QF | _QB | _ESC | _GLOB) && w != '#')
155/* TRUE if double quotes don't protect character */
156#define tricky_dq(w) (cmap(w, _DOL | _QB))
157
158/* tenematch():
159 *	Return:
160 *		> 1:    No. of items found
161 *		= 1:    Exactly one match / spelling corrected
162 *		= 0:    No match / spelling was correct
163 *		< 0:    Error (incl spelling correction impossible)
164 */
165int
166tenematch(inputline, num_read, command)
167    Char   *inputline;		/* match string prefix */
168    int     num_read;		/* # actually in inputline */
169    COMMAND command;		/* LIST or RECOGNIZE or PRINT_HELP */
170
171{
172    Char    qline[QLINESIZE];
173    Char    qu = 0, *pat = STRNULL;
174    Char   *str_end, *cp, *wp, *wordp;
175    Char   *cmd_start, *word_start, *word;
176    Char   *ocmd_start = NULL, *oword_start = NULL, *oword = NULL;
177    int	    suf = 0;
178    int     space_left;
179    int     looking;		/* what we are looking for		*/
180    int     search_ret;		/* what search returned for debugging 	*/
181    int     backq = 0;
182
183    if (num_read > QLINESIZE - 1)
184	return -1;
185    str_end = &inputline[num_read];
186
187    word_start = inputline;
188    word = cmd_start = wp = qline;
189    for (cp = inputline; cp < str_end; cp++) {
190        if (!cmap(qu, _ESC)) {
191	    if (cmap(*cp, _QF|_ESC)) {
192		if (qu == 0 || qu == *cp) {
193		    qu ^= *cp;
194		    continue;
195		}
196	    }
197	    if (qu != '\'' && cmap(*cp, _QB)) {
198		if ((backq ^= 1) != 0) {
199		    ocmd_start = cmd_start;
200		    oword_start = word_start;
201		    oword = word;
202		    word_start = cp + 1;
203		    word = cmd_start = wp + 1;
204		}
205		else {
206		    cmd_start = ocmd_start;
207		    word_start = oword_start;
208		    word = oword;
209		}
210		*wp++ = *cp;
211		continue;
212	    }
213	}
214	if (iscmdmeta(*cp))
215	    cmd_start = wp + 1;
216
217	/* Don't quote '/' to make the recognize stuff work easily */
218	/* Don't quote '$' in double quotes */
219
220	if (cmap(*cp, _ESC) && cp < str_end - 1 && cp[1] == HIST)
221	  *wp = *++cp | QUOTE;
222	else if (qu && (tricky(*cp) || *cp == '~') && !(qu == '\"' && tricky_dq(*cp)))
223	  *wp = *cp | QUOTE;
224	else
225	  *wp = *cp;
226	if (ismetahash(*wp) /* || isaset(cmd_start, wp + 1) */)
227	    word = wp + 1, word_start = cp + 1;
228	wp++;
229	if (cmap(qu, _ESC))
230	    qu = 0;
231      }
232    *wp = 0;
233
234#ifdef masscomp
235    /*
236     * Avoid a nasty message from the RTU 4.1A & RTU 5.0 compiler concerning
237     * the "overuse of registers". According to the compiler release notes,
238     * incorrect code may be produced unless the offending expression is
239     * rewritten. Therefore, we can't just ignore it, DAS DEC-90.
240     */
241    space_left = QLINESIZE - 1;
242    space_left -= word - qline;
243#else
244    space_left = QLINESIZE - 1 - (int) (word - qline);
245#endif
246
247    /*
248     *  SPECIAL HARDCODED COMPLETIONS:
249     *    first word of command       -> TW_COMMAND
250     *    everything else             -> TW_ZERO
251     *
252     */
253    looking = starting_a_command(word - 1, qline) ?
254	TW_COMMAND : TW_ZERO;
255
256    wordp = word;
257
258#ifdef TDEBUG
259    xprintf(CGETS(30, 1, "starting_a_command %d\n"), looking);
260    xprintf("\ncmd_start:%S:\n", cmd_start);
261    xprintf("qline:%S:\n", qline);
262    xprintf("qline:");
263    for (wp = qline; *wp; wp++)
264	xprintf("%c", *wp & QUOTE ? '-' : ' ');
265    xprintf(":\n");
266    xprintf("word:%S:\n", word);
267    xprintf("word:");
268    /* Must be last, so wp is still pointing to the end of word */
269    for (wp = word; *wp; wp++)
270	xprintf("%c", *wp & QUOTE ? '-' : ' ');
271    xprintf(":\n");
272#endif
273
274    if ((looking == TW_COMMAND || looking == TW_ZERO) &&
275        (command == RECOGNIZE || command == LIST || command == SPELL ||
276	 command == RECOGNIZE_SCROLL)) {
277#ifdef TDEBUG
278	xprintf(CGETS(30, 2, "complete %d "), looking);
279#endif
280	looking = tw_complete(cmd_start, &wordp, &pat, looking, &suf);
281#ifdef TDEBUG
282	xprintf(CGETS(30, 3, "complete %d %S\n"), looking, pat);
283#endif
284    }
285
286    switch (command) {
287	Char    buffer[FILSIZ + 1], *bptr;
288	Char   *slshp;
289	Char   *items[2], **ptr;
290	int     i, count;
291
292    case RECOGNIZE:
293    case RECOGNIZE_SCROLL:
294    case RECOGNIZE_ALL:
295	if (adrof(STRautocorrect)) {
296	    if ((slshp = Strrchr(wordp, '/')) != NULL && slshp[1] != '\0') {
297		SearchNoDirErr = 1;
298		for (bptr = wordp; bptr < slshp; bptr++) {
299		    /*
300		     * do not try to correct spelling of words containing
301		     * globbing characters
302		     */
303		    if (isglob(*bptr)) {
304			SearchNoDirErr = 0;
305			break;
306		    }
307		}
308	    }
309	}
310	else
311	    slshp = STRNULL;
312	search_ret = t_search(wordp, wp, command, space_left, looking, 1,
313			      pat, suf);
314	SearchNoDirErr = 0;
315
316	if (search_ret == -2) {
317	    Char    rword[FILSIZ + 1];
318
319	    (void) Strcpy(rword, slshp);
320	    if (slshp != STRNULL)
321		*slshp = '\0';
322	    search_ret = spell_me(wordp, QLINESIZE - (wordp - qline), looking,
323				  pat, suf);
324	    if (search_ret == 1) {
325		(void) Strcat(wordp, rword);
326		wp = wordp + (int) Strlen(wordp);
327		search_ret = t_search(wordp, wp, command, space_left,
328				      looking, 1, pat, suf);
329	    }
330	}
331	if (*wp && insert_meta(word_start, str_end, word, !qu) < 0)
332	    return -1;		/* error inserting */
333	return search_ret;
334
335    case SPELL:
336	for (bptr = word_start; bptr < str_end; bptr++) {
337	    /*
338	     * do not try to correct spelling of words containing globbing
339	     * characters
340	     */
341	    if (isglob(*bptr))
342		return 0;
343	}
344	search_ret = spell_me(wordp, QLINESIZE - (wordp - qline), looking,
345			      pat, suf);
346	if (search_ret == 1) {
347	    if (insert_meta(word_start, str_end, word, !qu) < 0)
348		return -1;		/* error inserting */
349	}
350	return search_ret;
351
352    case PRINT_HELP:
353	do_help(cmd_start);
354	return 1;
355
356    case GLOB:
357    case GLOB_EXPAND:
358	(void) Strncpy(buffer, wordp, FILSIZ + 1);
359	items[0] = buffer;
360	items[1] = NULL;
361	ptr = items;
362	count = (looking == TW_COMMAND && Strchr(wordp, '/') == 0) ?
363		c_glob(&ptr) :
364		t_glob(&ptr, looking == TW_COMMAND);
365	if (count > 0) {
366	    if (command == GLOB)
367		print_by_column(STRNULL, ptr, count, 0);
368	    else {
369		DeleteBack(str_end - word_start);/* get rid of old word */
370		for (i = 0; i < count; i++)
371		    if (ptr[i] && *ptr[i]) {
372			(void) quote(ptr[i]);
373			if (insert_meta(0, 0, ptr[i], 0) < 0 ||
374			    InsertStr(STRspace) < 0) {
375			    blkfree(ptr);
376			    return -1;		/* error inserting */
377			}
378		    }
379	    }
380	    blkfree(ptr);
381	}
382	return count;
383
384    case VARS_EXPAND:
385	if (dollar(buffer, word)) {
386	    if (insert_meta(word_start, str_end, buffer, !qu) < 0)
387		return -1;		/* error inserting */
388	    return 1;
389	}
390	return 0;
391
392    case PATH_NORMALIZE:
393	if ((bptr = dnormalize(wordp, symlinks == SYM_IGNORE ||
394				      symlinks == SYM_EXPAND)) != NULL) {
395	    (void) Strcpy(buffer, bptr);
396	    xfree((ptr_t) bptr);
397	    if (insert_meta(word_start, str_end, buffer, !qu) < 0)
398		return -1;		/* error inserting */
399	    return 1;
400	}
401	return 0;
402
403    case COMMAND_NORMALIZE:
404	if (!cmd_expand(wordp, buffer))
405	    return 0;
406	if (insert_meta(word_start, str_end, buffer, !qu) < 0)
407	    return -1;		/* error inserting */
408	return 1;
409
410    case LIST:
411    case LIST_ALL:
412	search_ret = t_search(wordp, wp, LIST, space_left, looking, 1,
413			      pat, suf);
414	return search_ret;
415
416    default:
417	xprintf(CGETS(30, 4, "%s: Internal match error.\n"), progname);
418	return 1;
419
420    }
421} /* end tenematch */
422
423
424/* t_glob():
425 * 	Return a list of files that match the pattern
426 */
427static int
428t_glob(v, cmd)
429    register Char ***v;
430    int cmd;
431{
432    jmp_buf_t osetexit;
433
434    if (**v == 0)
435	return (0);
436    gflag = 0, tglob(*v);
437    if (gflag) {
438	getexit(osetexit);	/* make sure to come back here */
439	if (setexit() == 0)
440	    *v = globall(*v);
441	resexit(osetexit);
442	gargv = 0;
443	if (haderr) {
444	    haderr = 0;
445	    NeedsRedraw = 1;
446	    return (-1);
447	}
448	if (*v == 0)
449	    return (0);
450    }
451    else
452	return (0);
453
454    if (cmd) {
455	Char **av = *v, *p;
456	int fwd, i, ac = gargc;
457
458	for (i = 0, fwd = 0; i < ac; i++)
459	    if (!executable(NULL, av[i], 0)) {
460		fwd++;
461		p = av[i];
462		av[i] = NULL;
463		xfree((ptr_t) p);
464	    }
465	    else if (fwd)
466		av[i - fwd] = av[i];
467
468	if (fwd)
469	    av[i - fwd] = av[i];
470	gargc -= fwd;
471	av[gargc] = NULL;
472    }
473
474    return (gargc);
475} /* end t_glob */
476
477
478/* c_glob():
479 * 	Return a list of commands that match the pattern
480 */
481static int
482c_glob(v)
483    register Char ***v;
484{
485    Char *pat = **v, *cmd, **av;
486    Char dir[MAXPATHLEN+1];
487    int flag, at, ac;
488
489    if (pat == NULL)
490	return (0);
491
492    ac = 0;
493    at = 10;
494    av = (Char **) xmalloc((size_t) (at * sizeof(Char *)));
495    av[ac] = NULL;
496
497    tw_cmd_start(NULL, NULL);
498    while ((cmd = tw_cmd_next(dir, &flag)) != NULL)
499	if (Gmatch(cmd, pat)) {
500	    if (ac + 1 >= at) {
501		at += 10;
502		av = (Char **) xrealloc((ptr_t) av,
503					(size_t) (at * sizeof(Char *)));
504	    }
505	    av[ac++] = Strsave(cmd);
506	    av[ac] = NULL;
507	}
508    tw_dir_end();
509    *v = av;
510
511    return (ac);
512} /* end c_glob */
513
514
515/* insert_meta():
516 *      change the word before the cursor.
517 *        cp must point to the start of the unquoted word.
518 *        cpend to the end of it.
519 *        word is the text that has to be substituted.
520 *      strategy:
521 *        try to keep all the quote characters of the user's input.
522 *        change quote type only if necessary.
523 */
524static int
525insert_meta(cp, cpend, word, closequotes)
526    Char   *cp;
527    Char   *cpend;
528    Char   *word;
529    bool    closequotes;
530{
531    Char buffer[2 * FILSIZ + 1], *bptr, *wptr;
532    int in_sync = (cp != NULL);
533    int qu = 0;
534    int ndel = (int) (cp ? cpend - cp : 0);
535    Char w, wq;
536#ifdef DSPMBYTE
537    int mbytepos = 1;
538#endif /* DSPMBYTE */
539
540    for (bptr = buffer, wptr = word;;) {
541	if (bptr > buffer + 2 * FILSIZ - 5)
542	    break;
543
544	if (cp >= cpend)
545	    in_sync = 0;
546#ifdef DSPMBYTE
547	if (mbytepos == 1)
548#endif /* DSPMBYTE */
549	if (in_sync && !cmap(qu, _ESC) && cmap(*cp, _QF|_ESC))
550	    if (qu == 0 || qu == *cp) {
551		qu ^= *cp;
552		*bptr++ = *cp++;
553		continue;
554	    }
555	w = *wptr;
556	if (w == 0)
557	    break;
558
559	wq = w & QUOTE;
560	w &= ~QUOTE;
561
562#ifdef DSPMBYTE
563	if (mbytepos == 2)
564	  goto mbyteskip;
565#endif /* DSPMBYTE */
566	if (cmap(w, _ESC | _QF))
567	    wq = QUOTE;		/* quotes are always quoted */
568
569	if (!wq && qu && tricky(w) && !(qu == '\"' && tricky_dq(w))) {
570	    /* We have to unquote the character */
571	    in_sync = 0;
572	    if (cmap(qu, _ESC))
573		bptr[-1] = w;
574	    else {
575		*bptr++ = (Char) qu;
576		*bptr++ = w;
577		if (wptr[1] == 0)
578		    qu = 0;
579		else
580		    *bptr++ = (Char) qu;
581	    }
582	} else if (qu && w == qu) {
583	    in_sync = 0;
584	    if (bptr > buffer && bptr[-1] == qu) {
585		/* User misunderstanding :) */
586		bptr[-1] = '\\';
587		*bptr++ = w;
588		qu = 0;
589	    } else {
590		*bptr++ = (Char) qu;
591		*bptr++ = '\\';
592		*bptr++ = w;
593		*bptr++ = (Char) qu;
594	    }
595	}
596	else if (wq && qu == '\"' && tricky_dq(w)) {
597	    in_sync = 0;
598	    *bptr++ = (Char) qu;
599	    *bptr++ = '\\';
600	    *bptr++ = w;
601	    *bptr++ = (Char) qu;
602	} else if (wq && ((!qu && (tricky(w) || (w == HISTSUB && bptr == buffer))) || (!cmap(qu, _ESC) && w == HIST))) {
603	    in_sync = 0;
604	    *bptr++ = '\\';
605	    *bptr++ = w;
606	} else {
607#ifdef DSPMBYTE
608	  mbyteskip:
609#endif /* DSPMBYTE */
610	    if (in_sync && *cp++ != w)
611		in_sync = 0;
612	    *bptr++ = w;
613#ifdef DSPMBYTE
614	    if (mbytepos == 1 && Ismbyte1(w))
615	      mbytepos = 2;
616	    else
617	      mbytepos = 1;
618#endif /* DSPMBYTE */
619	}
620	wptr++;
621	if (cmap(qu, _ESC))
622	    qu = 0;
623    }
624    if (closequotes && qu && !cmap(qu, _ESC))
625	*bptr++ = (Char) qu;
626    *bptr = '\0';
627    if (ndel)
628	DeleteBack(ndel);
629    return InsertStr(buffer);
630} /* end insert_meta */
631
632
633
634/* is_prefix():
635 *	return true if check matches initial chars in template
636 *	This differs from PWB imatch in that if check is null
637 *	it matches anything
638 */
639static int
640is_prefix(check, template)
641    register Char *check, *template;
642{
643    for (; *check; check++, template++)
644	if ((*check & TRIM) != (*template & TRIM))
645	    return (FALSE);
646    return (TRUE);
647} /* end is_prefix */
648
649
650/* is_prefixmatch():
651 *	return true if check matches initial chars in template
652 *	This differs from PWB imatch in that if check is null
653 *	it matches anything
654 * and matches on shortening of commands
655 */
656static int
657is_prefixmatch(check, template, igncase)
658    Char *check, *template;
659    int igncase;
660{
661    Char MCH1, MCH2;
662
663    for (; *check; check++, template++) {
664	if ((*check & TRIM) != (*template & TRIM)) {
665            MCH1 = (*check & TRIM);
666            MCH2 = (*template & TRIM);
667            MCH1 = Isupper(MCH1) ? Tolower(MCH1) : MCH1;
668            MCH2 = Isupper(MCH2) ? Tolower(MCH2) : MCH2;
669            if (MCH1 != MCH2) {
670                if (!igncase && ((*check & TRIM) == '-' ||
671				 (*check & TRIM) == '.' ||
672				 (*check & TRIM) == '_')) {
673                    MCH1 = MCH2 = (*check & TRIM);
674                    if (MCH1 == '_') {
675                        MCH2 = '-';
676                    } else if (MCH1 == '-') {
677                        MCH2 = '_';
678                    }
679                    for (;*template && (*template & TRIM) != MCH1 &&
680				       (*template & TRIM) != MCH2; template++)
681			continue;
682                    if (!*template) {
683	                return (FALSE);
684                    }
685                } else {
686	            return (FALSE);
687                }
688            }
689        }
690    }
691    return (TRUE);
692} /* end is_prefixmatch */
693
694
695/* is_suffix():
696 *	Return true if the chars in template appear at the
697 *	end of check, I.e., are it's suffix.
698 */
699static int
700is_suffix(check, template)
701    register Char *check, *template;
702{
703    register Char *t, *c;
704
705    for (t = template; *t++;)
706	continue;
707    for (c = check; *c++;)
708	continue;
709    for (;;) {
710	if (t == template)
711	    return 1;
712	if (c == check || (*--t & TRIM) != (*--c & TRIM))
713	    return 0;
714    }
715} /* end is_suffix */
716
717
718/* ignored():
719 *	Return true if this is an ignored item
720 */
721static int
722ignored(item)
723    register Char *item;
724{
725    struct varent *vp;
726    register Char **cp;
727
728    if ((vp = adrof(STRfignore)) == NULL || (cp = vp->vec) == NULL)
729	return (FALSE);
730    for (; *cp != NULL; cp++)
731	if (is_suffix(item, *cp))
732	    return (TRUE);
733    return (FALSE);
734} /* end ignored */
735
736
737
738/* starting_a_command():
739 *	return true if the command starting at wordstart is a command
740 */
741int
742starting_a_command(wordstart, inputline)
743    register Char *wordstart, *inputline;
744{
745    register Char *ptr, *ncmdstart;
746    int     count;
747    static  Char
748            cmdstart[] = {'`', ';', '&', '(', '|', '\0'},
749            cmdalive[] = {' ', '\t', '\'', '"', '<', '>', '\0'};
750
751    /*
752     * Find if the number of backquotes is odd or even.
753     */
754    for (ptr = wordstart, count = 0;
755	 ptr >= inputline;
756	 count += (*ptr-- == '`'))
757	continue;
758    /*
759     * if the number of backquotes is even don't include the backquote char in
760     * the list of command starting delimiters [if it is zero, then it does not
761     * matter]
762     */
763    ncmdstart = cmdstart + EVEN(count);
764
765    /*
766     * look for the characters previous to this word if we find a command
767     * starting delimiter we break. if we find whitespace and another previous
768     * word then we are not a command
769     *
770     * count is our state machine: 0 looking for anything 1 found white-space
771     * looking for non-ws
772     */
773    for (count = 0; wordstart >= inputline; wordstart--) {
774	if (*wordstart == '\0')
775	    continue;
776	if (Strchr(ncmdstart, *wordstart))
777	    break;
778	/*
779	 * found white space
780	 */
781	if ((ptr = Strchr(cmdalive, *wordstart)) != NULL)
782	    count = 1;
783	if (count == 1 && !ptr)
784	    return (FALSE);
785    }
786
787    if (wordstart > inputline)
788	switch (*wordstart) {
789	case '&':		/* Look for >& */
790	    while (wordstart > inputline &&
791		   (*--wordstart == ' ' || *wordstart == '\t'))
792		continue;
793	    if (*wordstart == '>')
794		return (FALSE);
795	    break;
796	case '(':		/* check for foreach, if etc. */
797	    while (wordstart > inputline &&
798		   (*--wordstart == ' ' || *wordstart == '\t'))
799		continue;
800	    if (!iscmdmeta(*wordstart) &&
801		(*wordstart != ' ' && *wordstart != '\t'))
802		return (FALSE);
803	    break;
804	default:
805	    break;
806	}
807    return (TRUE);
808} /* end starting_a_command */
809
810
811/* recognize():
812 *	Object: extend what user typed up to an ambiguity.
813 *	Algorithm:
814 *	On first match, copy full item (assume it'll be the only match)
815 *	On subsequent matches, shorten exp_name to the first
816 *	character mismatch between exp_name and item.
817 *	If we shorten it back to the prefix length, stop searching.
818 */
819static int
820recognize(exp_name, item, name_length, numitems, enhanced)
821    Char   *exp_name, *item;
822    int     name_length, numitems, enhanced;
823{
824    Char MCH1, MCH2;
825    register Char *x, *ent;
826    register int len = 0;
827#ifdef WINNT_NATIVE
828    struct varent *vp;
829    int igncase;
830    igncase = (vp = adrof(STRcomplete)) != NULL &&
831	Strcmp(*(vp->vec), STRigncase) == 0;
832#endif /* WINNT_NATIVE */
833
834    if (numitems == 1) {	/* 1st match */
835	copyn(exp_name, item, MAXNAMLEN);
836	return (0);
837    }
838    if (!enhanced
839#ifdef WINNT_NATIVE
840	&& !igncase
841#endif /* WINNT_NATIVE */
842    ) {
843	for (x = exp_name, ent = item; *x && (*x & TRIM) == (*ent & TRIM); x++, ent++)
844	    len++;
845    } else {
846	for (x = exp_name, ent = item; *x; x++, ent++) {
847	    MCH1 = *x & TRIM;
848	    MCH2 = *ent & TRIM;
849            MCH1 = Isupper(MCH1) ? Tolower(MCH1) : MCH1;
850            MCH2 = Isupper(MCH2) ? Tolower(MCH2) : MCH2;
851	    if (MCH1 != MCH2)
852		break;
853	    len++;
854	}
855	if (*x || !*ent)	/* Shorter or exact match */
856	    copyn(exp_name, item, MAXNAMLEN);
857    }
858    *x = '\0';		/* Shorten at 1st char diff */
859    if (!(match_unique_match || is_set(STRrecexact) || (enhanced && *ent)) && len == name_length)	/* Ambiguous to prefix? */
860	return (-1);	/* So stop now and save time */
861    return (0);
862} /* end recognize */
863
864
865/* tw_collect_items():
866 *	Collect items that match target.
867 *	SPELL command:
868 *		Returns the spelling distance of the closest match.
869 *	else
870 *		Returns the number of items found.
871 *		If none found, but some ignored items were found,
872 *		It returns the -number of ignored items.
873 */
874static int
875tw_collect_items(command, looking, exp_dir, exp_name, target, pat, flags)
876    COMMAND command;
877    int looking;
878    Char *exp_dir, *exp_name, *target, *pat;
879    int flags;
880
881{
882    int done = FALSE;			 /* Search is done */
883    int showdots;			 /* Style to show dot files */
884    int nignored = 0;			 /* Number of fignored items */
885    int numitems = 0;			 /* Number of matched items */
886    int name_length = (int) Strlen(target); /* Length of prefix (file name) */
887    int exec_check = flags & TW_EXEC_CHK;/* need to check executability	*/
888    int dir_check  = flags & TW_DIR_CHK; /* Need to check for directories */
889    int text_check = flags & TW_TEXT_CHK;/* Need to check for non-directories */
890    int dir_ok     = flags & TW_DIR_OK;  /* Ignore directories? */
891    int gpat       = flags & TW_PAT_OK;	 /* Match against a pattern */
892    int ignoring   = flags & TW_IGN_OK;	 /* Use fignore? */
893    int d = 4, nd;			 /* Spelling distance */
894    Char *item, *ptr;
895    Char buf[MAXPATHLEN+1];
896    struct varent *vp;
897    int len, enhanced;
898    int cnt = 0;
899    int igncase = 0;
900
901
902    flags = 0;
903
904    showdots = DOT_NONE;
905    if ((ptr = varval(STRlistflags)) != STRNULL)
906	while (*ptr)
907	    switch (*ptr++) {
908	    case 'a':
909		showdots = DOT_ALL;
910		break;
911	    case 'A':
912		showdots = DOT_NOT;
913		break;
914	    default:
915		break;
916	    }
917
918    while (!done && (item = (*tw_next_entry[looking])(exp_dir, &flags))) {
919#ifdef TDEBUG
920	xprintf("item = %S\n", item);
921#endif
922	switch (looking) {
923	case TW_FILE:
924	case TW_DIRECTORY:
925	case TW_TEXT:
926	    /*
927	     * Don't match . files on null prefix match
928	     */
929	    if (showdots == DOT_NOT && (ISDOT(item) || ISDOTDOT(item)))
930		done = TRUE;
931	    if (name_length == 0 && item[0] == '.' && showdots == DOT_NONE)
932		done = TRUE;
933	    break;
934
935	case TW_COMMAND:
936	    exec_check = flags & TW_EXEC_CHK;
937	    dir_ok = flags & TW_DIR_OK;
938	    break;
939
940	default:
941	    break;
942	}
943
944	if (done) {
945	    done = FALSE;
946	    continue;
947	}
948
949	switch (command) {
950
951	case SPELL:		/* correct the spelling of the last bit */
952	    if (name_length == 0) {/* zero-length word can't be misspelled */
953		exp_name[0] = '\0';/* (not trying is important for ~) */
954		d = 0;
955		done = TRUE;
956		break;
957	    }
958	    if (gpat && !Gmatch(item, pat))
959		break;
960	    /*
961	     * Swapped the order of the spdist() arguments as suggested
962	     * by eeide@asylum.cs.utah.edu (Eric Eide)
963	     */
964	    nd = spdist(target, item);	/* test the item against original */
965	    if (nd <= d && nd != 4) {
966		if (!(exec_check && !executable(exp_dir, item, dir_ok))) {
967		    (void) Strcpy(exp_name, item);
968		    d = nd;
969		    if (d == 0)	/* if found it exactly */
970			done = TRUE;
971		}
972	    }
973	    else if (nd == 4) {
974		if (spdir(exp_name, exp_dir, item, target)) {
975		    if (exec_check && !executable(exp_dir, exp_name, dir_ok))
976			break;
977#ifdef notdef
978		    /*
979		     * We don't want to stop immediately, because
980		     * we might find an exact/better match later.
981		     */
982		    d = 0;
983		    done = TRUE;
984#endif
985		    d = 3;
986		}
987	    }
988	    break;
989
990	case LIST:
991	case RECOGNIZE:
992	case RECOGNIZE_ALL:
993	case RECOGNIZE_SCROLL:
994
995#ifdef WINNT_NATIVE
996 	    igncase = (vp = adrof(STRcomplete)) != NULL &&
997		Strcmp(*(vp->vec), STRigncase) == 0;
998#endif /* WINNT_NATIVE */
999	    enhanced = (vp = adrof(STRcomplete)) != NULL && !Strcmp(*(vp->vec),STRenhance);
1000	    if (enhanced || igncase) {
1001	        if (!is_prefixmatch(target, item, igncase))
1002		    break;
1003     	    } else {
1004	        if (!is_prefix(target, item))
1005		    break;
1006	    }
1007
1008	    if (exec_check && !executable(exp_dir, item, dir_ok))
1009		break;
1010
1011	    if (dir_check && !isadirectory(exp_dir, item))
1012		break;
1013
1014	    if (text_check && isadirectory(exp_dir, item))
1015		break;
1016
1017	    /*
1018	     * Only pattern match directories if we're checking
1019	     * for directories.
1020	     */
1021	    if (gpat && !Gmatch(item, pat) &&
1022		(dir_check || !isadirectory(exp_dir, item)))
1023		    break;
1024
1025	    /*
1026	     * Remove duplicates in command listing and completion
1027             * AFEB added code for TW_LOGNAME and TW_USER cases
1028	     */
1029	    if (looking == TW_COMMAND || looking == TW_LOGNAME
1030		|| looking == TW_USER || command == LIST) {
1031		copyn(buf, item, MAXPATHLEN);
1032		len = (int) Strlen(buf);
1033		switch (looking) {
1034		case TW_COMMAND:
1035		    if (!(dir_ok && exec_check))
1036			break;
1037		    if (filetype(exp_dir, item) == '/') {
1038			buf[len++] = '/';
1039			buf[len] = '\0';
1040		    }
1041		    break;
1042
1043		case TW_FILE:
1044		case TW_DIRECTORY:
1045		    buf[len++] = filetype(exp_dir, item);
1046		    buf[len] = '\0';
1047		    break;
1048
1049		default:
1050		    break;
1051		}
1052		if ((looking == TW_COMMAND || looking == TW_USER
1053                     || looking == TW_LOGNAME) && tw_item_find(buf))
1054		    break;
1055		else {
1056		    /* maximum length 1 (NULL) + 1 (~ or $) + 1 (filetype) */
1057		    ptr = tw_item_add(len + 3);
1058		    copyn(ptr, buf, MAXPATHLEN);
1059		    if (command == LIST)
1060			numitems++;
1061		}
1062	    }
1063
1064	    if (command == RECOGNIZE || command == RECOGNIZE_ALL ||
1065		command == RECOGNIZE_SCROLL) {
1066		if (ignoring && ignored(item)) {
1067		    nignored++;
1068		    break;
1069		}
1070		else if (command == RECOGNIZE_SCROLL) {
1071		    add_scroll_tab(item);
1072		    cnt++;
1073		}
1074
1075		if (match_unique_match || is_set(STRrecexact)) {
1076		    if (StrQcmp(target, item) == 0) {	/* EXACT match */
1077			copyn(exp_name, item, MAXNAMLEN);
1078			numitems = 1;	/* fake into expanding */
1079			non_unique_match = TRUE;
1080			done = TRUE;
1081			break;
1082		    }
1083		}
1084		if (recognize(exp_name, item, name_length, ++numitems, enhanced))
1085		    if (command != RECOGNIZE_SCROLL)
1086			done = TRUE;
1087		if (enhanced && (int)Strlen(exp_name) < name_length)
1088		    copyn(exp_name, target, MAXNAMLEN);
1089	    }
1090	    break;
1091
1092	default:
1093	    break;
1094	}
1095#ifdef TDEBUG
1096	xprintf("done item = %S\n", item);
1097#endif
1098    }
1099
1100
1101    if (command == RECOGNIZE_SCROLL) {
1102	if ((cnt <= curchoice) || (curchoice == -1)) {
1103	    curchoice = -1;
1104	    nignored = 0;
1105	    numitems = 0;
1106	} else if (numitems > 1) {
1107	    if (curchoice < -1)
1108		curchoice = cnt - 1;
1109	    choose_scroll_tab(&exp_name, cnt);
1110	    numitems = 1;
1111	}
1112    }
1113    free_scroll_tab();
1114
1115    if (command == SPELL)
1116	return d;
1117    else {
1118	if (ignoring && numitems == 0 && nignored > 0)
1119	    return -nignored;
1120	else
1121	    return numitems;
1122    }
1123}
1124
1125
1126/* tw_suffix():
1127 *	Find and return the appropriate suffix character
1128 */
1129/*ARGSUSED*/
1130static Char
1131tw_suffix(looking, exp_dir, exp_name, target, name)
1132    int looking;
1133    Char *exp_dir, *exp_name, *target, *name;
1134{
1135    Char *ptr;
1136    struct varent *vp;
1137
1138    USE(name);
1139    (void) strip(exp_name);
1140
1141    switch (looking) {
1142
1143    case TW_LOGNAME:
1144	return '/';
1145
1146    case TW_VARIABLE:
1147	/*
1148	 * Don't consider array variables or empty variables
1149	 */
1150	if ((vp = adrof(exp_name)) != NULL) {
1151	    if ((ptr = vp->vec[0]) == NULL || *ptr == '\0' ||
1152		vp->vec[1] != NULL)
1153		return ' ';
1154	}
1155	else if ((ptr = tgetenv(exp_name)) == NULL || *ptr == '\0')
1156	    return ' ';
1157
1158	*--target = '\0';
1159
1160	return isadirectory(exp_dir, ptr) ? '/' : ' ';
1161
1162
1163    case TW_DIRECTORY:
1164	return '/';
1165
1166    case TW_COMMAND:
1167    case TW_FILE:
1168	return isadirectory(exp_dir, exp_name) ? '/' : ' ';
1169
1170    case TW_ALIAS:
1171    case TW_VARLIST:
1172    case TW_WORDLIST:
1173    case TW_SHELLVAR:
1174    case TW_ENVVAR:
1175    case TW_USER:
1176    case TW_BINDING:
1177    case TW_LIMIT:
1178    case TW_SIGNAL:
1179    case TW_JOB:
1180    case TW_COMPLETION:
1181    case TW_TEXT:
1182    case TW_GRPNAME:
1183	return ' ';
1184
1185    default:
1186	return '\0';
1187    }
1188} /* end tw_suffix */
1189
1190
1191/* tw_fixword():
1192 *	Repair a word after a spalling or a recognizwe
1193 */
1194static void
1195tw_fixword(looking, word, dir, exp_name, max_word_length)
1196    int looking;
1197    Char *word, *dir, *exp_name;
1198    int max_word_length;
1199{
1200    Char *ptr;
1201
1202    switch (looking) {
1203    case TW_LOGNAME:
1204	copyn(word, STRtilde, 1);
1205	break;
1206
1207    case TW_VARIABLE:
1208	if ((ptr = Strrchr(word, '$')) != NULL)
1209	    *++ptr = '\0';	/* Delete after the dollar */
1210	else
1211	    word[0] = '\0';
1212	break;
1213
1214    case TW_DIRECTORY:
1215    case TW_FILE:
1216    case TW_TEXT:
1217	copyn(word, dir, max_word_length);	/* put back dir part */
1218	break;
1219
1220    default:
1221	word[0] = '\0';
1222	break;
1223    }
1224
1225    (void) quote(exp_name);
1226    catn(word, exp_name, max_word_length);	/* add extended name */
1227} /* end tw_fixword */
1228
1229
1230/* tw_collect():
1231 *	Collect items. Return -1 in case we were interrupted or
1232 *	the return value of tw_collect
1233 *	This is really a wrapper for tw_collect_items, serving two
1234 *	purposes:
1235 *		1. Handles interrupt cleanups.
1236 *		2. Retries if we had no matches, but there were ignored matches
1237 */
1238static int
1239tw_collect(command, looking, exp_dir, exp_name, target, pat, flags, dir_fd)
1240    COMMAND command;
1241    int looking;
1242    Char *exp_dir, *exp_name, **target, *pat;
1243    int flags;
1244    DIR *dir_fd;
1245{
1246    static int ni;	/* static so we don't get clobbered */
1247    jmp_buf_t osetexit;
1248
1249#ifdef TDEBUG
1250    xprintf("target = %S\n", *target);
1251#endif
1252    ni = 0;
1253    getexit(osetexit);
1254    for (;;) {
1255	(*tw_start_entry[looking])(dir_fd, pat);
1256	InsideCompletion = 1;
1257	if (setexit()) {
1258	    /* interrupted, clean up */
1259	    resexit(osetexit);
1260	    InsideCompletion = 0;
1261	    haderr = 0;
1262
1263#if defined(SOLARIS2) && defined(i386) && !defined(__GNUC__)
1264	    /* Compiler bug? (from PWP) */
1265	    if ((looking == TW_LOGNAME) || (looking == TW_USER))
1266		tw_logname_end();
1267	    else
1268		if (looking == TW_GRPNAME)
1269		   tw_grpname_end();
1270		else
1271		    tw_dir_end();
1272#else /* !(SOLARIS2 && i386 && !__GNUC__) */
1273	    (*tw_end_entry[looking])();
1274#endif /* !(SOLARIS2 && i386 && !__GNUC__) */
1275
1276	    /* flag error */
1277	    return(-1);
1278	}
1279        if ((ni = tw_collect_items(command, looking, exp_dir, exp_name,
1280			           *target, pat,
1281				   ni >= 0 ? flags :
1282					flags & ~TW_IGN_OK)) >= 0) {
1283	    resexit(osetexit);
1284	    InsideCompletion = 0;
1285
1286#if defined(SOLARIS2) && defined(i386) && !defined(__GNUC__)
1287	    /* Compiler bug? (from PWP) */
1288	    if ((looking == TW_LOGNAME) || (looking == TW_USER))
1289		tw_logname_end();
1290	    else
1291		if (looking == TW_GRPNAME)
1292		   tw_grpname_end();
1293		else
1294		    tw_dir_end();
1295#else /* !(SOLARIS2 && i386 && !__GNUC__) */
1296	    (*tw_end_entry[looking])();
1297#endif /* !(SOLARIS2 && i386 && !__GNUC__) */
1298
1299	    return(ni);
1300	}
1301    }
1302} /* end tw_collect */
1303
1304
1305/* tw_list_items():
1306 *	List the items that were found
1307 *
1308 *	NOTE instead of looking at numerical vars listmax and listmaxrows
1309 *	we can look at numerical var listmax, and have a string value
1310 *	listmaxtype (or similar) than can have values 'items' and 'rows'
1311 *	(by default interpreted as 'items', for backwards compatibility)
1312 */
1313static void
1314tw_list_items(looking, numitems, list_max)
1315    int looking, numitems, list_max;
1316{
1317    Char *ptr;
1318    int max_items = 0;
1319    int max_rows = 0;
1320
1321    if ((ptr = varval(STRlistmax)) != STRNULL) {
1322	while (*ptr) {
1323	    if (!Isdigit(*ptr)) {
1324		max_items = 0;
1325		break;
1326	    }
1327	    max_items = max_items * 10 + *ptr++ - '0';
1328	}
1329	if ((max_items > 0) && (numitems > max_items) && list_max)
1330	    max_items = numitems;
1331	else
1332	    max_items = 0;
1333    }
1334
1335    if (max_items == 0 && (ptr = varval(STRlistmaxrows)) != STRNULL) {
1336	int rows;
1337
1338	while (*ptr) {
1339	    if (!Isdigit(*ptr)) {
1340		max_rows = 0;
1341		break;
1342	    }
1343	    max_rows = max_rows * 10 + *ptr++ - '0';
1344	}
1345	if (max_rows != 0 && looking != TW_JOB)
1346	    rows = find_rows(tw_item_get(), numitems, TRUE);
1347	else
1348	    rows = numitems; /* underestimate for lines wider than the termH */
1349	if ((max_rows > 0) && (rows > max_rows) && list_max)
1350	    max_rows = rows;
1351	else
1352	    max_rows = 0;
1353    }
1354
1355
1356    if (max_items || max_rows) {
1357	char    	 tc;
1358	const char	*name;
1359	int maxs;
1360
1361	if (max_items) {
1362	    name = CGETS(30, 5, "items");
1363	    maxs = max_items;
1364	}
1365	else {
1366	    name = CGETS(30, 6, "rows");
1367	    maxs = max_rows;
1368	}
1369
1370	xprintf(CGETS(30, 7, "There are %d %s, list them anyway? [n/y] "),
1371		maxs, name);
1372	flush();
1373	/* We should be in Rawmode here, so no \n to catch */
1374	(void) read(SHIN, &tc, 1);
1375	xprintf("%c\r\n", tc);	/* echo the char, do a newline */
1376	/*
1377	 * Perhaps we should use the yesexpr from the
1378	 * actual locale
1379	 */
1380	if (strchr(CGETS(30, 13, "Yy"), tc) == NULL)
1381	    return;
1382    }
1383
1384    if (looking != TW_SIGNAL)
1385	qsort((ptr_t) tw_item_get(), (size_t) numitems, sizeof(Char *),
1386	      (int (*) __P((const void *, const void *))) fcompare);
1387    if (looking != TW_JOB)
1388	print_by_column(STRNULL, tw_item_get(), numitems, TRUE);
1389    else {
1390	/*
1391	 * print one item on every line because jobs can have spaces
1392	 * and it is confusing.
1393	 */
1394	int i;
1395	Char **w = tw_item_get();
1396
1397	for (i = 0; i < numitems; i++) {
1398	    xprintf("%S", w[i]);
1399	    if (Tty_raw_mode)
1400		xputchar('\r');
1401	    xputchar('\n');
1402	}
1403    }
1404} /* end tw_list_items */
1405
1406
1407/* t_search():
1408 *	Perform a RECOGNIZE, LIST or SPELL command on string "word".
1409 *
1410 *	Return value:
1411 *		>= 0:   SPELL command: "distance" (see spdist())
1412 *		                other: No. of items found
1413 *  		 < 0:   Error (message or beep is output)
1414 */
1415/*ARGSUSED*/
1416int
1417t_search(word, wp, command, max_word_length, looking, list_max, pat, suf)
1418    Char   *word, *wp;		/* original end-of-word */
1419    COMMAND command;
1420    int     max_word_length, looking, list_max;
1421    Char   *pat;
1422    int     suf;
1423{
1424    int     numitems,			/* Number of items matched */
1425	    flags = 0,			/* search flags */
1426	    gpat = pat[0] != '\0',	/* Glob pattern search */
1427	    nd;				/* Normalized directory return */
1428    Char    exp_dir[FILSIZ + 1],	/* dir after ~ expansion */
1429            dir[FILSIZ + 1],		/* /x/y/z/ part in /x/y/z/f */
1430            exp_name[MAXNAMLEN + 1],	/* the recognized (extended) */
1431            name[MAXNAMLEN + 1],	/* f part in /d/d/d/f name */
1432           *target;			/* Target to expand/correct/list */
1433    DIR    *dir_fd = NULL;
1434
1435    USE(wp);
1436
1437    /*
1438     * bugfix by Marty Grossman (grossman@CC5.BBN.COM): directory listing can
1439     * dump core when interrupted
1440     */
1441    tw_item_free();
1442
1443    non_unique_match = FALSE;	/* See the recexact code below */
1444
1445    extract_dir_and_name(word, dir, name);
1446
1447    /*
1448     *  SPECIAL HARDCODED COMPLETIONS:
1449     *    foo$variable                -> TW_VARIABLE
1450     *    ~user                       -> TW_LOGNAME
1451     *
1452     */
1453    if ((*word == '~') && (Strchr(word, '/') == NULL)) {
1454	looking = TW_LOGNAME;
1455	target = name;
1456	gpat = 0;	/* Override pattern mechanism */
1457    }
1458    else if ((target = Strrchr(name, '$')) != 0 &&
1459	     (Strchr(name, '/') == NULL)) {
1460	target++;
1461	looking = TW_VARIABLE;
1462	gpat = 0;	/* Override pattern mechanism */
1463    }
1464    else
1465	target = name;
1466
1467    /*
1468     * Try to figure out what we should be looking for
1469     */
1470    if (looking & TW_PATH) {
1471	gpat = 0;	/* pattern holds the pathname to be used */
1472	copyn(exp_dir, pat, MAXNAMLEN);
1473	if (exp_dir[Strlen(exp_dir) - 1] != '/')
1474	    catn(exp_dir, STRslash, MAXNAMLEN);
1475	catn(exp_dir, dir, MAXNAMLEN);
1476    }
1477    else
1478	exp_dir[0] = '\0';
1479
1480    switch (looking & ~TW_PATH) {
1481    case TW_NONE:
1482	return -1;
1483
1484    case TW_ZERO:
1485	looking = TW_FILE;
1486	break;
1487
1488    case TW_COMMAND:
1489	if (Strchr(word, '/') || (looking & TW_PATH)) {
1490	    looking = TW_FILE;
1491	    flags |= TW_EXEC_CHK;
1492	    flags |= TW_DIR_OK;
1493	}
1494#ifdef notdef
1495	/* PWP: don't even bother when doing ALL of the commands */
1496	if (looking == TW_COMMAND && (*word == '\0'))
1497	    return (-1);
1498#endif
1499	break;
1500
1501
1502    case TW_VARLIST:
1503    case TW_WORDLIST:
1504	gpat = 0;	/* pattern holds the name of the variable */
1505	break;
1506
1507    case TW_EXPLAIN:
1508	if (command == LIST && pat != NULL) {
1509	    xprintf("%S", pat);
1510	    if (Tty_raw_mode)
1511		xputchar('\r');
1512	    xputchar('\n');
1513	}
1514	return 2;
1515
1516    default:
1517	break;
1518    }
1519
1520    /*
1521     * let fignore work only when we are not using a pattern
1522     */
1523    flags |= (gpat == 0) ? TW_IGN_OK : TW_PAT_OK;
1524
1525#ifdef TDEBUG
1526    xprintf(CGETS(30, 8, "looking = %d\n"), looking);
1527#endif
1528
1529    switch (looking) {
1530    case TW_ALIAS:
1531    case TW_SHELLVAR:
1532    case TW_ENVVAR:
1533    case TW_BINDING:
1534    case TW_LIMIT:
1535    case TW_SIGNAL:
1536    case TW_JOB:
1537    case TW_COMPLETION:
1538    case TW_GRPNAME:
1539	break;
1540
1541
1542    case TW_VARIABLE:
1543	if ((nd = expand_dir(dir, exp_dir, &dir_fd, command)) != 0)
1544	    return nd;
1545	break;
1546
1547    case TW_DIRECTORY:
1548	flags |= TW_DIR_CHK;
1549
1550#ifdef notyet
1551	/*
1552	 * This is supposed to expand the directory stack.
1553	 * Problems:
1554	 * 1. Slow
1555	 * 2. directories with the same name
1556	 */
1557	flags |= TW_DIR_OK;
1558#endif
1559#ifdef notyet
1560	/*
1561	 * Supposed to do delayed expansion, but it is inconsistent
1562	 * from a user-interface point of view, since it does not
1563	 * immediately obey addsuffix
1564	 */
1565	if ((nd = expand_dir(dir, exp_dir, &dir_fd, command)) != 0)
1566	    return nd;
1567	if (isadirectory(exp_dir, name)) {
1568	    if (exp_dir[0] != '\0' || name[0] != '\0') {
1569		catn(dir, name, MAXNAMLEN);
1570		if (dir[Strlen(dir) - 1] != '/')
1571		    catn(dir, STRslash, MAXNAMLEN);
1572		if ((nd = expand_dir(dir, exp_dir, &dir_fd, command)) != 0)
1573		    return nd;
1574		if (word[Strlen(word) - 1] != '/')
1575		    catn(word, STRslash, MAXNAMLEN);
1576		name[0] = '\0';
1577	    }
1578	}
1579#endif
1580	if ((nd = expand_dir(dir, exp_dir, &dir_fd, command)) != 0)
1581	    return nd;
1582	break;
1583
1584    case TW_TEXT:
1585	flags |= TW_TEXT_CHK;
1586	/*FALLTHROUGH*/
1587    case TW_FILE:
1588	if ((nd = expand_dir(dir, exp_dir, &dir_fd, command)) != 0)
1589	    return nd;
1590	break;
1591
1592    case TW_PATH | TW_TEXT:
1593    case TW_PATH | TW_FILE:
1594    case TW_PATH | TW_DIRECTORY:
1595    case TW_PATH | TW_COMMAND:
1596	if ((dir_fd = opendir(short2str(exp_dir))) == NULL) {
1597	    xprintf("%S: %s\n", exp_dir, strerror(errno));
1598	    return -1;
1599	}
1600	if (exp_dir[Strlen(exp_dir) - 1] != '/')
1601	    catn(exp_dir, STRslash, MAXNAMLEN);
1602
1603	looking &= ~TW_PATH;
1604
1605	switch (looking) {
1606	case TW_TEXT:
1607	    flags |= TW_TEXT_CHK;
1608	    break;
1609
1610	case TW_FILE:
1611	    break;
1612
1613	case TW_DIRECTORY:
1614	    flags |= TW_DIR_CHK;
1615	    break;
1616
1617	case TW_COMMAND:
1618	    copyn(target, word, MAXNAMLEN);	/* so it can match things */
1619	    break;
1620
1621	default:
1622	    abort();	/* Cannot happen */
1623	    break;
1624	}
1625	break;
1626
1627    case TW_LOGNAME:
1628	word++;
1629	/*FALLTHROUGH*/
1630    case TW_USER:
1631	/*
1632	 * Check if the spelling was already correct
1633	 * From: Rob McMahon <cudcv@cu.warwick.ac.uk>
1634	 */
1635	if (command == SPELL && getpwnam(short2str(word)) != NULL) {
1636#ifdef YPBUGS
1637	    fix_yp_bugs();
1638#endif /* YPBUGS */
1639	    return (0);
1640	}
1641	copyn(name, word, MAXNAMLEN);	/* name sans ~ */
1642	if (looking == TW_LOGNAME)
1643	    word--;
1644	break;
1645
1646    case TW_COMMAND:
1647    case TW_VARLIST:
1648    case TW_WORDLIST:
1649	copyn(target, word, MAXNAMLEN);	/* so it can match things */
1650	break;
1651
1652    default:
1653	xprintf(CGETS(30, 9,
1654		"\n%s internal error: I don't know what I'm looking for!\n"),
1655		progname);
1656	NeedsRedraw = 1;
1657	return (-1);
1658    }
1659
1660    numitems = tw_collect(command, looking, exp_dir, exp_name,
1661			  &target, pat, flags, dir_fd);
1662    if (numitems == -1)
1663	return -1;
1664
1665    switch (command) {
1666    case RECOGNIZE:
1667    case RECOGNIZE_ALL:
1668    case RECOGNIZE_SCROLL:
1669	if (numitems <= 0)
1670	    return (numitems);
1671
1672	tw_fixword(looking, word, dir, exp_name, max_word_length);
1673
1674	if (!match_unique_match && is_set(STRaddsuffix) && numitems == 1) {
1675	    Char suffix[2];
1676
1677	    suffix[1] = '\0';
1678	    switch (suf) {
1679	    case 0: 	/* Automatic suffix */
1680		suffix[0] = tw_suffix(looking, exp_dir, exp_name, target, name);
1681		break;
1682
1683	    case -1:	/* No suffix */
1684		return numitems;
1685
1686	    default:	/* completion specified suffix */
1687		suffix[0] = (Char) suf;
1688		break;
1689	    }
1690	    catn(word, suffix, max_word_length);
1691	}
1692	return numitems;
1693
1694    case LIST:
1695	tw_list_items(looking, numitems, list_max);
1696	tw_item_free();
1697	return (numitems);
1698
1699    case SPELL:
1700	tw_fixword(looking, word, dir, exp_name, max_word_length);
1701	return (numitems);
1702
1703    default:
1704	xprintf("Bad tw_command\n");
1705	return (0);
1706    }
1707} /* end t_search */
1708
1709
1710/* extract_dir_and_name():
1711 * 	parse full path in file into 2 parts: directory and file names
1712 * 	Should leave final slash (/) at end of dir.
1713 */
1714static void
1715extract_dir_and_name(path, dir, name)
1716    Char   *path, *dir, *name;
1717{
1718    register Char *p;
1719
1720    p = Strrchr(path, '/');
1721#ifdef WINNT_NATIVE
1722    if (p == NULL)
1723	p = Strrchr(path, ':');
1724#endif /* WINNT_NATIVE */
1725    if (p == NULL) {
1726	copyn(name, path, MAXNAMLEN);
1727	dir[0] = '\0';
1728    }
1729    else {
1730	p++;
1731	copyn(name, p, MAXNAMLEN);
1732	copyn(dir, path, p - path);
1733    }
1734} /* end extract_dir_and_name */
1735
1736
1737/* dollar():
1738 * 	expand "/$old1/$old2/old3/"
1739 * 	to "/value_of_old1/value_of_old2/old3/"
1740 */
1741Char *
1742dollar(new, old)
1743    Char   *new;
1744    const Char *old;
1745{
1746    Char    *p;
1747    size_t   space;
1748
1749    for (space = FILSIZ, p = new; *old && space > 0;)
1750	if (*old != '$') {
1751	    *p++ = *old++;
1752	    space--;
1753	}
1754	else {
1755	    if (expdollar(&p, &old, &space, QUOTE) == NULL)
1756		return NULL;
1757	}
1758    *p = '\0';
1759    return (new);
1760} /* end dollar */
1761
1762
1763/* tilde():
1764 * 	expand ~person/foo to home_directory_of_person/foo
1765 *	or =<stack-entry> to <dir in stack entry>
1766 */
1767static Char *
1768tilde(new, old)
1769    Char   *new, *old;
1770{
1771    register Char *o, *p;
1772
1773    switch (old[0]) {
1774    case '~':
1775	for (p = new, o = &old[1]; *o && *o != '/'; *p++ = *o++)
1776	    continue;
1777	*p = '\0';
1778	if (gethdir(new)) {
1779	    new[0] = '\0';
1780	    return NULL;
1781	}
1782	(void) Strcat(new, o);
1783	return new;
1784
1785    case '=':
1786	if ((p = globequal(new, old)) == NULL) {
1787	    *new = '\0';
1788	    return NULL;
1789	}
1790	if (p == new)
1791	    return new;
1792	/*FALLTHROUGH*/
1793
1794    default:
1795	(void) Strcpy(new, old);
1796	return new;
1797    }
1798} /* end tilde */
1799
1800
1801/* expand_dir():
1802 *	Open the directory given, expanding ~user and $var
1803 *	Optionally normalize the path given
1804 */
1805static int
1806expand_dir(dir, edir, dfd, cmd)
1807    Char   *dir, *edir;
1808    DIR   **dfd;
1809    COMMAND cmd;
1810{
1811    Char   *nd = NULL;
1812    Char    tdir[MAXPATHLEN + 1];
1813
1814    if ((dollar(tdir, dir) == 0) ||
1815	(tilde(edir, tdir) == 0) ||
1816	!(nd = dnormalize(*edir ? edir : STRdot, symlinks == SYM_IGNORE ||
1817						 symlinks == SYM_EXPAND)) ||
1818	((*dfd = opendir(short2str(nd))) == NULL)) {
1819	xfree((ptr_t) nd);
1820	if (cmd == SPELL || SearchNoDirErr)
1821	    return (-2);
1822	/*
1823	 * From: Amos Shapira <amoss@cs.huji.ac.il>
1824	 * Print a better message when completion fails
1825	 */
1826	xprintf("\n%S %s\n",
1827		*edir ? edir :
1828		(*tdir ? tdir : dir),
1829		(errno == ENOTDIR ? CGETS(30, 10, "not a directory") :
1830		(errno == ENOENT ? CGETS(30, 11, "not found") :
1831		 CGETS(30, 12, "unreadable"))));
1832	NeedsRedraw = 1;
1833	return (-1);
1834    }
1835    if (nd) {
1836	if (*dir != '\0') {
1837	    Char   *s, *d, *p;
1838
1839	    /*
1840	     * Copy and append a / if there was one
1841	     */
1842	    for (p = edir; *p; p++)
1843		continue;
1844	    if (*--p == '/') {
1845		for (p = nd; *p; p++)
1846		    continue;
1847		if (*--p != '/')
1848		    p = NULL;
1849	    }
1850	    for (d = edir, s = nd; (*d++ = *s++) != '\0';)
1851		continue;
1852	    if (!p) {
1853		*d-- = '\0';
1854		*d = '/';
1855	    }
1856	}
1857	xfree((ptr_t) nd);
1858    }
1859    return 0;
1860} /* end expand_dir */
1861
1862
1863/* nostat():
1864 *	Returns true if the directory should not be stat'd,
1865 *	false otherwise.
1866 *	This way, things won't grind to a halt when you complete in /afs
1867 *	or very large directories.
1868 */
1869static bool
1870nostat(dir)
1871     Char *dir;
1872{
1873    struct varent *vp;
1874    register Char **cp;
1875
1876    if ((vp = adrof(STRnostat)) == NULL || (cp = vp->vec) == NULL)
1877	return FALSE;
1878    for (; *cp != NULL; cp++) {
1879	if (Strcmp(*cp, STRstar) == 0)
1880	    return TRUE;
1881	if (Gmatch(dir, *cp))
1882	    return TRUE;
1883    }
1884    return FALSE;
1885} /* end nostat */
1886
1887
1888/* filetype():
1889 *	Return a character that signifies a filetype
1890 *	symbology from 4.3 ls command.
1891 */
1892static  Char
1893filetype(dir, file)
1894    Char   *dir, *file;
1895{
1896    if (dir) {
1897	Char    path[512];
1898	char   *ptr;
1899	struct stat statb;
1900#ifdef S_ISCDF
1901	/*
1902	 * From: veals@crchh84d.bnr.ca (Percy Veals)
1903	 * An extra stat is required for HPUX CDF files.
1904	 */
1905	struct stat hpstatb;
1906#endif /* S_ISCDF */
1907
1908	if (nostat(dir)) return(' ');
1909
1910	(void) Strcpy(path, dir);
1911	catn(path, file, (int) (sizeof(path) / sizeof(Char)));
1912
1913	if (lstat(ptr = short2str(path), &statb) != -1)
1914	    /* see above #define of lstat */
1915	{
1916#ifdef S_ISLNK
1917	    if (S_ISLNK(statb.st_mode)) {	/* Symbolic link */
1918		if (adrof(STRlistlinks)) {
1919		    if (stat(ptr, &statb) == -1)
1920			return ('&');
1921		    else if (S_ISDIR(statb.st_mode))
1922			return ('>');
1923		    else
1924			return ('@');
1925		}
1926		else
1927		    return ('@');
1928	    }
1929#endif
1930#ifdef S_ISSOCK
1931	    if (S_ISSOCK(statb.st_mode))	/* Socket */
1932		return ('=');
1933#endif
1934#ifdef S_ISFIFO
1935	    if (S_ISFIFO(statb.st_mode)) /* Named Pipe */
1936		return ('|');
1937#endif
1938#ifdef S_ISHIDDEN
1939	    if (S_ISHIDDEN(statb.st_mode)) /* Hidden Directory [aix] */
1940		return ('+');
1941#endif
1942#ifdef S_ISCDF
1943	    (void) strcat(ptr, "+");	/* Must append a '+' and re-stat(). */
1944	    if ((stat(ptr, &hpstatb) != -1) && S_ISCDF(hpstatb.st_mode))
1945	    	return ('+');		/* Context Dependent Files [hpux] */
1946#endif
1947#ifdef S_ISNWK
1948	    if (S_ISNWK(statb.st_mode)) /* Network Special [hpux] */
1949		return (':');
1950#endif
1951#ifdef S_ISCHR
1952	    if (S_ISCHR(statb.st_mode))	/* char device */
1953		return ('%');
1954#endif
1955#ifdef S_ISBLK
1956	    if (S_ISBLK(statb.st_mode))	/* block device */
1957		return ('#');
1958#endif
1959#ifdef S_ISDIR
1960	    if (S_ISDIR(statb.st_mode))	/* normal Directory */
1961		return ('/');
1962#endif
1963	    if (statb.st_mode & (S_IXUSR|S_IXGRP|S_IXOTH))
1964		return ('*');
1965	}
1966    }
1967    return (' ');
1968} /* end filetype */
1969
1970
1971/* isadirectory():
1972 *	Return trus if the file is a directory
1973 */
1974static int
1975isadirectory(dir, file)		/* return 1 if dir/file is a directory */
1976    Char   *dir, *file;		/* uses stat rather than lstat to get dest. */
1977{
1978    if (dir) {
1979	Char    path[MAXPATHLEN];
1980	struct stat statb;
1981
1982	(void) Strcpy(path, dir);
1983	catn(path, file, (int) (sizeof(path) / sizeof(Char)));
1984	if (stat(short2str(path), &statb) >= 0) {	/* resolve through
1985							 * symlink */
1986#ifdef S_ISSOCK
1987	    if (S_ISSOCK(statb.st_mode))	/* Socket */
1988		return 0;
1989#endif
1990#ifdef S_ISFIFO
1991	    if (S_ISFIFO(statb.st_mode))	/* Named Pipe */
1992		return 0;
1993#endif
1994	    if (S_ISDIR(statb.st_mode))	/* normal Directory */
1995		return 1;
1996	}
1997    }
1998    return 0;
1999} /* end isadirectory */
2000
2001
2002
2003/* find_rows():
2004 * 	Return how many rows needed to print sorted down columns
2005 */
2006static int
2007find_rows(items, count, no_file_suffix)
2008    Char *items[];
2009    int     count, no_file_suffix;
2010{
2011    register int i, columns, rows;
2012    unsigned int maxwidth = 0;
2013
2014    for (i = 0; i < count; i++)	/* find widest string */
2015	maxwidth = max(maxwidth, (unsigned int) Strlen(items[i]));
2016
2017    maxwidth += no_file_suffix ? 1 : 2;	/* for the file tag and space */
2018    columns = (TermH + 1) / maxwidth;	/* PWP: terminal size change */
2019    if (!columns)
2020	columns = 1;
2021    rows = (count + (columns - 1)) / columns;
2022
2023    return rows;
2024} /* end rows_needed_by_print_by_column */
2025
2026
2027/* print_by_column():
2028 * 	Print sorted down columns or across columns when the first
2029 *	word of $listflags shell variable contains 'x'.
2030 *
2031 */
2032void
2033print_by_column(dir, items, count, no_file_suffix)
2034    register Char *dir, *items[];
2035    int     count, no_file_suffix;
2036{
2037    register int i, r, c, columns, rows;
2038    unsigned int w, maxwidth = 0;
2039    Char *val;
2040    bool across;
2041
2042    lbuffed = 0;		/* turn off line buffering */
2043
2044
2045    across = ((val = varval(STRlistflags)) != STRNULL) &&
2046	     (Strchr(val, 'x') != NULL);
2047
2048    for (i = 0; i < count; i++)	/* find widest string */
2049	maxwidth = max(maxwidth, (unsigned int) Strlen(items[i]));
2050
2051    maxwidth += no_file_suffix ? 1 : 2;	/* for the file tag and space */
2052    columns = TermH / maxwidth;		/* PWP: terminal size change */
2053    if (!columns || !isatty(didfds ? 1 : SHOUT))
2054	columns = 1;
2055    rows = (count + (columns - 1)) / columns;
2056
2057    i = -1;
2058    for (r = 0; r < rows; r++) {
2059	for (c = 0; c < columns; c++) {
2060	    i = across ? (i + 1) : (c * rows + r);
2061
2062	    if (i < count) {
2063		w = (unsigned int) Strlen(items[i]);
2064
2065#ifdef COLOR_LS_F
2066		if (no_file_suffix) {
2067		    /* Print the command name */
2068		    Char f = items[i][w - 1];
2069		    items[i][w - 1] = 0;
2070		    print_with_color(items[i], w - 1, f);
2071		}
2072		else {
2073		    /* Print filename followed by '/' or '*' or ' ' */
2074		    print_with_color(items[i], w, filetype(dir, items[i]));
2075		    w++;
2076		}
2077#else /* ifndef COLOR_LS_F */
2078		if (no_file_suffix) {
2079		    /* Print the command name */
2080		    xprintf("%S", items[i]);
2081		}
2082		else {
2083		    /* Print filename followed by '/' or '*' or ' ' */
2084		    xprintf("%S%c", items[i],
2085			    filetype(dir, items[i]));
2086		    w++;
2087		}
2088#endif /* COLOR_LS_F */
2089
2090		if (c < (columns - 1))	/* Not last column? */
2091		    for (; w < maxwidth; w++)
2092			xputchar(' ');
2093	    }
2094	    else if (across)
2095		break;
2096	}
2097	if (Tty_raw_mode)
2098	    xputchar('\r');
2099	xputchar('\n');
2100    }
2101
2102    lbuffed = 1;		/* turn back on line buffering */
2103    flush();
2104} /* end print_by_column */
2105
2106
2107/* StrQcmp():
2108 *	Compare strings ignoring the quoting chars
2109 */
2110int
2111StrQcmp(str1, str2)
2112    register Char *str1, *str2;
2113{
2114    for (; *str1 && samecase(*str1 & TRIM) == samecase(*str2 & TRIM);
2115	 str1++, str2++)
2116	continue;
2117    /*
2118     * The following case analysis is necessary so that characters which look
2119     * negative collate low against normal characters but high against the
2120     * end-of-string NUL.
2121     */
2122    if (*str1 == '\0' && *str2 == '\0')
2123	return (0);
2124    else if (*str1 == '\0')
2125	return (-1);
2126    else if (*str2 == '\0')
2127	return (1);
2128    else
2129	return ((*str1 & TRIM) - (*str2 & TRIM));
2130} /* end StrQcmp */
2131
2132
2133/* fcompare():
2134 * 	Comparison routine for qsort
2135 */
2136int
2137fcompare(file1, file2)
2138    Char  **file1, **file2;
2139{
2140    return (int) collate(*file1, *file2);
2141} /* end fcompare */
2142
2143
2144/* catn():
2145 *	Concatenate src onto tail of des.
2146 *	Des is a string whose maximum length is count.
2147 *	Always null terminate.
2148 */
2149void
2150catn(des, src, count)
2151    register Char *des, *src;
2152    int count;
2153{
2154    while (--count >= 0 && *des)
2155	des++;
2156    while (--count >= 0)
2157	if ((*des++ = *src++) == 0)
2158	    return;
2159    *des = '\0';
2160} /* end catn */
2161
2162
2163/* copyn():
2164 *	 like strncpy but always leave room for trailing \0
2165 *	 and always null terminate.
2166 */
2167void
2168copyn(des, src, count)
2169    register Char *des, *src;
2170    int count;
2171{
2172    while (--count >= 0)
2173	if ((*des++ = *src++) == 0)
2174	    return;
2175    *des = '\0';
2176} /* end copyn */
2177
2178
2179/* tgetenv():
2180 *	like it's normal string counter-part
2181 *	[apollo uses that in tc.os.c, so it cannot be static]
2182 */
2183Char *
2184tgetenv(str)
2185    Char   *str;
2186{
2187    Char  **var;
2188    int     len, res;
2189
2190    len = (int) Strlen(str);
2191    /* Search the STR_environ for the entry matching str. */
2192    for (var = STR_environ; var != NULL && *var != NULL; var++)
2193	if (Strlen(*var) >= len && (*var)[len] == '=') {
2194	  /* Temporarily terminate the string so we can copy the variable
2195	     name. */
2196	    (*var)[len] = '\0';
2197	    res = StrQcmp(*var, str);
2198	    /* Restore the '=' and return a pointer to the value of the
2199	       environment variable. */
2200	    (*var)[len] = '=';
2201	    if (res == 0)
2202		return (&((*var)[len + 1]));
2203	}
2204    return (NULL);
2205} /* end tgetenv */
2206
2207
2208struct scroll_tab_list *scroll_tab = 0;
2209
2210static void
2211add_scroll_tab(item)
2212    Char *item;
2213{
2214    struct scroll_tab_list *new_scroll;
2215
2216    new_scroll = (struct scroll_tab_list *) xmalloc((size_t)
2217	    sizeof(struct scroll_tab_list));
2218    new_scroll->element = Strsave(item);
2219    new_scroll->next = scroll_tab;
2220    scroll_tab = new_scroll;
2221}
2222
2223static void
2224choose_scroll_tab(exp_name, cnt)
2225    Char **exp_name;
2226    int cnt;
2227{
2228    struct scroll_tab_list *loop;
2229    int tmp = cnt;
2230    Char **ptr;
2231
2232    ptr = (Char **) xmalloc((size_t) sizeof(Char *) * cnt);
2233
2234    for(loop = scroll_tab; loop && (tmp >= 0); loop = loop->next)
2235	ptr[--tmp] = loop->element;
2236
2237    qsort((ptr_t) ptr, (size_t) cnt, sizeof(Char *),
2238	  (int (*) __P((const void *, const void *))) fcompare);
2239
2240    copyn(*exp_name, ptr[curchoice], (int) Strlen(ptr[curchoice]));
2241    xfree((ptr_t) ptr);
2242}
2243
2244static void
2245free_scroll_tab()
2246{
2247    struct scroll_tab_list *loop;
2248
2249    while(scroll_tab) {
2250	loop = scroll_tab;
2251	scroll_tab = scroll_tab->next;
2252	xfree((ptr_t) loop->element);
2253	xfree((ptr_t) loop);
2254    }
2255}
2256