xref: /freebsd/contrib/tcsh/tw.parse.c (revision 3ff369fed2a08f32dda232c10470b949bef9489f)
1 /* $Header: /src/pub/tcsh/tw.parse.c,v 3.90 2001/03/18 19:06:32 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 
42 RCSID("$Id: tw.parse.c,v 3.90 2001/03/18 19:06:32 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	*/
62 static 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 
70 static 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 
78 static 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 
92 int curchoice = -1;
93 
94 int match_unique_match = FALSE;
95 int non_unique_match = FALSE;
96 static 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 */
100 int InsideCompletion = 0;
101 
102 /* do the expand or list on the command line -- SHOULD BE REPLACED */
103 
104 extern Char NeedsRedraw;	/* from ed.h */
105 extern int Tty_raw_mode;
106 extern int TermH;		/* from the editor routines */
107 extern int lbuffed;		/* from sh.print.c */
108 
109 static	void	 extract_dir_and_name	__P((Char *, Char *, Char *));
110 static	int	 insert_meta		__P((Char *, Char *, Char *, bool));
111 static	Char	*tilde			__P((Char *, Char *));
112 #ifndef __MVS__
113 static  int      expand_dir		__P((Char *, Char *, DIR  **, COMMAND));
114 #endif
115 static	bool	 nostat			__P((Char *));
116 static	Char	 filetype		__P((Char *, Char *));
117 static	int	 t_glob			__P((Char ***, int));
118 static	int	 c_glob			__P((Char ***));
119 static	int	 is_prefix		__P((Char *, Char *));
120 static	int	 is_prefixmatch		__P((Char *, Char *, int));
121 static	int	 is_suffix		__P((Char *, Char *));
122 static	int	 recognize		__P((Char *, Char *, int, int, int));
123 static	int	 ignored		__P((Char *));
124 static	int	 isadirectory		__P((Char *, Char *));
125 #ifndef __MVS__
126 static  int      tw_collect_items	__P((COMMAND, int, Char *, Char *,
127 					     Char *, Char *, int));
128 static  int      tw_collect		__P((COMMAND, int, Char *, Char *,
129 					     Char **, Char *, int, DIR *));
130 #endif
131 static	Char 	 tw_suffix		__P((int, Char *, Char *, Char *,
132 					     Char *));
133 static	void 	 tw_fixword		__P((int, Char *, Char *, Char *, int));
134 static	void	 tw_list_items		__P((int, int, int));
135 static 	void	 add_scroll_tab		__P((Char *));
136 static 	void 	 choose_scroll_tab	__P((Char **, int));
137 static	void	 free_scroll_tab	__P((void));
138 static	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  */
165 int
166 tenematch(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  */
427 static int
428 t_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  */
481 static int
482 c_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  */
524 static int
525 insert_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  */
639 static int
640 is_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  */
656 static int
657 is_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  */
699 static int
700 is_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  */
721 static int
722 ignored(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  */
741 int
742 starting_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  */
819 static int
820 recognize(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  */
874 static int
875 tw_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*/
1130 static Char
1131 tw_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  */
1194 static void
1195 tw_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  */
1238 static int
1239 tw_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  */
1313 static void
1314 tw_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 (numitems == 0)
1322 	return;
1323 
1324     if ((ptr = varval(STRlistmax)) != STRNULL) {
1325 	while (*ptr) {
1326 	    if (!Isdigit(*ptr)) {
1327 		max_items = 0;
1328 		break;
1329 	    }
1330 	    max_items = max_items * 10 + *ptr++ - '0';
1331 	}
1332 	if ((max_items > 0) && (numitems > max_items) && list_max)
1333 	    max_items = numitems;
1334 	else
1335 	    max_items = 0;
1336     }
1337 
1338     if (max_items == 0 && (ptr = varval(STRlistmaxrows)) != STRNULL) {
1339 	int rows;
1340 
1341 	while (*ptr) {
1342 	    if (!Isdigit(*ptr)) {
1343 		max_rows = 0;
1344 		break;
1345 	    }
1346 	    max_rows = max_rows * 10 + *ptr++ - '0';
1347 	}
1348 	if (max_rows != 0 && looking != TW_JOB)
1349 	    rows = find_rows(tw_item_get(), numitems, TRUE);
1350 	else
1351 	    rows = numitems; /* underestimate for lines wider than the termH */
1352 	if ((max_rows > 0) && (rows > max_rows) && list_max)
1353 	    max_rows = rows;
1354 	else
1355 	    max_rows = 0;
1356     }
1357 
1358 
1359     if (max_items || max_rows) {
1360 	char    	 tc;
1361 	const char	*name;
1362 	int maxs;
1363 
1364 	if (max_items) {
1365 	    name = CGETS(30, 5, "items");
1366 	    maxs = max_items;
1367 	}
1368 	else {
1369 	    name = CGETS(30, 6, "rows");
1370 	    maxs = max_rows;
1371 	}
1372 
1373 	xprintf(CGETS(30, 7, "There are %d %s, list them anyway? [n/y] "),
1374 		maxs, name);
1375 	flush();
1376 	/* We should be in Rawmode here, so no \n to catch */
1377 	(void) read(SHIN, &tc, 1);
1378 	xprintf("%c\r\n", tc);	/* echo the char, do a newline */
1379 	/*
1380 	 * Perhaps we should use the yesexpr from the
1381 	 * actual locale
1382 	 */
1383 	if (strchr(CGETS(30, 13, "Yy"), tc) == NULL)
1384 	    return;
1385     }
1386 
1387     if (looking != TW_SIGNAL)
1388 	qsort((ptr_t) tw_item_get(), (size_t) numitems, sizeof(Char *),
1389 	      (int (*) __P((const void *, const void *))) fcompare);
1390     if (looking != TW_JOB)
1391 	print_by_column(STRNULL, tw_item_get(), numitems, TRUE);
1392     else {
1393 	/*
1394 	 * print one item on every line because jobs can have spaces
1395 	 * and it is confusing.
1396 	 */
1397 	int i;
1398 	Char **w = tw_item_get();
1399 
1400 	for (i = 0; i < numitems; i++) {
1401 	    xprintf("%S", w[i]);
1402 	    if (Tty_raw_mode)
1403 		xputchar('\r');
1404 	    xputchar('\n');
1405 	}
1406     }
1407 } /* end tw_list_items */
1408 
1409 
1410 /* t_search():
1411  *	Perform a RECOGNIZE, LIST or SPELL command on string "word".
1412  *
1413  *	Return value:
1414  *		>= 0:   SPELL command: "distance" (see spdist())
1415  *		                other: No. of items found
1416  *  		 < 0:   Error (message or beep is output)
1417  */
1418 /*ARGSUSED*/
1419 int
1420 t_search(word, wp, command, max_word_length, looking, list_max, pat, suf)
1421     Char   *word, *wp;		/* original end-of-word */
1422     COMMAND command;
1423     int     max_word_length, looking, list_max;
1424     Char   *pat;
1425     int     suf;
1426 {
1427     int     numitems,			/* Number of items matched */
1428 	    flags = 0,			/* search flags */
1429 	    gpat = pat[0] != '\0',	/* Glob pattern search */
1430 	    nd;				/* Normalized directory return */
1431     Char    exp_dir[FILSIZ + 1],	/* dir after ~ expansion */
1432             dir[FILSIZ + 1],		/* /x/y/z/ part in /x/y/z/f */
1433             exp_name[MAXNAMLEN + 1],	/* the recognized (extended) */
1434             name[MAXNAMLEN + 1],	/* f part in /d/d/d/f name */
1435            *target;			/* Target to expand/correct/list */
1436     DIR    *dir_fd = NULL;
1437 
1438     USE(wp);
1439 
1440     /*
1441      * bugfix by Marty Grossman (grossman@CC5.BBN.COM): directory listing can
1442      * dump core when interrupted
1443      */
1444     tw_item_free();
1445 
1446     non_unique_match = FALSE;	/* See the recexact code below */
1447 
1448     extract_dir_and_name(word, dir, name);
1449 
1450     /*
1451      *  SPECIAL HARDCODED COMPLETIONS:
1452      *    foo$variable                -> TW_VARIABLE
1453      *    ~user                       -> TW_LOGNAME
1454      *
1455      */
1456     if ((*word == '~') && (Strchr(word, '/') == NULL)) {
1457 	looking = TW_LOGNAME;
1458 	target = name;
1459 	gpat = 0;	/* Override pattern mechanism */
1460     }
1461     else if ((target = Strrchr(name, '$')) != 0 &&
1462 	     (Strchr(name, '/') == NULL)) {
1463 	target++;
1464 	looking = TW_VARIABLE;
1465 	gpat = 0;	/* Override pattern mechanism */
1466     }
1467     else
1468 	target = name;
1469 
1470     /*
1471      * Try to figure out what we should be looking for
1472      */
1473     if (looking & TW_PATH) {
1474 	gpat = 0;	/* pattern holds the pathname to be used */
1475 	copyn(exp_dir, pat, MAXNAMLEN);
1476 	if (exp_dir[Strlen(exp_dir) - 1] != '/')
1477 	    catn(exp_dir, STRslash, MAXNAMLEN);
1478 	catn(exp_dir, dir, MAXNAMLEN);
1479     }
1480     else
1481 	exp_dir[0] = '\0';
1482 
1483     switch (looking & ~TW_PATH) {
1484     case TW_NONE:
1485 	return -1;
1486 
1487     case TW_ZERO:
1488 	looking = TW_FILE;
1489 	break;
1490 
1491     case TW_COMMAND:
1492 	if (Strchr(word, '/') || (looking & TW_PATH)) {
1493 	    looking = TW_FILE;
1494 	    flags |= TW_EXEC_CHK;
1495 	    flags |= TW_DIR_OK;
1496 	}
1497 #ifdef notdef
1498 	/* PWP: don't even bother when doing ALL of the commands */
1499 	if (looking == TW_COMMAND && (*word == '\0'))
1500 	    return (-1);
1501 #endif
1502 	break;
1503 
1504 
1505     case TW_VARLIST:
1506     case TW_WORDLIST:
1507 	gpat = 0;	/* pattern holds the name of the variable */
1508 	break;
1509 
1510     case TW_EXPLAIN:
1511 	if (command == LIST && pat != NULL) {
1512 	    xprintf("%S", pat);
1513 	    if (Tty_raw_mode)
1514 		xputchar('\r');
1515 	    xputchar('\n');
1516 	}
1517 	return 2;
1518 
1519     default:
1520 	break;
1521     }
1522 
1523     /*
1524      * let fignore work only when we are not using a pattern
1525      */
1526     flags |= (gpat == 0) ? TW_IGN_OK : TW_PAT_OK;
1527 
1528 #ifdef TDEBUG
1529     xprintf(CGETS(30, 8, "looking = %d\n"), looking);
1530 #endif
1531 
1532     switch (looking) {
1533     case TW_ALIAS:
1534     case TW_SHELLVAR:
1535     case TW_ENVVAR:
1536     case TW_BINDING:
1537     case TW_LIMIT:
1538     case TW_SIGNAL:
1539     case TW_JOB:
1540     case TW_COMPLETION:
1541     case TW_GRPNAME:
1542 	break;
1543 
1544 
1545     case TW_VARIABLE:
1546 	if ((nd = expand_dir(dir, exp_dir, &dir_fd, command)) != 0)
1547 	    return nd;
1548 	break;
1549 
1550     case TW_DIRECTORY:
1551 	flags |= TW_DIR_CHK;
1552 
1553 #ifdef notyet
1554 	/*
1555 	 * This is supposed to expand the directory stack.
1556 	 * Problems:
1557 	 * 1. Slow
1558 	 * 2. directories with the same name
1559 	 */
1560 	flags |= TW_DIR_OK;
1561 #endif
1562 #ifdef notyet
1563 	/*
1564 	 * Supposed to do delayed expansion, but it is inconsistent
1565 	 * from a user-interface point of view, since it does not
1566 	 * immediately obey addsuffix
1567 	 */
1568 	if ((nd = expand_dir(dir, exp_dir, &dir_fd, command)) != 0)
1569 	    return nd;
1570 	if (isadirectory(exp_dir, name)) {
1571 	    if (exp_dir[0] != '\0' || name[0] != '\0') {
1572 		catn(dir, name, MAXNAMLEN);
1573 		if (dir[Strlen(dir) - 1] != '/')
1574 		    catn(dir, STRslash, MAXNAMLEN);
1575 		if ((nd = expand_dir(dir, exp_dir, &dir_fd, command)) != 0)
1576 		    return nd;
1577 		if (word[Strlen(word) - 1] != '/')
1578 		    catn(word, STRslash, MAXNAMLEN);
1579 		name[0] = '\0';
1580 	    }
1581 	}
1582 #endif
1583 	if ((nd = expand_dir(dir, exp_dir, &dir_fd, command)) != 0)
1584 	    return nd;
1585 	break;
1586 
1587     case TW_TEXT:
1588 	flags |= TW_TEXT_CHK;
1589 	/*FALLTHROUGH*/
1590     case TW_FILE:
1591 	if ((nd = expand_dir(dir, exp_dir, &dir_fd, command)) != 0)
1592 	    return nd;
1593 	break;
1594 
1595     case TW_PATH | TW_TEXT:
1596     case TW_PATH | TW_FILE:
1597     case TW_PATH | TW_DIRECTORY:
1598     case TW_PATH | TW_COMMAND:
1599 	if ((dir_fd = opendir(short2str(exp_dir))) == NULL) {
1600  	    if (command == RECOGNIZE)
1601  		xprintf("\n");
1602  	    xprintf("%S: %s", exp_dir, strerror(errno));
1603  	    if (command != RECOGNIZE)
1604  		xprintf("\n");
1605  	    NeedsRedraw = 1;
1606 	    return -1;
1607 	}
1608 	if (exp_dir[Strlen(exp_dir) - 1] != '/')
1609 	    catn(exp_dir, STRslash, MAXNAMLEN);
1610 
1611 	looking &= ~TW_PATH;
1612 
1613 	switch (looking) {
1614 	case TW_TEXT:
1615 	    flags |= TW_TEXT_CHK;
1616 	    break;
1617 
1618 	case TW_FILE:
1619 	    break;
1620 
1621 	case TW_DIRECTORY:
1622 	    flags |= TW_DIR_CHK;
1623 	    break;
1624 
1625 	case TW_COMMAND:
1626 	    copyn(target, word, MAXNAMLEN);	/* so it can match things */
1627 	    break;
1628 
1629 	default:
1630 	    abort();	/* Cannot happen */
1631 	    break;
1632 	}
1633 	break;
1634 
1635     case TW_LOGNAME:
1636 	word++;
1637 	/*FALLTHROUGH*/
1638     case TW_USER:
1639 	/*
1640 	 * Check if the spelling was already correct
1641 	 * From: Rob McMahon <cudcv@cu.warwick.ac.uk>
1642 	 */
1643 	if (command == SPELL && getpwnam(short2str(word)) != NULL) {
1644 #ifdef YPBUGS
1645 	    fix_yp_bugs();
1646 #endif /* YPBUGS */
1647 	    return (0);
1648 	}
1649 	copyn(name, word, MAXNAMLEN);	/* name sans ~ */
1650 	if (looking == TW_LOGNAME)
1651 	    word--;
1652 	break;
1653 
1654     case TW_COMMAND:
1655     case TW_VARLIST:
1656     case TW_WORDLIST:
1657 	copyn(target, word, MAXNAMLEN);	/* so it can match things */
1658 	break;
1659 
1660     default:
1661 	xprintf(CGETS(30, 9,
1662 		"\n%s internal error: I don't know what I'm looking for!\n"),
1663 		progname);
1664 	NeedsRedraw = 1;
1665 	return (-1);
1666     }
1667 
1668     numitems = tw_collect(command, looking, exp_dir, exp_name,
1669 			  &target, pat, flags, dir_fd);
1670     if (numitems == -1)
1671 	return -1;
1672 
1673     switch (command) {
1674     case RECOGNIZE:
1675     case RECOGNIZE_ALL:
1676     case RECOGNIZE_SCROLL:
1677 	if (numitems <= 0)
1678 	    return (numitems);
1679 
1680 	tw_fixword(looking, word, dir, exp_name, max_word_length);
1681 
1682 	if (!match_unique_match && is_set(STRaddsuffix) && numitems == 1) {
1683 	    Char suffix[2];
1684 
1685 	    suffix[1] = '\0';
1686 	    switch (suf) {
1687 	    case 0: 	/* Automatic suffix */
1688 		suffix[0] = tw_suffix(looking, exp_dir, exp_name, target, name);
1689 		break;
1690 
1691 	    case -1:	/* No suffix */
1692 		return numitems;
1693 
1694 	    default:	/* completion specified suffix */
1695 		suffix[0] = (Char) suf;
1696 		break;
1697 	    }
1698 	    catn(word, suffix, max_word_length);
1699 	}
1700 	return numitems;
1701 
1702     case LIST:
1703 	tw_list_items(looking, numitems, list_max);
1704 	tw_item_free();
1705 	return (numitems);
1706 
1707     case SPELL:
1708 	tw_fixword(looking, word, dir, exp_name, max_word_length);
1709 	return (numitems);
1710 
1711     default:
1712 	xprintf("Bad tw_command\n");
1713 	return (0);
1714     }
1715 } /* end t_search */
1716 
1717 
1718 /* extract_dir_and_name():
1719  * 	parse full path in file into 2 parts: directory and file names
1720  * 	Should leave final slash (/) at end of dir.
1721  */
1722 static void
1723 extract_dir_and_name(path, dir, name)
1724     Char   *path, *dir, *name;
1725 {
1726     register Char *p;
1727 
1728     p = Strrchr(path, '/');
1729 #ifdef WINNT_NATIVE
1730     if (p == NULL)
1731 	p = Strrchr(path, ':');
1732 #endif /* WINNT_NATIVE */
1733     if (p == NULL) {
1734 	copyn(name, path, MAXNAMLEN);
1735 	dir[0] = '\0';
1736     }
1737     else {
1738 	p++;
1739 	copyn(name, p, MAXNAMLEN);
1740 	copyn(dir, path, p - path);
1741     }
1742 } /* end extract_dir_and_name */
1743 
1744 
1745 /* dollar():
1746  * 	expand "/$old1/$old2/old3/"
1747  * 	to "/value_of_old1/value_of_old2/old3/"
1748  */
1749 Char *
1750 dollar(new, old)
1751     Char   *new;
1752     const Char *old;
1753 {
1754     Char    *p;
1755     size_t   space;
1756 
1757     for (space = FILSIZ, p = new; *old && space > 0;)
1758 	if (*old != '$') {
1759 	    *p++ = *old++;
1760 	    space--;
1761 	}
1762 	else {
1763 	    if (expdollar(&p, &old, &space, QUOTE) == NULL)
1764 		return NULL;
1765 	}
1766     *p = '\0';
1767     return (new);
1768 } /* end dollar */
1769 
1770 
1771 /* tilde():
1772  * 	expand ~person/foo to home_directory_of_person/foo
1773  *	or =<stack-entry> to <dir in stack entry>
1774  */
1775 static Char *
1776 tilde(new, old)
1777     Char   *new, *old;
1778 {
1779     register Char *o, *p;
1780 
1781     switch (old[0]) {
1782     case '~':
1783 	for (p = new, o = &old[1]; *o && *o != '/'; *p++ = *o++)
1784 	    continue;
1785 	*p = '\0';
1786 	if (gethdir(new)) {
1787 	    new[0] = '\0';
1788 	    return NULL;
1789 	}
1790 #ifdef apollo
1791 	/* Special case: if the home directory expands to "/", we do
1792 	 * not want to create "//" by appending a slash from o.
1793 	 */
1794 	if (new[0] == '/' && new[1] == '\0' && *o == '/')
1795 	    ++o;
1796 #endif /* apollo */
1797 	(void) Strcat(new, o);
1798 	return new;
1799 
1800     case '=':
1801 	if ((p = globequal(new, old)) == NULL) {
1802 	    *new = '\0';
1803 	    return NULL;
1804 	}
1805 	if (p == new)
1806 	    return new;
1807 	/*FALLTHROUGH*/
1808 
1809     default:
1810 	(void) Strcpy(new, old);
1811 	return new;
1812     }
1813 } /* end tilde */
1814 
1815 
1816 /* expand_dir():
1817  *	Open the directory given, expanding ~user and $var
1818  *	Optionally normalize the path given
1819  */
1820 static int
1821 expand_dir(dir, edir, dfd, cmd)
1822     Char   *dir, *edir;
1823     DIR   **dfd;
1824     COMMAND cmd;
1825 {
1826     Char   *nd = NULL;
1827     Char    tdir[MAXPATHLEN + 1];
1828 
1829     if ((dollar(tdir, dir) == 0) ||
1830 	(tilde(edir, tdir) == 0) ||
1831 	!(nd = dnormalize(*edir ? edir : STRdot, symlinks == SYM_IGNORE ||
1832 						 symlinks == SYM_EXPAND)) ||
1833 	((*dfd = opendir(short2str(nd))) == NULL)) {
1834 	xfree((ptr_t) nd);
1835 	if (cmd == SPELL || SearchNoDirErr)
1836 	    return (-2);
1837 	/*
1838 	 * From: Amos Shapira <amoss@cs.huji.ac.il>
1839 	 * Print a better message when completion fails
1840 	 */
1841 	xprintf("\n%S %s\n",
1842 		*edir ? edir :
1843 		(*tdir ? tdir : dir),
1844 		(errno == ENOTDIR ? CGETS(30, 10, "not a directory") :
1845 		(errno == ENOENT ? CGETS(30, 11, "not found") :
1846 		 CGETS(30, 12, "unreadable"))));
1847 	NeedsRedraw = 1;
1848 	return (-1);
1849     }
1850     if (nd) {
1851 	if (*dir != '\0') {
1852 	    Char   *s, *d, *p;
1853 
1854 	    /*
1855 	     * Copy and append a / if there was one
1856 	     */
1857 	    for (p = edir; *p; p++)
1858 		continue;
1859 	    if (*--p == '/') {
1860 		for (p = nd; *p; p++)
1861 		    continue;
1862 		if (*--p != '/')
1863 		    p = NULL;
1864 	    }
1865 	    for (d = edir, s = nd; (*d++ = *s++) != '\0';)
1866 		continue;
1867 	    if (!p) {
1868 		*d-- = '\0';
1869 		*d = '/';
1870 	    }
1871 	}
1872 	xfree((ptr_t) nd);
1873     }
1874     return 0;
1875 } /* end expand_dir */
1876 
1877 
1878 /* nostat():
1879  *	Returns true if the directory should not be stat'd,
1880  *	false otherwise.
1881  *	This way, things won't grind to a halt when you complete in /afs
1882  *	or very large directories.
1883  */
1884 static bool
1885 nostat(dir)
1886      Char *dir;
1887 {
1888     struct varent *vp;
1889     register Char **cp;
1890 
1891     if ((vp = adrof(STRnostat)) == NULL || (cp = vp->vec) == NULL)
1892 	return FALSE;
1893     for (; *cp != NULL; cp++) {
1894 	if (Strcmp(*cp, STRstar) == 0)
1895 	    return TRUE;
1896 	if (Gmatch(dir, *cp))
1897 	    return TRUE;
1898     }
1899     return FALSE;
1900 } /* end nostat */
1901 
1902 
1903 /* filetype():
1904  *	Return a character that signifies a filetype
1905  *	symbology from 4.3 ls command.
1906  */
1907 static  Char
1908 filetype(dir, file)
1909     Char   *dir, *file;
1910 {
1911     if (dir) {
1912 	Char    path[512];
1913 	char   *ptr;
1914 	struct stat statb;
1915 #ifdef S_ISCDF
1916 	/*
1917 	 * From: veals@crchh84d.bnr.ca (Percy Veals)
1918 	 * An extra stat is required for HPUX CDF files.
1919 	 */
1920 	struct stat hpstatb;
1921 #endif /* S_ISCDF */
1922 
1923 	if (nostat(dir)) return(' ');
1924 
1925 	(void) Strcpy(path, dir);
1926 	catn(path, file, (int) (sizeof(path) / sizeof(Char)));
1927 
1928 	if (lstat(ptr = short2str(path), &statb) != -1)
1929 	    /* see above #define of lstat */
1930 	{
1931 #ifdef S_ISLNK
1932 	    if (S_ISLNK(statb.st_mode)) {	/* Symbolic link */
1933 		if (adrof(STRlistlinks)) {
1934 		    if (stat(ptr, &statb) == -1)
1935 			return ('&');
1936 		    else if (S_ISDIR(statb.st_mode))
1937 			return ('>');
1938 		    else
1939 			return ('@');
1940 		}
1941 		else
1942 		    return ('@');
1943 	    }
1944 #endif
1945 #ifdef S_ISSOCK
1946 	    if (S_ISSOCK(statb.st_mode))	/* Socket */
1947 		return ('=');
1948 #endif
1949 #ifdef S_ISFIFO
1950 	    if (S_ISFIFO(statb.st_mode)) /* Named Pipe */
1951 		return ('|');
1952 #endif
1953 #ifdef S_ISHIDDEN
1954 	    if (S_ISHIDDEN(statb.st_mode)) /* Hidden Directory [aix] */
1955 		return ('+');
1956 #endif
1957 #ifdef S_ISCDF
1958 	    (void) strcat(ptr, "+");	/* Must append a '+' and re-stat(). */
1959 	    if ((stat(ptr, &hpstatb) != -1) && S_ISCDF(hpstatb.st_mode))
1960 	    	return ('+');		/* Context Dependent Files [hpux] */
1961 #endif
1962 #ifdef S_ISNWK
1963 	    if (S_ISNWK(statb.st_mode)) /* Network Special [hpux] */
1964 		return (':');
1965 #endif
1966 #ifdef S_ISCHR
1967 	    if (S_ISCHR(statb.st_mode))	/* char device */
1968 		return ('%');
1969 #endif
1970 #ifdef S_ISBLK
1971 	    if (S_ISBLK(statb.st_mode))	/* block device */
1972 		return ('#');
1973 #endif
1974 #ifdef S_ISDIR
1975 	    if (S_ISDIR(statb.st_mode))	/* normal Directory */
1976 		return ('/');
1977 #endif
1978 	    if (statb.st_mode & (S_IXUSR|S_IXGRP|S_IXOTH))
1979 		return ('*');
1980 	}
1981     }
1982     return (' ');
1983 } /* end filetype */
1984 
1985 
1986 /* isadirectory():
1987  *	Return trus if the file is a directory
1988  */
1989 static int
1990 isadirectory(dir, file)		/* return 1 if dir/file is a directory */
1991     Char   *dir, *file;		/* uses stat rather than lstat to get dest. */
1992 {
1993     if (dir) {
1994 	Char    path[MAXPATHLEN];
1995 	struct stat statb;
1996 
1997 	(void) Strcpy(path, dir);
1998 	catn(path, file, (int) (sizeof(path) / sizeof(Char)));
1999 	if (stat(short2str(path), &statb) >= 0) {	/* resolve through
2000 							 * symlink */
2001 #ifdef S_ISSOCK
2002 	    if (S_ISSOCK(statb.st_mode))	/* Socket */
2003 		return 0;
2004 #endif
2005 #ifdef S_ISFIFO
2006 	    if (S_ISFIFO(statb.st_mode))	/* Named Pipe */
2007 		return 0;
2008 #endif
2009 	    if (S_ISDIR(statb.st_mode))	/* normal Directory */
2010 		return 1;
2011 	}
2012     }
2013     return 0;
2014 } /* end isadirectory */
2015 
2016 
2017 
2018 /* find_rows():
2019  * 	Return how many rows needed to print sorted down columns
2020  */
2021 static int
2022 find_rows(items, count, no_file_suffix)
2023     Char *items[];
2024     int     count, no_file_suffix;
2025 {
2026     register int i, columns, rows;
2027     unsigned int maxwidth = 0;
2028 
2029     for (i = 0; i < count; i++)	/* find widest string */
2030 	maxwidth = max(maxwidth, (unsigned int) Strlen(items[i]));
2031 
2032     maxwidth += no_file_suffix ? 1 : 2;	/* for the file tag and space */
2033     columns = (TermH + 1) / maxwidth;	/* PWP: terminal size change */
2034     if (!columns)
2035 	columns = 1;
2036     rows = (count + (columns - 1)) / columns;
2037 
2038     return rows;
2039 } /* end rows_needed_by_print_by_column */
2040 
2041 
2042 /* print_by_column():
2043  * 	Print sorted down columns or across columns when the first
2044  *	word of $listflags shell variable contains 'x'.
2045  *
2046  */
2047 void
2048 print_by_column(dir, items, count, no_file_suffix)
2049     register Char *dir, *items[];
2050     int     count, no_file_suffix;
2051 {
2052     register int i, r, c, columns, rows;
2053     unsigned int w, maxwidth = 0;
2054     Char *val;
2055     bool across;
2056 
2057     lbuffed = 0;		/* turn off line buffering */
2058 
2059 
2060     across = ((val = varval(STRlistflags)) != STRNULL) &&
2061 	     (Strchr(val, 'x') != NULL);
2062 
2063     for (i = 0; i < count; i++)	/* find widest string */
2064 	maxwidth = max(maxwidth, (unsigned int) Strlen(items[i]));
2065 
2066     maxwidth += no_file_suffix ? 1 : 2;	/* for the file tag and space */
2067     columns = TermH / maxwidth;		/* PWP: terminal size change */
2068     if (!columns || !isatty(didfds ? 1 : SHOUT))
2069 	columns = 1;
2070     rows = (count + (columns - 1)) / columns;
2071 
2072     i = -1;
2073     for (r = 0; r < rows; r++) {
2074 	for (c = 0; c < columns; c++) {
2075 	    i = across ? (i + 1) : (c * rows + r);
2076 
2077 	    if (i < count) {
2078 		w = (unsigned int) Strlen(items[i]);
2079 
2080 #ifdef COLOR_LS_F
2081 		if (no_file_suffix) {
2082 		    /* Print the command name */
2083 		    Char f = items[i][w - 1];
2084 		    items[i][w - 1] = 0;
2085 		    print_with_color(items[i], w - 1, f);
2086 		}
2087 		else {
2088 		    /* Print filename followed by '/' or '*' or ' ' */
2089 		    print_with_color(items[i], w, filetype(dir, items[i]));
2090 		    w++;
2091 		}
2092 #else /* ifndef COLOR_LS_F */
2093 		if (no_file_suffix) {
2094 		    /* Print the command name */
2095 		    xprintf("%S", items[i]);
2096 		}
2097 		else {
2098 		    /* Print filename followed by '/' or '*' or ' ' */
2099 		    xprintf("%S%c", items[i],
2100 			    filetype(dir, items[i]));
2101 		    w++;
2102 		}
2103 #endif /* COLOR_LS_F */
2104 
2105 		if (c < (columns - 1))	/* Not last column? */
2106 		    for (; w < maxwidth; w++)
2107 			xputchar(' ');
2108 	    }
2109 	    else if (across)
2110 		break;
2111 	}
2112 	if (Tty_raw_mode)
2113 	    xputchar('\r');
2114 	xputchar('\n');
2115     }
2116 
2117     lbuffed = 1;		/* turn back on line buffering */
2118     flush();
2119 } /* end print_by_column */
2120 
2121 
2122 /* StrQcmp():
2123  *	Compare strings ignoring the quoting chars
2124  */
2125 int
2126 StrQcmp(str1, str2)
2127     register Char *str1, *str2;
2128 {
2129     for (; *str1 && samecase(*str1 & TRIM) == samecase(*str2 & TRIM);
2130 	 str1++, str2++)
2131 	continue;
2132     /*
2133      * The following case analysis is necessary so that characters which look
2134      * negative collate low against normal characters but high against the
2135      * end-of-string NUL.
2136      */
2137     if (*str1 == '\0' && *str2 == '\0')
2138 	return (0);
2139     else if (*str1 == '\0')
2140 	return (-1);
2141     else if (*str2 == '\0')
2142 	return (1);
2143     else
2144 	return ((*str1 & TRIM) - (*str2 & TRIM));
2145 } /* end StrQcmp */
2146 
2147 
2148 /* fcompare():
2149  * 	Comparison routine for qsort
2150  */
2151 int
2152 fcompare(file1, file2)
2153     Char  **file1, **file2;
2154 {
2155     return (int) collate(*file1, *file2);
2156 } /* end fcompare */
2157 
2158 
2159 /* catn():
2160  *	Concatenate src onto tail of des.
2161  *	Des is a string whose maximum length is count.
2162  *	Always null terminate.
2163  */
2164 void
2165 catn(des, src, count)
2166     register Char *des, *src;
2167     int count;
2168 {
2169     while (--count >= 0 && *des)
2170 	des++;
2171     while (--count >= 0)
2172 	if ((*des++ = *src++) == 0)
2173 	    return;
2174     *des = '\0';
2175 } /* end catn */
2176 
2177 
2178 /* copyn():
2179  *	 like strncpy but always leave room for trailing \0
2180  *	 and always null terminate.
2181  */
2182 void
2183 copyn(des, src, count)
2184     register Char *des, *src;
2185     int count;
2186 {
2187     while (--count >= 0)
2188 	if ((*des++ = *src++) == 0)
2189 	    return;
2190     *des = '\0';
2191 } /* end copyn */
2192 
2193 
2194 /* tgetenv():
2195  *	like it's normal string counter-part
2196  *	[apollo uses that in tc.os.c, so it cannot be static]
2197  */
2198 Char *
2199 tgetenv(str)
2200     Char   *str;
2201 {
2202     Char  **var;
2203     int     len, res;
2204 
2205     len = (int) Strlen(str);
2206     /* Search the STR_environ for the entry matching str. */
2207     for (var = STR_environ; var != NULL && *var != NULL; var++)
2208 	if (Strlen(*var) >= len && (*var)[len] == '=') {
2209 	  /* Temporarily terminate the string so we can copy the variable
2210 	     name. */
2211 	    (*var)[len] = '\0';
2212 	    res = StrQcmp(*var, str);
2213 	    /* Restore the '=' and return a pointer to the value of the
2214 	       environment variable. */
2215 	    (*var)[len] = '=';
2216 	    if (res == 0)
2217 		return (&((*var)[len + 1]));
2218 	}
2219     return (NULL);
2220 } /* end tgetenv */
2221 
2222 
2223 struct scroll_tab_list *scroll_tab = 0;
2224 
2225 static void
2226 add_scroll_tab(item)
2227     Char *item;
2228 {
2229     struct scroll_tab_list *new_scroll;
2230 
2231     new_scroll = (struct scroll_tab_list *) xmalloc((size_t)
2232 	    sizeof(struct scroll_tab_list));
2233     new_scroll->element = Strsave(item);
2234     new_scroll->next = scroll_tab;
2235     scroll_tab = new_scroll;
2236 }
2237 
2238 static void
2239 choose_scroll_tab(exp_name, cnt)
2240     Char **exp_name;
2241     int cnt;
2242 {
2243     struct scroll_tab_list *loop;
2244     int tmp = cnt;
2245     Char **ptr;
2246 
2247     ptr = (Char **) xmalloc((size_t) sizeof(Char *) * cnt);
2248 
2249     for(loop = scroll_tab; loop && (tmp >= 0); loop = loop->next)
2250 	ptr[--tmp] = loop->element;
2251 
2252     qsort((ptr_t) ptr, (size_t) cnt, sizeof(Char *),
2253 	  (int (*) __P((const void *, const void *))) fcompare);
2254 
2255     copyn(*exp_name, ptr[curchoice], (int) Strlen(ptr[curchoice]));
2256     xfree((ptr_t) ptr);
2257 }
2258 
2259 static void
2260 free_scroll_tab()
2261 {
2262     struct scroll_tab_list *loop;
2263 
2264     while(scroll_tab) {
2265 	loop = scroll_tab;
2266 	scroll_tab = scroll_tab->next;
2267 	xfree((ptr_t) loop->element);
2268 	xfree((ptr_t) loop);
2269     }
2270 }
2271