2 * tw.parse.c: Everyone has taken a shot in this futile effort to
3 * lexically analyze a csh line... Well we cannot good
4 * a job as good as sh.lex.c; but we try. Amazing that
5 * it works considering how many hands have touched this code
8 * Copyright (c) 1980, 1991 The Regents of the University of California.
11 * Redistribution and use in source and binary forms, with or without
12 * modification, are permitted provided that the following conditions
14 * 1. Redistributions of source code must retain the above copyright
15 * notice, this list of conditions and the following disclaimer.
16 * 2. Redistributions in binary form must reproduce the above copyright
17 * notice, this list of conditions and the following disclaimer in the
18 * documentation and/or other materials provided with the distribution.
19 * 3. Neither the name of the University nor the names of its contributors
20 * may be used to endorse or promote products derived from this software
21 * without specific prior written permission.
23 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
24 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
25 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
26 * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
27 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
28 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
29 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
30 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
31 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
32 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
44 #endif /* WINNT_NATIVE */
45 #define EVEN(x) (((x) & 1) != 1)
47 #define DOT_NONE 0 /* Don't display dot files */
48 #define DOT_NOT 1 /* Don't display dot or dot-dot */
49 #define DOT_ALL 2 /* Display all dot files */
51 /* TW_NONE, TW_COMMAND, TW_VARIABLE, TW_LOGNAME, */
52 /* TW_FILE, TW_DIRECTORY, TW_VARLIST, TW_USER, */
53 /* TW_COMPLETION, TW_ALIAS, TW_SHELLVAR, TW_ENVVAR, */
54 /* TW_BINDING, TW_WORDLIST, TW_LIMIT, TW_SIGNAL */
55 /* TW_JOB, TW_EXPLAIN, TW_TEXT, TW_GRPNAME */
56 static void (*const tw_start_entry[]) (DIR *, const Char *) = {
57 tw_file_start, tw_cmd_start, tw_var_start, tw_logname_start,
58 tw_file_start, tw_file_start, tw_vl_start, tw_logname_start,
59 tw_complete_start, tw_alias_start, tw_var_start, tw_var_start,
60 tw_bind_start, tw_wl_start, tw_limit_start, tw_sig_start,
61 tw_job_start, tw_file_start, tw_file_start, tw_grpname_start
64 static int (*const tw_next_entry[]) (struct Strbuf *, struct Strbuf *,
66 tw_file_next, tw_cmd_next, tw_var_next, tw_logname_next,
67 tw_file_next, tw_file_next, tw_var_next, tw_logname_next,
68 tw_var_next, tw_var_next, tw_shvar_next, tw_envvar_next,
69 tw_bind_next, tw_wl_next, tw_limit_next, tw_sig_next,
70 tw_job_next, tw_file_next, tw_file_next, tw_grpname_next
73 static void (*const tw_end_entry[]) (void) = {
74 tw_dir_end, tw_dir_end, tw_dir_end, tw_logname_end,
75 tw_dir_end, tw_dir_end, tw_dir_end, tw_logname_end,
76 tw_dir_end, tw_dir_end, tw_dir_end, tw_dir_end,
77 tw_dir_end, tw_dir_end, tw_dir_end, tw_dir_end,
78 tw_dir_end, tw_dir_end, tw_dir_end, tw_grpname_end
83 /* Set to TRUE if recexact is set and an exact match is found
84 * along with other, longer, matches.
89 int match_unique_match = FALSE;
90 int non_unique_match = FALSE;
91 static int SearchNoDirErr = 0; /* t_search returns -2 if dir is unreadable */
93 /* state so if a completion is interrupted, the input line doesn't get
95 int InsideCompletion = 0;
97 /* do the expand or list on the command line -- SHOULD BE REPLACED */
99 static void extract_dir_and_name (const Char *, struct Strbuf *,
101 static int insert_meta (const Char *, const Char *,
103 static int tilde (struct Strbuf *, Char *);
104 static int expand_dir (const Char *, struct Strbuf *, DIR **,
106 static int nostat (const Char *);
107 static int t_glob (Char ***, int);
108 static int c_glob (Char ***);
109 static int is_prefix (Char *, Char *);
110 static int is_prefixmatch (Char *, Char *, int);
111 static int is_suffix (Char *, Char *);
112 static int recognize (struct Strbuf *, const Char *, size_t,
114 static int ignored (Char *);
115 static int isadirectory (const Char *, const Char *);
116 static int tw_collect_items (COMMAND, int, struct Strbuf *,
117 struct Strbuf *, Char *, const Char *,
119 static int tw_collect (COMMAND, int, struct Strbuf *,
120 struct Strbuf *, Char *, Char *, int,
122 static Char tw_suffix (int, struct Strbuf *,const Char *,
124 static void tw_fixword (int, struct Strbuf *, Char *, Char *);
125 static void tw_list_items (int, int, int);
126 static void add_scroll_tab (Char *);
127 static void choose_scroll_tab (struct Strbuf *, int);
128 static void free_scroll_tab (void);
129 static int find_rows (Char *[], int, int);
133 * If we find a set command, then we break a=b to a= and word becomes
134 * b else, we don't break a=b. [don't use that; splits words badly and
135 * messes up tw_complete()]
137 #define isaset(c, w) ((w)[-1] == '=' && \
138 ((c)[0] == 's' && (c)[1] == 'e' && (c)[2] == 't' && \
139 ((c[3] == ' ' || (c)[3] == '\t'))))
142 /* TRUE if character must be quoted */
143 #define tricky(w) (cmap(w, _META | _DOL | _QF | _QB | _ESC | _GLOB) && w != '#')
144 /* TRUE if double quotes don't protect character */
145 #define tricky_dq(w) (cmap(w, _DOL | _QB))
149 * > 1: No. of items found
150 * = 1: Exactly one match / spelling corrected
151 * = 0: No match / spelling was correct
152 * < 0: Error (incl spelling correction impossible)
155 tenematch(Char *inputline, int num_read, COMMAND command)
157 struct Strbuf qline = Strbuf_INIT;
158 Char qu = 0, *pat = STRNULL;
159 size_t wp, word, wordp, cmd_start, oword = 0, ocmd_start = 0;
162 Char *oword_start = NULL;
164 int looking; /* what we are looking for */
165 int search_ret; /* what search returned for debugging */
168 str_end = &inputline[num_read];
169 cleanup_push(&qline, Strbuf_cleanup);
171 word_start = inputline;
172 word = cmd_start = 0;
173 for (cp = inputline; cp < str_end; cp++) {
174 if (!cmap(qu, _ESC)) {
175 if (cmap(*cp, _QF|_ESC)) {
176 if (qu == 0 || qu == *cp) {
181 if (qu != '\'' && cmap(*cp, _QB)) {
182 if ((backq ^= 1) != 0) {
183 ocmd_start = cmd_start;
184 oword_start = word_start;
187 word = cmd_start = qline.len + 1;
190 cmd_start = ocmd_start;
191 word_start = oword_start;
194 Strbuf_append1(&qline, *cp);
199 cmd_start = qline.len + 1;
201 /* Don't quote '/' to make the recognize stuff work easily */
202 /* Don't quote '$' in double quotes */
204 if (cmap(*cp, _ESC) && cp < str_end - 1 && cp[1] == HIST &&
206 Strbuf_append1(&qline, *++cp | QUOTE);
207 else if (qu && (tricky(*cp) || *cp == '~') &&
208 !(qu == '\"' && tricky_dq(*cp)))
209 Strbuf_append1(&qline, *cp | QUOTE);
211 Strbuf_append1(&qline, *cp);
212 if (ismetahash(qline.s[qline.len - 1])
213 /* || isaset(qline.s + cmd_start, qline.s + qline.len) */)
214 word = qline.len, word_start = cp + 1;
218 Strbuf_terminate(&qline);
222 * SPECIAL HARDCODED COMPLETIONS:
223 * first word of command -> TW_COMMAND
224 * everything else -> TW_ZERO
227 looking = starting_a_command(qline.s + word - 1, qline.s) ?
228 TW_COMMAND : TW_ZERO;
236 xprintf(CGETS(30, 1, "starting_a_command %d\n"), looking);
237 xprintf("\ncmd_start:%" TCSH_S ":\n", qline.s + cmd_start);
238 xprintf("qline:%" TCSH_S ":\n", qline.s);
240 for (p = qline.s; *p; p++)
241 xprintf("%c", *p & QUOTE ? '-' : ' ');
243 xprintf("word:%" TCSH_S ":\n", qline.s + word);
245 for (p = qline.s + word; *p; p++)
246 xprintf("%c", *p & QUOTE ? '-' : ' ');
251 if ((looking == TW_COMMAND || looking == TW_ZERO) &&
252 (command == RECOGNIZE || command == LIST || command == SPELL ||
253 command == RECOGNIZE_SCROLL)) {
257 xprintf(CGETS(30, 2, "complete %d "), looking);
260 looking = tw_complete(qline.s + cmd_start, &p, &pat, looking, &suf);
263 xprintf(CGETS(30, 3, "complete %d %" TCSH_S "\n"), looking, pat);
269 Char *items[2], **ptr;
273 case RECOGNIZE_SCROLL:
274 case RECOGNIZE_ALL: {
275 struct Strbuf wordbuf = Strbuf_INIT;
278 if (adrof(STRautocorrect)) {
279 if ((slshp = Strrchr(qline.s + wordp, '/')) != NULL &&
282 for (bptr = qline.s + wordp; bptr < slshp; bptr++) {
284 * do not try to correct spelling of words containing
285 * globbing characters
296 Strbuf_append(&wordbuf, qline.s + wordp);
297 Strbuf_terminate(&wordbuf);
298 cleanup_push(&wordbuf, Strbuf_cleanup);
299 search_ret = t_search(&wordbuf, command, looking, 1, pat, suf);
301 Strbuf_append(&qline, wordbuf.s);
302 Strbuf_terminate(&qline);
303 cleanup_until(&wordbuf);
306 if (search_ret == -2) {
309 rword = Strsave(slshp);
310 cleanup_push(rword, xfree);
311 if (slshp != STRNULL)
313 wordbuf = Strbuf_init;
314 Strbuf_append(&wordbuf, qline.s + wordp);
315 Strbuf_terminate(&wordbuf);
316 cleanup_push(&wordbuf, Strbuf_cleanup);
317 search_ret = spell_me(&wordbuf, looking, pat, suf);
318 if (search_ret == 1) {
319 Strbuf_append(&wordbuf, rword);
320 Strbuf_terminate(&wordbuf);
321 wp = wordp + wordbuf.len;
322 search_ret = t_search(&wordbuf, command, looking, 1, pat, suf);
325 Strbuf_append(&qline, wordbuf.s);
326 Strbuf_terminate(&qline);
327 cleanup_until(rword);
329 if (qline.s[wp] != '\0' &&
330 insert_meta(word_start, str_end, qline.s + word, !qu) < 0)
331 goto err; /* error inserting */
336 struct Strbuf wordbuf = Strbuf_INIT;
338 for (bptr = word_start; bptr < str_end; bptr++) {
340 * do not try to correct spelling of words containing globbing
348 Strbuf_append(&wordbuf, qline.s + wordp);
349 Strbuf_terminate(&wordbuf);
350 cleanup_push(&wordbuf, Strbuf_cleanup);
353 * Don't try to spell things that we know they are correct.
354 * Trying to spell can hang when we have NFS mounted hung
357 if ((looking == TW_COMMAND) && Strchr(wordbuf.s, '/') != NULL) {
358 if (executable(NULL, wordbuf.s, 0)) {
359 cleanup_until(&wordbuf);
365 search_ret = spell_me(&wordbuf, looking, pat, suf);
367 Strbuf_append(&qline, wordbuf.s);
368 Strbuf_terminate(&qline);
369 cleanup_until(&wordbuf);
370 if (search_ret == 1) {
371 if (insert_meta(word_start, str_end, qline.s + word, !qu) < 0)
372 goto err; /* error inserting */
378 do_help(qline.s + cmd_start);
384 items[0] = Strsave(qline.s + wordp);
386 cleanup_push(items[0], xfree);
388 count = (looking == TW_COMMAND && Strchr(qline.s + wordp, '/') == 0) ?
390 t_glob(&ptr, looking == TW_COMMAND);
391 cleanup_until(items[0]);
393 cleanup_push(ptr, blk_cleanup);
396 print_by_column(STRNULL, ptr, count, 0);
398 DeleteBack(str_end - word_start);/* get rid of old word */
399 for (i = 0; i < count; i++)
400 if (ptr[i] && *ptr[i]) {
401 (void) quote(ptr[i]);
402 if (insert_meta(0, 0, ptr[i], 0) < 0 ||
403 InsertStr(STRspace) < 0) {
406 goto err; /* error inserting */
417 bptr = dollar(qline.s + word);
419 if (insert_meta(word_start, str_end, bptr, !qu) < 0) {
421 goto err; /* error inserting */
431 if ((bptr = dnormalize(qline.s + wordp, symlinks == SYM_IGNORE ||
432 symlinks == SYM_EXPAND)) != NULL) {
433 if (insert_meta(word_start, str_end, bptr, !qu) < 0) {
435 goto err; /* error inserting */
444 case COMMAND_NORMALIZE: {
448 found = cmd_expand(qline.s + wordp, &p);
455 if (insert_meta(word_start, str_end, p, !qu) < 0) {
457 goto err; /* error inserting */
466 struct Strbuf wordbuf = Strbuf_INIT;
468 Strbuf_append(&wordbuf, qline.s + wordp);
469 Strbuf_terminate(&wordbuf);
470 cleanup_push(&wordbuf, Strbuf_cleanup);
471 search_ret = t_search(&wordbuf, LIST, looking, 1, pat, suf);
473 Strbuf_append(&qline, wordbuf.s);
474 Strbuf_terminate(&qline);
475 cleanup_until(&wordbuf);
480 xprintf(CGETS(30, 4, "%s: Internal match error.\n"), progname);
484 cleanup_until(&qline);
488 cleanup_until(&qline);
490 } /* end tenematch */
494 * Return a list of files that match the pattern
497 t_glob(Char ***v, int cmd)
508 getexit(osetexit); /* make sure to come back here */
509 omark = cleanup_push_mark();
511 *v = globall(*v, gflag);
512 cleanup_pop_mark(omark);
529 for (i = 0, fwd = 0; av[i] != NULL; i++)
530 if (!executable(NULL, av[i], 0)) {
548 * Return a list of commands that match the pattern
553 struct blk_buf av = BLK_BUF_INIT;
554 struct Strbuf cmd = Strbuf_INIT, dir = Strbuf_INIT;
561 cleanup_push(&av, bb_cleanup);
562 cleanup_push(&cmd, Strbuf_cleanup);
563 cleanup_push(&dir, Strbuf_cleanup);
565 tw_cmd_start(NULL, NULL);
566 while (cmd.len = 0, tw_cmd_next(&cmd, &dir, &flag) != 0) {
567 Strbuf_terminate(&cmd);
568 if (Gmatch(cmd.s, pat))
569 bb_append(&av, Strsave(cmd.s));
581 * change the word before the cursor.
582 * cp must point to the start of the unquoted word.
583 * cpend to the end of it.
584 * word is the text that has to be substituted.
586 * try to keep all the quote characters of the user's input.
587 * change quote type only if necessary.
590 insert_meta(const Char *cp, const Char *cpend, const Char *word,
593 struct Strbuf buffer = Strbuf_INIT;
596 int in_sync = (cp != NULL);
598 int ndel = (int) (cp ? cpend - cp : 0);
602 for (wptr = word;;) {
605 if (in_sync && !cmap(qu, _ESC) && cmap(*cp, _QF|_ESC))
606 if (qu == 0 || qu == *cp) {
608 Strbuf_append1(&buffer, *cp++);
616 #if INVALID_BYTE != 0
617 /* add checking INVALID_BYTE for FIX UTF32 */
618 if ((w & INVALID_BYTE) != INVALID_BYTE) /* w < INVALID_BYTE */
622 if (cmap(w, _ESC | _QF))
623 wq = QUOTE; /* quotes are always quoted */
625 if (!wq && qu && tricky(w) && !(qu == '\"' && tricky_dq(w))) {
626 /* We have to unquote the character */
629 buffer.s[buffer.len - 1] = w;
631 Strbuf_append1(&buffer, qu);
632 Strbuf_append1(&buffer, w);
636 Strbuf_append1(&buffer, qu);
638 } else if (qu && w == qu) {
640 if (buffer.len != 0 && buffer.s[buffer.len - 1] == qu) {
641 /* User misunderstanding :) */
642 buffer.s[buffer.len - 1] = '\\';
643 Strbuf_append1(&buffer, w);
646 Strbuf_append1(&buffer, qu);
647 Strbuf_append1(&buffer, '\\');
648 Strbuf_append1(&buffer, w);
649 Strbuf_append1(&buffer, qu);
652 else if (wq && qu == '\"' && tricky_dq(w)) {
654 Strbuf_append1(&buffer, qu);
655 Strbuf_append1(&buffer, '\\');
656 Strbuf_append1(&buffer, w);
657 Strbuf_append1(&buffer, qu);
659 ((!qu && (tricky(w) || (w == HISTSUB && HISTSUB != '\0'
660 && buffer.len == 0))) ||
661 (!cmap(qu, _ESC) && w == HIST && HIST != '\0'))) {
663 Strbuf_append1(&buffer, '\\');
664 Strbuf_append1(&buffer, w);
666 if (in_sync && *cp++ != w)
668 Strbuf_append1(&buffer, w);
674 if (closequotes && qu && !cmap(qu, _ESC))
675 Strbuf_append1(&buffer, w);
676 bptr = Strbuf_finish(&buffer);
679 res = InsertStr(bptr);
682 } /* end insert_meta */
687 * return true if check matches initial chars in template
688 * This differs from PWB imatch in that if check is null
689 * it matches anything
692 is_prefix(Char *check, Char *template)
694 for (; *check; check++, template++)
695 if ((*check & TRIM) != (*template & TRIM))
698 } /* end is_prefix */
702 * return true if check matches initial chars in template
703 * This differs from PWB imatch in that if check is null
704 * it matches anything
705 * and matches on shortening of commands
708 is_prefixmatch(Char *check, Char *template, int enhanced)
710 Char MCH1, MCH2, LCH1, LCH2;
712 for (; *check; check++, template++) {
713 if ((*check & TRIM) != (*template & TRIM)) {
714 MCH1 = (*check & TRIM);
715 MCH2 = (*template & TRIM);
716 LCH1 = Isupper(MCH1) ? Tolower(MCH1) :
717 enhanced == 2 && MCH1 == '_' ? '-' : MCH1;
718 LCH2 = Isupper(MCH2) ? Tolower(MCH2) :
719 enhanced == 2 && MCH2 == '_' ? '-' : MCH2;
720 if (MCH1 != MCH2 && MCH1 != LCH2 &&
721 (LCH1 != MCH2 || enhanced == 2)) {
722 if (enhanced && ((*check & TRIM) == '-' ||
723 (*check & TRIM) == '.' ||
724 (*check & TRIM) == '_')) {
725 MCH1 = MCH2 = (*check & TRIM);
726 if (MCH1 == '_' && enhanced != 2) {
728 } else if (MCH1 == '-') {
731 for (; *template && (*template & TRIM) != MCH1 &&
732 (*template & TRIM) != MCH2; template++)
744 } /* end is_prefixmatch */
748 * Return true if the chars in template appear at the
749 * end of check, I.e., are it's suffix.
752 is_suffix(Char *check, Char *template)
756 t = Strend(template);
761 if (c == check || (*--t & TRIM) != (*--c & TRIM))
764 } /* end is_suffix */
768 * Return true if this is an ignored item
776 if ((vp = adrof(STRfignore)) == NULL || (cp = vp->vec) == NULL)
778 for (; *cp != NULL; cp++)
779 if (is_suffix(item, *cp))
786 /* starting_a_command():
787 * return true if the command starting at wordstart is a command
790 starting_a_command(Char *wordstart, Char *inputline)
792 Char *ptr, *ncmdstart;
795 cmdstart[] = {'`', ';', '&', '(', '|', '\0'},
796 cmdalive[] = {' ', '\t', '\'', '"', '<', '>', '\0'};
799 * Find if the number of backquotes is odd or even.
801 for (ptr = wordstart, count = 0;
803 count += (*ptr-- == '`'))
806 * if the number of backquotes is even don't include the backquote char in
807 * the list of command starting delimiters [if it is zero, then it does not
810 ncmdstart = cmdstart + EVEN(count);
813 * look for the characters previous to this word if we find a command
814 * starting delimiter we break. if we find whitespace and another previous
815 * word then we are not a command
817 * count is our state machine: 0 looking for anything 1 found white-space
820 for (count = 0; wordstart >= inputline; wordstart--) {
821 if (*wordstart == '\0')
823 if (Strchr(ncmdstart, *wordstart)) {
824 for (ptr = wordstart, bsl = 0; *(--ptr) == '\\'; bsl++);
834 if ((ptr = Strchr(cmdalive, *wordstart)) != NULL)
836 if (count == 1 && !ptr)
840 if (wordstart > inputline)
841 switch (*wordstart) {
842 case '&': /* Look for >& */
843 while (wordstart > inputline &&
844 (*--wordstart == ' ' || *wordstart == '\t'))
846 if (*wordstart == '>')
849 case '(': /* check for foreach, if etc. */
850 while (wordstart > inputline &&
851 (*--wordstart == ' ' || *wordstart == '\t'))
853 if (!iscmdmeta(*wordstart) &&
854 (*wordstart != ' ' && *wordstart != '\t'))
861 } /* end starting_a_command */
865 * Object: extend what user typed up to an ambiguity.
867 * On first match, copy full item (assume it'll be the only match)
868 * On subsequent matches, shorten exp_name to the first
869 * character mismatch between exp_name and item.
870 * If we shorten it back to the prefix length, stop searching.
873 recognize(struct Strbuf *exp_name, const Char *item, size_t name_length,
874 int numitems, int enhanced, int igncase)
876 Char MCH1, MCH2, LCH1, LCH2;
881 if (numitems == 1) { /* 1st match */
883 Strbuf_append(exp_name, item);
884 Strbuf_terminate(exp_name);
887 if (!enhanced && !igncase) {
888 for (x = exp_name->s, ent = item; *x && (*x & TRIM) == (*ent & TRIM);
892 for (x = exp_name->s, ent = item; *x; x++, ent++) {
895 LCH1 = Isupper(MCH1) ? Tolower(MCH1) : MCH1;
896 LCH2 = Isupper(MCH2) ? Tolower(MCH2) : MCH2;
898 if (LCH1 == MCH2 || (MCH1 == '_' && MCH2 == '-'))
900 else if (LCH1 != LCH2)
906 *x = '\0'; /* Shorten at 1st char diff */
907 exp_name->len = x - exp_name->s;
908 if (!(match_unique_match || is_set(STRrecexact) || (enhanced && *ent)) &&
909 len == name_length) /* Ambiguous to prefix? */
910 return (-1); /* So stop now and save time */
912 } /* end recognize */
915 /* tw_collect_items():
916 * Collect items that match target.
918 * Returns the spelling distance of the closest match.
920 * Returns the number of items found.
921 * If none found, but some ignored items were found,
922 * It returns the -number of ignored items.
925 tw_collect_items(COMMAND command, int looking, struct Strbuf *exp_dir,
926 struct Strbuf *exp_name, Char *target, const Char *pat,
929 int done = FALSE; /* Search is done */
930 int showdots; /* Style to show dot files */
931 int nignored = 0; /* Number of fignored items */
932 int numitems = 0; /* Number of matched items */
933 size_t name_length = Strlen(target); /* Length of prefix (file name) */
934 int exec_check = flags & TW_EXEC_CHK;/* need to check executability */
935 int dir_check = flags & TW_DIR_CHK; /* Need to check for directories */
936 int text_check = flags & TW_TEXT_CHK;/* Need to check for non-directories */
937 int dir_ok = flags & TW_DIR_OK; /* Ignore directories? */
938 int gpat = flags & TW_PAT_OK; /* Match against a pattern */
939 int ignoring = flags & TW_IGN_OK; /* Use fignore? */
940 int d = 4, nd; /* Spelling distance */
944 struct Strbuf buf = Strbuf_INIT, item = Strbuf_INIT;
953 if ((ptr = varval(STRlistflags)) != STRNULL)
966 if (looking == TW_COMMAND
967 && (vp = adrof(STRautorehash)) != NULL && vp->vec != NULL)
968 for (cp = vp->vec; *cp; cp++)
969 if (Strcmp(*cp, STRalways) == 0
970 || (Strcmp(*cp, STRcorrect) == 0 && command == SPELL)
971 || (Strcmp(*cp, STRcomplete) == 0 && command != SPELL)) {
973 tw_cmd_start(NULL, NULL);
977 cleanup_push(&item, Strbuf_cleanup);
978 cleanup_push(&buf, Strbuf_cleanup);
981 tw_next_entry[looking](&item, exp_dir, &flags) != 0)) {
982 Strbuf_terminate(&item);
984 xprintf("item = %" TCSH_S "\n", item.s);
991 * Don't match . files on null prefix match
993 if (showdots == DOT_NOT && (ISDOT(item.s) || ISDOTDOT(item.s)))
995 if (name_length == 0 && item.s[0] == '.' && showdots == DOT_NONE)
1000 #if defined(_UWIN) || defined(__CYGWIN__)
1002 * Turn foo.{exe,com,bat,cmd} into foo since UWIN's readdir returns
1003 * the file with the .exe, .com, .bat, .cmd extension
1005 * Same for Cygwin, but only for .exe and .com extension.
1009 static const char *rext[] = { ".exe", ".com" };
1011 static const char *rext[] = { ".exe", ".bat", ".com", ".cmd" };
1013 size_t exti = Strlen(item.s);
1016 char *ext = short2str(&item.s[exti -= 4]);
1019 for (i = 0; i < sizeof(rext) / sizeof(rext[0]); i++)
1020 if (strcasecmp(ext, rext[i]) == 0) {
1022 Strbuf_terminate(&item);
1027 #endif /* _UWIN || __CYGWIN__ */
1028 exec_check = flags & TW_EXEC_CHK;
1029 dir_ok = flags & TW_DIR_OK;
1043 case SPELL: /* correct the spelling of the last bit */
1044 if (name_length == 0) {/* zero-length word can't be misspelled */
1045 exp_name->len = 0; /* (not trying is important for ~) */
1046 Strbuf_terminate(exp_name);
1051 if (gpat && !Gmatch(item.s, pat))
1054 * Swapped the order of the spdist() arguments as suggested
1055 * by eeide@asylum.cs.utah.edu (Eric Eide)
1057 nd = spdist(target, item.s); /* test the item against original */
1058 if (nd <= d && nd != 4) {
1059 if (!(exec_check && !executable(exp_dir->s, item.s, dir_ok))) {
1061 Strbuf_append(exp_name, item.s);
1062 Strbuf_terminate(exp_name);
1064 if (d == 0) /* if found it exactly */
1069 if (spdir(exp_name, exp_dir->s, item.s, target)) {
1071 !executable(exp_dir->s, exp_name->s, dir_ok))
1075 * We don't want to stop immediately, because
1076 * we might find an exact/better match later.
1089 case RECOGNIZE_SCROLL:
1091 if ((vp = adrof(STRcomplete)) != NULL && vp->vec != NULL)
1092 for (cp = vp->vec; *cp; cp++) {
1093 if (Strcmp(*cp, STREnhance) == 0)
1095 else if (Strcmp(*cp, STRigncase) == 0)
1097 else if (Strcmp(*cp, STRenhance) == 0)
1101 if (enhanced || igncase) {
1102 if (!is_prefixmatch(target, item.s, enhanced))
1105 if (!is_prefix(target, item.s))
1109 if (exec_check && !executable(exp_dir->s, item.s, dir_ok))
1112 if (dir_check && !isadirectory(exp_dir->s, item.s))
1115 if (text_check && isadirectory(exp_dir->s, item.s))
1119 * Only pattern match directories if we're checking
1122 if (gpat && !Gmatch(item.s, pat) &&
1123 (dir_check || !isadirectory(exp_dir->s, item.s)))
1127 * Remove duplicates in command listing and completion
1128 * AFEB added code for TW_LOGNAME and TW_USER cases
1130 if (looking == TW_COMMAND || looking == TW_LOGNAME
1131 || looking == TW_USER || command == LIST) {
1133 Strbuf_append(&buf, item.s);
1136 if (!(dir_ok && exec_check))
1138 if (filetype(exp_dir->s, item.s) == '/')
1139 Strbuf_append1(&buf, '/');
1144 Strbuf_append1(&buf, filetype(exp_dir->s, item.s));
1150 Strbuf_terminate(&buf);
1151 if ((looking == TW_COMMAND || looking == TW_USER
1152 || looking == TW_LOGNAME) && tw_item_find(buf.s))
1155 /* maximum length 1 (NULL) + 1 (~ or $) + 1 (filetype) */
1157 if (command == LIST)
1162 if (command == RECOGNIZE || command == RECOGNIZE_ALL ||
1163 command == RECOGNIZE_SCROLL) {
1164 if (ignoring && ignored(item.s)) {
1168 else if (command == RECOGNIZE_SCROLL) {
1169 add_scroll_tab(item.s);
1173 if (match_unique_match || is_set(STRrecexact)) {
1174 if (StrQcmp(target, item.s) == 0) { /* EXACT match */
1176 Strbuf_append(exp_name, item.s);
1177 Strbuf_terminate(exp_name);
1178 numitems = 1; /* fake into expanding */
1179 non_unique_match = TRUE;
1184 if (recognize(exp_name, item.s, name_length, ++numitems,
1186 if (command != RECOGNIZE_SCROLL)
1188 if (enhanced && exp_name->len < name_length) {
1190 Strbuf_append(exp_name, target);
1191 Strbuf_terminate(exp_name);
1200 xprintf("done item = %" TCSH_S "\n", item.s);
1203 cleanup_until(&item);
1205 if (command == RECOGNIZE_SCROLL) {
1206 if ((cnt <= curchoice) || (curchoice == -1)) {
1210 } else if (numitems > 1) {
1212 curchoice = cnt - 1;
1213 choose_scroll_tab(exp_name, cnt);
1219 if (command == SPELL)
1222 if (ignoring && numitems == 0 && nignored > 0)
1231 * Find and return the appropriate suffix character
1235 tw_suffix(int looking, struct Strbuf *word, const Char *exp_dir, Char *exp_name)
1241 (void) strip(exp_name);
1250 * Don't consider array variables or empty variables
1252 if ((vp = adrof(exp_name)) != NULL && vp->vec != NULL) {
1253 if ((ptr = vp->vec[0]) == NULL || *ptr == '\0' ||
1257 else if ((ptr = tgetenv(exp_name)) == NULL || *ptr == '\0')
1260 if ((dol = Strrchr(word->s, '$')) != 0 &&
1261 dol[1] == '{' && Strchr(dol, '}') == NULL)
1264 return isadirectory(exp_dir, ptr) ? '/' : ' ';
1272 return isadirectory(exp_dir, exp_name) ? '/' : ' ';
1292 } /* end tw_suffix */
1296 * Repair a word after a spalling or a recognizwe
1299 tw_fixword(int looking, struct Strbuf *word, Char *dir, Char *exp_name)
1306 Strbuf_append1(word, '~');
1310 if ((ptr = Strrchr(word->s, '$')) != NULL) {
1311 if (ptr[1] == '{') ptr++;
1312 word->len = ptr + 1 - word->s; /* Delete after the dollar */
1321 Strbuf_append(word, dir); /* put back dir part */
1329 (void) quote(exp_name);
1330 Strbuf_append(word, exp_name); /* add extended name */
1331 Strbuf_terminate(word);
1332 } /* end tw_fixword */
1336 * Collect items. Return -1 in case we were interrupted or
1337 * the return value of tw_collect
1338 * This is really a wrapper for tw_collect_items, serving two
1340 * 1. Handles interrupt cleanups.
1341 * 2. Retries if we had no matches, but there were ignored matches
1344 tw_collect(COMMAND command, int looking, struct Strbuf *exp_dir,
1345 struct Strbuf *exp_name, Char *target, Char *pat, int flags,
1352 xprintf("target = %" TCSH_S "\n", target);
1357 volatile size_t omark;
1359 (*tw_start_entry[looking])(dir_fd, pat);
1360 InsideCompletion = 1;
1362 cleanup_pop_mark(omark);
1364 /* interrupted, clean up */
1366 ni = -1; /* flag error */
1369 omark = cleanup_push_mark();
1370 ni = tw_collect_items(command, looking, exp_dir, exp_name, target, pat,
1371 ni >= 0 ? flags : flags & ~TW_IGN_OK);
1372 cleanup_pop_mark(omark);
1377 InsideCompletion = 0;
1378 #if defined(SOLARIS2) && defined(i386) && !defined(__GNUC__)
1379 /* Compiler bug? (from PWP) */
1380 if ((looking == TW_LOGNAME) || (looking == TW_USER))
1382 else if (looking == TW_GRPNAME)
1386 #else /* !(SOLARIS2 && i386 && !__GNUC__) */
1387 (*tw_end_entry[looking])();
1388 #endif /* !(SOLARIS2 && i386 && !__GNUC__) */
1390 } /* end tw_collect */
1394 * List the items that were found
1396 * NOTE instead of looking at numerical vars listmax and listmaxrows
1397 * we can look at numerical var listmax, and have a string value
1398 * listmaxtype (or similar) than can have values 'items' and 'rows'
1399 * (by default interpreted as 'items', for backwards compatibility)
1402 tw_list_items(int looking, int numitems, int list_max)
1411 if ((ptr = varval(STRlistmax)) != STRNULL) {
1413 if (!Isdigit(*ptr)) {
1417 max_items = max_items * 10 + *ptr++ - '0';
1419 if ((max_items > 0) && (numitems > max_items) && list_max)
1420 max_items = numitems;
1425 if (max_items == 0 && (ptr = varval(STRlistmaxrows)) != STRNULL) {
1429 if (!Isdigit(*ptr)) {
1433 max_rows = max_rows * 10 + *ptr++ - '0';
1435 if (max_rows != 0 && looking != TW_JOB)
1436 rows = find_rows(tw_item_get(), numitems, TRUE);
1438 rows = numitems; /* underestimate for lines wider than the termH */
1439 if ((max_rows > 0) && (rows > max_rows) && list_max)
1446 if (max_items || max_rows) {
1452 name = CGETS(30, 5, "items");
1456 name = CGETS(30, 6, "rows");
1460 sname = strsave(name);
1461 cleanup_push(sname, xfree);
1462 xprintf(CGETS(30, 7, "There are %d %s, list them anyway? [n/y] "),
1464 cleanup_until(sname);
1466 /* We should be in Rawmode here, so no \n to catch */
1467 (void) xread(SHIN, &tc, 1);
1468 xprintf("%c\r\n", tc); /* echo the char, do a newline */
1470 * Perhaps we should use the yesexpr from the
1473 if (strchr(CGETS(30, 13, "Yy"), tc) == NULL)
1477 if (looking != TW_SIGNAL)
1478 qsort(tw_item_get(), numitems, sizeof(Char *), fcompare);
1479 if (looking != TW_JOB)
1480 print_by_column(STRNULL, tw_item_get(), numitems, TRUE);
1483 * print one item on every line because jobs can have spaces
1484 * and it is confusing.
1487 Char **w = tw_item_get();
1489 for (i = 0; i < numitems; i++) {
1490 xprintf("%" TCSH_S "", w[i]);
1496 } /* end tw_list_items */
1500 * Perform a RECOGNIZE, LIST or SPELL command on string "word".
1503 * >= 0: SPELL command: "distance" (see spdist())
1504 * other: No. of items found
1505 * < 0: Error (message or beep is output)
1509 t_search(struct Strbuf *word, COMMAND command, int looking, int list_max,
1510 Char *pat, eChar suf)
1512 int numitems, /* Number of items matched */
1513 flags = 0, /* search flags */
1514 gpat = pat[0] != '\0', /* Glob pattern search */
1515 res; /* Return value */
1516 struct Strbuf exp_dir = Strbuf_INIT;/* dir after ~ expansion */
1517 struct Strbuf dir = Strbuf_INIT; /* /x/y/z/ part in /x/y/z/f */
1518 struct Strbuf exp_name = Strbuf_INIT;/* the recognized (extended) */
1519 Char *name, /* f part in /d/d/d/f name */
1520 *target; /* Target to expand/correct/list */
1524 * bugfix by Marty Grossman (grossman@CC5.BBN.COM): directory listing can
1525 * dump core when interrupted
1529 non_unique_match = FALSE; /* See the recexact code below */
1531 extract_dir_and_name(word->s, &dir, &name);
1532 cleanup_push(&dir, Strbuf_cleanup);
1533 cleanup_push(&name, xfree_indirect);
1536 * SPECIAL HARDCODED COMPLETIONS:
1537 * foo$variable -> TW_VARIABLE
1538 * ~user -> TW_LOGNAME
1541 if ((*word->s == '~') && (Strchr(word->s, '/') == NULL)) {
1542 looking = TW_LOGNAME;
1544 gpat = 0; /* Override pattern mechanism */
1546 else if ((target = Strrchr(name, '$')) != 0 &&
1547 (target[1] != '{' || Strchr(target, '}') == NULL) &&
1548 (Strchr(name, '/') == NULL)) {
1550 if (target[0] == '{') target++;
1551 looking = TW_VARIABLE;
1552 gpat = 0; /* Override pattern mechanism */
1558 * Try to figure out what we should be looking for
1560 if (looking & TW_PATH) {
1561 gpat = 0; /* pattern holds the pathname to be used */
1562 Strbuf_append(&exp_dir, pat);
1563 if (exp_dir.len != 0 && exp_dir.s[exp_dir.len - 1] != '/')
1564 Strbuf_append1(&exp_dir, '/');
1565 Strbuf_append(&exp_dir, dir.s);
1567 Strbuf_terminate(&exp_dir);
1568 cleanup_push(&exp_dir, Strbuf_cleanup);
1570 switch (looking & ~TW_PATH) {
1580 if (Strchr(word->s, '/') || (looking & TW_PATH)) {
1582 flags |= TW_EXEC_CHK;
1586 /* PWP: don't even bother when doing ALL of the commands */
1587 if (looking == TW_COMMAND && word->len == 0) {
1597 gpat = 0; /* pattern holds the name of the variable */
1601 if (command == LIST && pat != NULL) {
1602 xprintf("%" TCSH_S "", pat);
1615 * let fignore work only when we are not using a pattern
1617 flags |= (gpat == 0) ? TW_IGN_OK : TW_PAT_OK;
1620 xprintf(CGETS(30, 8, "looking = %d\n"), looking);
1639 if ((res = expand_dir(dir.s, &exp_dir, &dir_fd, command)) != 0)
1644 flags |= TW_DIR_CHK;
1648 * This is supposed to expand the directory stack.
1651 * 2. directories with the same name
1657 * Supposed to do delayed expansion, but it is inconsistent
1658 * from a user-interface point of view, since it does not
1659 * immediately obey addsuffix
1661 if ((res = expand_dir(dir.s, &exp_dir, &dir_fd, command)) != 0)
1663 if (isadirectory(exp_dir.s, name)) {
1664 if (exp_dir.len != 0 || name[0] != '\0') {
1665 Strbuf_append(&dir, name);
1666 if (dir.s[dir.len - 1] != '/')
1667 Strbuf_append1(&dir, '/');
1668 Strbuf_terminate(&dir);
1669 if ((res = expand_dir(dir.s, &exp_dir, &dir_fd, command)) != 0)
1671 if (word->len != 0 && word->s[word->len - 1] != '/') {
1672 Strbuf_append1(word, '/');
1673 Strbuf_terminate(word);
1679 if ((res = expand_dir(dir.s, &exp_dir, &dir_fd, command)) != 0)
1684 flags |= TW_TEXT_CHK;
1687 if ((res = expand_dir(dir.s, &exp_dir, &dir_fd, command)) != 0)
1691 case TW_PATH | TW_TEXT:
1692 case TW_PATH | TW_FILE:
1693 case TW_PATH | TW_DIRECTORY:
1694 case TW_PATH | TW_COMMAND:
1695 if ((dir_fd = opendir(short2str(exp_dir.s))) == NULL) {
1696 if (command == RECOGNIZE)
1698 xprintf("%" TCSH_S ": %s", exp_dir.s, strerror(errno));
1699 if (command != RECOGNIZE)
1705 if (exp_dir.len != 0 && exp_dir.s[exp_dir.len - 1] != '/') {
1706 Strbuf_append1(&exp_dir, '/');
1707 Strbuf_terminate(&exp_dir);
1710 looking &= ~TW_PATH;
1714 flags |= TW_TEXT_CHK;
1721 flags |= TW_DIR_CHK;
1726 target = name = Strsave(word->s); /* so it can match things */
1730 abort(); /* Cannot happen */
1736 user_name = word->s + 1;
1741 user_name = word->s;
1744 * Check if the spelling was already correct
1745 * From: Rob McMahon <cudcv@cu.warwick.ac.uk>
1747 if (command == SPELL && xgetpwnam(short2str(user_name)) != NULL) {
1755 target = name = Strsave(user_name);
1761 target = name = Strsave(word->s); /* so it can match things */
1765 xprintf(CGETS(30, 9,
1766 "\n%s internal error: I don't know what I'm looking for!\n"),
1773 cleanup_push(&exp_name, Strbuf_cleanup);
1774 numitems = tw_collect(command, looking, &exp_dir, &exp_name, target, pat,
1782 case RECOGNIZE_SCROLL:
1786 Strbuf_terminate(&exp_name);
1787 tw_fixword(looking, word, dir.s, exp_name.s);
1789 if (!match_unique_match && is_set(STRaddsuffix) && numitems == 1) {
1791 case 0: /* Automatic suffix */
1792 Strbuf_append1(word,
1793 tw_suffix(looking, word, exp_dir.s, exp_name.s));
1796 case CHAR_ERR: /* No suffix */
1799 default: /* completion specified suffix */
1800 Strbuf_append1(word, suf);
1803 Strbuf_terminate(word);
1808 tw_list_items(looking, numitems, list_max);
1813 Strbuf_terminate(&exp_name);
1814 tw_fixword(looking, word, dir.s, exp_name.s);
1818 xprintf("Bad tw_command\n");
1824 cleanup_until(&dir);
1826 } /* end t_search */
1829 /* extract_dir_and_name():
1830 * parse full path in file into 2 parts: directory and file names
1831 * Should leave final slash (/) at end of dir.
1834 extract_dir_and_name(const Char *path, struct Strbuf *dir, Char **name)
1838 p = Strrchr(path, '/');
1841 p = Strrchr(path, ':');
1842 #endif /* WINNT_NATIVE */
1844 *name = Strsave(path);
1848 Strbuf_appendn(dir, path, p - path);
1850 Strbuf_terminate(dir);
1851 } /* end extract_dir_and_name */
1855 * expand "/$old1/$old2/old3/"
1856 * to "/value_of_old1/value_of_old2/old3/"
1859 dollar(const Char *old)
1861 struct Strbuf buf = Strbuf_INIT;
1865 Strbuf_append1(&buf, *old++);
1867 if (expdollar(&buf, &old, QUOTE) == 0) {
1873 return Strbuf_finish(&buf);
1878 * expand ~person/foo to home_directory_of_person/foo
1879 * or =<stack-entry> to <dir in stack entry>
1882 tilde(struct Strbuf *new, Char *old)
1892 for (o = old; *o && *o != '/'; o++)
1894 name = Strnsave(old, o - old);
1895 home = gethdir(name);
1899 Strbuf_append(new, home);
1901 /* If the home directory expands to "/", we do
1902 * not want to create "//" by appending a slash from o.
1904 if (new->s[0] == '/' && new->len == 1 && *o == '/')
1906 Strbuf_append(new, o);
1911 if ((p = globequal(old)) == NULL)
1914 Strbuf_append(new, p);
1921 Strbuf_append(new, old);
1924 Strbuf_terminate(new);
1928 Strbuf_terminate(new);
1934 * Open the directory given, expanding ~user and $var
1935 * Optionally normalize the path given
1938 expand_dir(const Char *dir, struct Strbuf *edir, DIR **dfd, COMMAND cmd)
1944 cleanup_push(tdir, xfree);
1946 (tilde(edir, tdir) != 0) ||
1947 !(nd = dnormalize(edir->len ? edir->s : STRdot,
1948 symlinks == SYM_IGNORE || symlinks == SYM_EXPAND)) ||
1949 ((*dfd = opendir(short2str(nd))) == NULL)) {
1951 if (cmd == SPELL || SearchNoDirErr) {
1952 cleanup_until(tdir);
1956 * From: Amos Shapira <amoss@cs.huji.ac.il>
1957 * Print a better message when completion fails
1959 xprintf("\n%" TCSH_S " %s\n", edir->len ? edir->s : (tdir ? tdir : dir),
1960 (errno == ENOTDIR ? CGETS(30, 10, "not a directory") :
1961 (errno == ENOENT ? CGETS(30, 11, "not found") :
1962 CGETS(30, 12, "unreadable"))));
1964 cleanup_until(tdir);
1967 cleanup_until(tdir);
1973 * Copy and append a / if there was one
1975 slash = edir->len != 0 && edir->s[edir->len - 1] == '/';
1977 Strbuf_append(edir, nd);
1978 if (slash != 0 && edir->s[edir->len - 1] != '/')
1979 Strbuf_append1(edir, '/');
1980 Strbuf_terminate(edir);
1985 } /* end expand_dir */
1989 * Returns true if the directory should not be stat'd,
1991 * This way, things won't grind to a halt when you complete in /afs
1992 * or very large directories.
1995 nostat(const Char *dir)
2000 if ((vp = adrof(STRnostat)) == NULL || (cp = vp->vec) == NULL)
2002 for (; *cp != NULL; cp++) {
2003 if (Strcmp(*cp, STRstar) == 0)
2005 if (Gmatch(dir, *cp))
2013 * Return a character that signifies a filetype
2014 * symbology from 4.3 ls command.
2017 filetype(const Char *dir, const Char *file)
2023 if (!dir || nostat(dir))
2026 path = Strspl(dir, file);
2027 ptr = short2str(path);
2030 if (lstat(ptr, &statb) == -1)
2034 if (S_ISLNK(statb.st_mode)) { /* Symbolic link */
2035 if (adrof(STRlistlinks)) {
2036 if (stat(ptr, &statb) == -1)
2038 else if (S_ISDIR(statb.st_mode))
2048 if (S_ISSOCK(statb.st_mode)) /* Socket */
2052 if (S_ISFIFO(statb.st_mode)) /* Named Pipe */
2056 if (S_ISHIDDEN(statb.st_mode)) /* Hidden Directory [aix] */
2061 struct stat hpstatb;
2064 p2 = strspl(ptr, "+"); /* Must append a '+' and re-stat(). */
2065 if ((stat(p2, &hpstatb) != -1) && S_ISCDF(hpstatb.st_mode)) {
2067 return '+'; /* Context Dependent Files [hpux] */
2073 if (S_ISNWK(statb.st_mode)) /* Network Special [hpux] */
2077 if (S_ISCHR(statb.st_mode)) /* char device */
2081 if (S_ISBLK(statb.st_mode)) /* block device */
2085 if (S_ISDIR(statb.st_mode)) /* normal Directory */
2088 if (statb.st_mode & (S_IXUSR|S_IXGRP|S_IXOTH))
2092 } /* end filetype */
2096 * Return trus if the file is a directory
2099 isadirectory(const Char *dir, const Char *file)
2100 /* return 1 if dir/file is a directory */
2101 /* uses stat rather than lstat to get dest. */
2108 path = Strspl(dir, file);
2109 cpath = short2str(path);
2111 if (stat(cpath, &statb) >= 0) { /* resolve through symlink */
2113 if (S_ISSOCK(statb.st_mode)) /* Socket */
2117 if (S_ISFIFO(statb.st_mode)) /* Named Pipe */
2120 if (S_ISDIR(statb.st_mode)) /* normal Directory */
2125 } /* end isadirectory */
2130 * Return how many rows needed to print sorted down columns
2133 find_rows(Char *items[], int count, int no_file_suffix)
2135 int i, columns, rows;
2136 unsigned int maxwidth = 0;
2138 for (i = 0; i < count; i++) /* find widest string */
2139 maxwidth = max(maxwidth, (unsigned int) Strlen(items[i]));
2141 maxwidth += no_file_suffix ? 1 : 2; /* for the file tag and space */
2142 columns = (TermH + 1) / maxwidth; /* PWP: terminal size change */
2145 rows = (count + (columns - 1)) / columns;
2148 } /* end rows_needed_by_print_by_column */
2151 /* print_by_column():
2152 * Print sorted down columns or across columns when the first
2153 * word of $listflags shell variable contains 'x'.
2157 print_by_column(Char *dir, Char *items[], int count, int no_file_suffix)
2159 int i, r, c, columns, rows;
2161 unsigned int wx, maxwidth = 0;
2165 lbuffed = 0; /* turn off line buffering */
2168 across = ((val = varval(STRlistflags)) != STRNULL) &&
2169 (Strchr(val, 'x') != NULL);
2171 for (i = 0; i < count; i++) { /* find widest string */
2172 maxwidth = max(maxwidth, (unsigned int) NLSStringWidth(items[i]));
2175 maxwidth += no_file_suffix ? 1 : 2; /* for the file tag and space */
2176 columns = TermH / maxwidth; /* PWP: terminal size change */
2177 if (!columns || !isatty(didfds ? 1 : SHOUT))
2179 rows = (count + (columns - 1)) / columns;
2182 for (r = 0; r < rows; r++) {
2183 for (c = 0; c < columns; c++) {
2184 i = across ? (i + 1) : (c * rows + r);
2188 w = Strlen(items[i]);
2191 if (no_file_suffix) {
2192 /* Print the command name */
2193 Char f = items[i][w - 1];
2194 items[i][w - 1] = 0;
2195 print_with_color(items[i], w - 1, f);
2196 items[i][w - 1] = f;
2199 /* Print filename followed by '/' or '*' or ' ' */
2200 print_with_color(items[i], w, filetype(dir, items[i]));
2203 #else /* ifndef COLOR_LS_F */
2204 if (no_file_suffix) {
2205 /* Print the command name */
2206 xprintf("%" TCSH_S, items[i]);
2209 /* Print filename followed by '/' or '*' or ' ' */
2210 xprintf("%-" TCSH_S "%c", items[i],
2211 filetype(dir, items[i]));
2214 #endif /* COLOR_LS_F */
2216 if (c < (columns - 1)) { /* Not last column? */
2217 w = NLSStringWidth(items[i]) + wx;
2218 for (; w < maxwidth; w++)
2230 lbuffed = 1; /* turn back on line buffering */
2232 } /* end print_by_column */
2236 * Compare strings ignoring the quoting chars
2239 StrQcmp(const Char *str1, const Char *str2)
2241 for (; *str1 && samecase(*str1 & TRIM) == samecase(*str2 & TRIM);
2245 * The following case analysis is necessary so that characters which look
2246 * negative collate low against normal characters but high against the
2247 * end-of-string NUL.
2249 if (*str1 == '\0' && *str2 == '\0')
2251 else if (*str1 == '\0')
2253 else if (*str2 == '\0')
2256 return ((*str1 & TRIM) - (*str2 & TRIM));
2261 * Comparison routine for qsort, (Char **, Char **)
2264 fcompare(const void *xfile1, const void *xfile2)
2266 const Char *const *file1 = xfile1, *const *file2 = xfile2;
2268 return collate(*file1, *file2);
2269 } /* end fcompare */
2273 * Concatenate src onto tail of des.
2274 * Des is a string whose maximum length is count.
2275 * Always null terminate.
2278 catn(Char *des, const Char *src, int count)
2280 while (*des && --count > 0)
2283 if ((*des++ = *src++) == 0)
2290 * like strncpy but always leave room for trailing \0
2291 * and always null terminate.
2294 copyn(Char *des, const Char *src, size_t count)
2296 while (--count != 0)
2297 if ((*des++ = *src++) == 0)
2304 * like it's normal string counter-part
2314 /* Search the STR_environ for the entry matching str. */
2315 for (var = STR_environ; var != NULL && *var != NULL; var++)
2316 if (Strlen(*var) >= len && (*var)[len] == '=') {
2317 /* Temporarily terminate the string so we can copy the variable
2320 res = StrQcmp(*var, str);
2321 /* Restore the '=' and return a pointer to the value of the
2322 environment variable. */
2325 return (&((*var)[len + 1]));
2331 struct scroll_tab_list *scroll_tab = 0;
2334 add_scroll_tab(Char *item)
2336 struct scroll_tab_list *new_scroll;
2338 new_scroll = xmalloc(sizeof(struct scroll_tab_list));
2339 new_scroll->element = Strsave(item);
2340 new_scroll->next = scroll_tab;
2341 scroll_tab = new_scroll;
2345 choose_scroll_tab(struct Strbuf *exp_name, int cnt)
2347 struct scroll_tab_list *loop;
2351 ptr = xmalloc(sizeof(Char *) * cnt);
2352 cleanup_push(ptr, xfree);
2354 for (loop = scroll_tab; loop && (tmp >= 0); loop = loop->next)
2355 ptr[--tmp] = loop->element;
2357 qsort(ptr, cnt, sizeof(Char *), fcompare);
2360 Strbuf_append(exp_name, ptr[curchoice]);
2361 Strbuf_terminate(exp_name);
2366 free_scroll_tab(void)
2368 struct scroll_tab_list *loop;
2370 while (scroll_tab) {
2372 scroll_tab = scroll_tab->next;
2373 xfree(loop->element);