1 /* $Header: /src/pub/tcsh/tw.parse.c,v 3.89 2000/11/11 23:03:40 christos Exp $ */
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
9 * Copyright (c) 1980, 1991 The Regents of the University of California.
10 * All rights reserved.
12 * Redistribution and use in source and binary forms, with or without
13 * modification, are permitted provided that the following conditions
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.
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
42 RCSID("$Id: tw.parse.c,v 3.89 2000/11/11 23:03:40 christos Exp $")
50 #endif /* WINNT_NATIVE */
51 #define EVEN(x) (((x) & 1) != 1)
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 */
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
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
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
88 /* Set to TRUE if recexact is set and an exact match is found
89 * along with other, longer, matches.
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 */
98 /* state so if a completion is interrupted, the input line doesn't get
100 int InsideCompletion = 0;
102 /* do the expand or list on the command line -- SHOULD BE REPLACED */
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 */
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 *));
113 static int expand_dir __P((Char *, Char *, DIR **, COMMAND));
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 *));
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 *));
131 static Char tw_suffix __P((int, Char *, Char *, 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));
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()]
146 #define isaset(c, w) ((w)[-1] == '=' && \
147 ((c)[0] == 's' && (c)[1] == 'e' && (c)[2] == 't' && \
148 ((c[3] == ' ' || (c)[3] == '\t'))))
151 #define QLINESIZE (INBUFSIZE + 1)
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))
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)
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 */
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;
179 int looking; /* what we are looking for */
180 int search_ret; /* what search returned for debugging */
183 if (num_read > QLINESIZE - 1)
185 str_end = &inputline[num_read];
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) {
197 if (qu != '\'' && cmap(*cp, _QB)) {
198 if ((backq ^= 1) != 0) {
199 ocmd_start = cmd_start;
200 oword_start = word_start;
203 word = cmd_start = wp + 1;
206 cmd_start = ocmd_start;
207 word_start = oword_start;
217 /* Don't quote '/' to make the recognize stuff work easily */
218 /* Don't quote '$' in double quotes */
220 if (cmap(*cp, _ESC) && cp < str_end - 1 && cp[1] == HIST)
222 else if (qu && (tricky(*cp) || *cp == '~') && !(qu == '\"' && tricky_dq(*cp)))
226 if (ismetahash(*wp) /* || isaset(cmd_start, wp + 1) */)
227 word = wp + 1, word_start = cp + 1;
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.
241 space_left = QLINESIZE - 1;
242 space_left -= word - qline;
244 space_left = QLINESIZE - 1 - (int) (word - qline);
248 * SPECIAL HARDCODED COMPLETIONS:
249 * first word of command -> TW_COMMAND
250 * everything else -> TW_ZERO
253 looking = starting_a_command(word - 1, qline) ?
254 TW_COMMAND : TW_ZERO;
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);
263 for (wp = qline; *wp; wp++)
264 xprintf("%c", *wp & QUOTE ? '-' : ' ');
266 xprintf("word:%S:\n", 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 ? '-' : ' ');
274 if ((looking == TW_COMMAND || looking == TW_ZERO) &&
275 (command == RECOGNIZE || command == LIST || command == SPELL ||
276 command == RECOGNIZE_SCROLL)) {
278 xprintf(CGETS(30, 2, "complete %d "), looking);
280 looking = tw_complete(cmd_start, &wordp, &pat, looking, &suf);
282 xprintf(CGETS(30, 3, "complete %d %S\n"), looking, pat);
287 Char buffer[FILSIZ + 1], *bptr;
289 Char *items[2], **ptr;
293 case RECOGNIZE_SCROLL:
295 if (adrof(STRautocorrect)) {
296 if ((slshp = Strrchr(wordp, '/')) != NULL && slshp[1] != '\0') {
298 for (bptr = wordp; bptr < slshp; bptr++) {
300 * do not try to correct spelling of words containing
301 * globbing characters
312 search_ret = t_search(wordp, wp, command, space_left, looking, 1,
316 if (search_ret == -2) {
317 Char rword[FILSIZ + 1];
319 (void) Strcpy(rword, slshp);
320 if (slshp != STRNULL)
322 search_ret = spell_me(wordp, QLINESIZE - (wordp - qline), looking,
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);
331 if (*wp && insert_meta(word_start, str_end, word, !qu) < 0)
332 return -1; /* error inserting */
336 for (bptr = word_start; bptr < str_end; bptr++) {
338 * do not try to correct spelling of words containing globbing
344 search_ret = spell_me(wordp, QLINESIZE - (wordp - qline), looking,
346 if (search_ret == 1) {
347 if (insert_meta(word_start, str_end, word, !qu) < 0)
348 return -1; /* error inserting */
358 (void) Strncpy(buffer, wordp, FILSIZ + 1);
362 count = (looking == TW_COMMAND && Strchr(wordp, '/') == 0) ?
364 t_glob(&ptr, looking == TW_COMMAND);
367 print_by_column(STRNULL, ptr, count, 0);
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) {
376 return -1; /* error inserting */
385 if (dollar(buffer, word)) {
386 if (insert_meta(word_start, str_end, buffer, !qu) < 0)
387 return -1; /* error inserting */
393 if ((bptr = dnormalize(wordp, symlinks == SYM_IGNORE ||
394 symlinks == SYM_EXPAND)) != NULL) {
395 (void) Strcpy(buffer, bptr);
397 if (insert_meta(word_start, str_end, buffer, !qu) < 0)
398 return -1; /* error inserting */
403 case COMMAND_NORMALIZE:
404 if (!cmd_expand(wordp, buffer))
406 if (insert_meta(word_start, str_end, buffer, !qu) < 0)
407 return -1; /* error inserting */
412 search_ret = t_search(wordp, wp, LIST, space_left, looking, 1,
417 xprintf(CGETS(30, 4, "%s: Internal match error.\n"), progname);
421 } /* end tenematch */
425 * Return a list of files that match the pattern
436 gflag = 0, tglob(*v);
438 getexit(osetexit); /* make sure to come back here */
456 int fwd, i, ac = gargc;
458 for (i = 0, fwd = 0; i < ac; i++)
459 if (!executable(NULL, av[i], 0)) {
479 * Return a list of commands that match the pattern
485 Char *pat = **v, *cmd, **av;
486 Char dir[MAXPATHLEN+1];
494 av = (Char **) xmalloc((size_t) (at * sizeof(Char *)));
497 tw_cmd_start(NULL, NULL);
498 while ((cmd = tw_cmd_next(dir, &flag)) != NULL)
499 if (Gmatch(cmd, pat)) {
502 av = (Char **) xrealloc((ptr_t) av,
503 (size_t) (at * sizeof(Char *)));
505 av[ac++] = Strsave(cmd);
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.
521 * try to keep all the quote characters of the user's input.
522 * change quote type only if necessary.
525 insert_meta(cp, cpend, word, closequotes)
531 Char buffer[2 * FILSIZ + 1], *bptr, *wptr;
532 int in_sync = (cp != NULL);
534 int ndel = (int) (cp ? cpend - cp : 0);
538 #endif /* DSPMBYTE */
540 for (bptr = buffer, wptr = word;;) {
541 if (bptr > buffer + 2 * FILSIZ - 5)
548 #endif /* DSPMBYTE */
549 if (in_sync && !cmap(qu, _ESC) && cmap(*cp, _QF|_ESC))
550 if (qu == 0 || qu == *cp) {
565 #endif /* DSPMBYTE */
566 if (cmap(w, _ESC | _QF))
567 wq = QUOTE; /* quotes are always quoted */
569 if (!wq && qu && tricky(w) && !(qu == '\"' && tricky_dq(w))) {
570 /* We have to unquote the character */
582 } else if (qu && w == qu) {
584 if (bptr > buffer && bptr[-1] == qu) {
585 /* User misunderstanding :) */
596 else if (wq && qu == '\"' && tricky_dq(w)) {
602 } else if (wq && ((!qu && (tricky(w) || (w == HISTSUB && bptr == buffer))) || (!cmap(qu, _ESC) && w == HIST))) {
609 #endif /* DSPMBYTE */
610 if (in_sync && *cp++ != w)
614 if (mbytepos == 1 && Ismbyte1(w))
618 #endif /* DSPMBYTE */
624 if (closequotes && qu && !cmap(qu, _ESC))
629 return InsertStr(buffer);
630 } /* end insert_meta */
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
640 is_prefix(check, template)
641 register Char *check, *template;
643 for (; *check; check++, template++)
644 if ((*check & TRIM) != (*template & TRIM))
647 } /* end is_prefix */
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
657 is_prefixmatch(check, template, igncase)
658 Char *check, *template;
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;
670 if (!igncase && ((*check & TRIM) == '-' ||
671 (*check & TRIM) == '.' ||
672 (*check & TRIM) == '_')) {
673 MCH1 = MCH2 = (*check & TRIM);
676 } else if (MCH1 == '-') {
679 for (;*template && (*template & TRIM) != MCH1 &&
680 (*template & TRIM) != MCH2; template++)
692 } /* end is_prefixmatch */
696 * Return true if the chars in template appear at the
697 * end of check, I.e., are it's suffix.
700 is_suffix(check, template)
701 register Char *check, *template;
703 register Char *t, *c;
705 for (t = template; *t++;)
707 for (c = check; *c++;)
712 if (c == check || (*--t & TRIM) != (*--c & TRIM))
715 } /* end is_suffix */
719 * Return true if this is an ignored item
728 if ((vp = adrof(STRfignore)) == NULL || (cp = vp->vec) == NULL)
730 for (; *cp != NULL; cp++)
731 if (is_suffix(item, *cp))
738 /* starting_a_command():
739 * return true if the command starting at wordstart is a command
742 starting_a_command(wordstart, inputline)
743 register Char *wordstart, *inputline;
745 register Char *ptr, *ncmdstart;
748 cmdstart[] = {'`', ';', '&', '(', '|', '\0'},
749 cmdalive[] = {' ', '\t', '\'', '"', '<', '>', '\0'};
752 * Find if the number of backquotes is odd or even.
754 for (ptr = wordstart, count = 0;
756 count += (*ptr-- == '`'))
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
763 ncmdstart = cmdstart + EVEN(count);
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
770 * count is our state machine: 0 looking for anything 1 found white-space
773 for (count = 0; wordstart >= inputline; wordstart--) {
774 if (*wordstart == '\0')
776 if (Strchr(ncmdstart, *wordstart))
781 if ((ptr = Strchr(cmdalive, *wordstart)) != NULL)
783 if (count == 1 && !ptr)
787 if (wordstart > inputline)
788 switch (*wordstart) {
789 case '&': /* Look for >& */
790 while (wordstart > inputline &&
791 (*--wordstart == ' ' || *wordstart == '\t'))
793 if (*wordstart == '>')
796 case '(': /* check for foreach, if etc. */
797 while (wordstart > inputline &&
798 (*--wordstart == ' ' || *wordstart == '\t'))
800 if (!iscmdmeta(*wordstart) &&
801 (*wordstart != ' ' && *wordstart != '\t'))
808 } /* end starting_a_command */
812 * Object: extend what user typed up to an ambiguity.
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.
820 recognize(exp_name, item, name_length, numitems, enhanced)
821 Char *exp_name, *item;
822 int name_length, numitems, enhanced;
825 register Char *x, *ent;
826 register int len = 0;
830 igncase = (vp = adrof(STRcomplete)) != NULL &&
831 Strcmp(*(vp->vec), STRigncase) == 0;
832 #endif /* WINNT_NATIVE */
834 if (numitems == 1) { /* 1st match */
835 copyn(exp_name, item, MAXNAMLEN);
841 #endif /* WINNT_NATIVE */
843 for (x = exp_name, ent = item; *x && (*x & TRIM) == (*ent & TRIM); x++, ent++)
846 for (x = exp_name, ent = item; *x; x++, ent++) {
849 MCH1 = Isupper(MCH1) ? Tolower(MCH1) : MCH1;
850 MCH2 = Isupper(MCH2) ? Tolower(MCH2) : MCH2;
855 if (*x || !*ent) /* Shorter or exact match */
856 copyn(exp_name, item, MAXNAMLEN);
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 */
862 } /* end recognize */
865 /* tw_collect_items():
866 * Collect items that match target.
868 * Returns the spelling distance of the closest match.
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.
875 tw_collect_items(command, looking, exp_dir, exp_name, target, pat, flags)
878 Char *exp_dir, *exp_name, *target, *pat;
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 */
895 Char buf[MAXPATHLEN+1];
905 if ((ptr = varval(STRlistflags)) != STRNULL)
918 while (!done && (item = (*tw_next_entry[looking])(exp_dir, &flags))) {
920 xprintf("item = %S\n", item);
927 * Don't match . files on null prefix match
929 if (showdots == DOT_NOT && (ISDOT(item) || ISDOTDOT(item)))
931 if (name_length == 0 && item[0] == '.' && showdots == DOT_NONE)
936 exec_check = flags & TW_EXEC_CHK;
937 dir_ok = flags & TW_DIR_OK;
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 ~) */
958 if (gpat && !Gmatch(item, pat))
961 * Swapped the order of the spdist() arguments as suggested
962 * by eeide@asylum.cs.utah.edu (Eric Eide)
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);
969 if (d == 0) /* if found it exactly */
974 if (spdir(exp_name, exp_dir, item, target)) {
975 if (exec_check && !executable(exp_dir, exp_name, dir_ok))
979 * We don't want to stop immediately, because
980 * we might find an exact/better match later.
993 case RECOGNIZE_SCROLL:
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))
1004 if (!is_prefix(target, item))
1008 if (exec_check && !executable(exp_dir, item, dir_ok))
1011 if (dir_check && !isadirectory(exp_dir, item))
1014 if (text_check && isadirectory(exp_dir, item))
1018 * Only pattern match directories if we're checking
1021 if (gpat && !Gmatch(item, pat) &&
1022 (dir_check || !isadirectory(exp_dir, item)))
1026 * Remove duplicates in command listing and completion
1027 * AFEB added code for TW_LOGNAME and TW_USER cases
1029 if (looking == TW_COMMAND || looking == TW_LOGNAME
1030 || looking == TW_USER || command == LIST) {
1031 copyn(buf, item, MAXPATHLEN);
1032 len = (int) Strlen(buf);
1035 if (!(dir_ok && exec_check))
1037 if (filetype(exp_dir, item) == '/') {
1045 buf[len++] = filetype(exp_dir, item);
1052 if ((looking == TW_COMMAND || looking == TW_USER
1053 || looking == TW_LOGNAME) && tw_item_find(buf))
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)
1064 if (command == RECOGNIZE || command == RECOGNIZE_ALL ||
1065 command == RECOGNIZE_SCROLL) {
1066 if (ignoring && ignored(item)) {
1070 else if (command == RECOGNIZE_SCROLL) {
1071 add_scroll_tab(item);
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;
1084 if (recognize(exp_name, item, name_length, ++numitems, enhanced))
1085 if (command != RECOGNIZE_SCROLL)
1087 if (enhanced && (int)Strlen(exp_name) < name_length)
1088 copyn(exp_name, target, MAXNAMLEN);
1096 xprintf("done item = %S\n", item);
1101 if (command == RECOGNIZE_SCROLL) {
1102 if ((cnt <= curchoice) || (curchoice == -1)) {
1106 } else if (numitems > 1) {
1108 curchoice = cnt - 1;
1109 choose_scroll_tab(&exp_name, cnt);
1115 if (command == SPELL)
1118 if (ignoring && numitems == 0 && nignored > 0)
1127 * Find and return the appropriate suffix character
1131 tw_suffix(looking, exp_dir, exp_name, target, name)
1133 Char *exp_dir, *exp_name, *target, *name;
1139 (void) strip(exp_name);
1148 * Don't consider array variables or empty variables
1150 if ((vp = adrof(exp_name)) != NULL) {
1151 if ((ptr = vp->vec[0]) == NULL || *ptr == '\0' ||
1155 else if ((ptr = tgetenv(exp_name)) == NULL || *ptr == '\0')
1160 return isadirectory(exp_dir, ptr) ? '/' : ' ';
1168 return isadirectory(exp_dir, exp_name) ? '/' : ' ';
1188 } /* end tw_suffix */
1192 * Repair a word after a spalling or a recognizwe
1195 tw_fixword(looking, word, dir, exp_name, max_word_length)
1197 Char *word, *dir, *exp_name;
1198 int max_word_length;
1204 copyn(word, STRtilde, 1);
1208 if ((ptr = Strrchr(word, '$')) != NULL)
1209 *++ptr = '\0'; /* Delete after the dollar */
1217 copyn(word, dir, max_word_length); /* put back dir part */
1225 (void) quote(exp_name);
1226 catn(word, exp_name, max_word_length); /* add extended name */
1227 } /* end tw_fixword */
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
1235 * 1. Handles interrupt cleanups.
1236 * 2. Retries if we had no matches, but there were ignored matches
1239 tw_collect(command, looking, exp_dir, exp_name, target, pat, flags, dir_fd)
1242 Char *exp_dir, *exp_name, **target, *pat;
1246 static int ni; /* static so we don't get clobbered */
1250 xprintf("target = %S\n", *target);
1255 (*tw_start_entry[looking])(dir_fd, pat);
1256 InsideCompletion = 1;
1258 /* interrupted, clean up */
1260 InsideCompletion = 0;
1263 #if defined(SOLARIS2) && defined(i386) && !defined(__GNUC__)
1264 /* Compiler bug? (from PWP) */
1265 if ((looking == TW_LOGNAME) || (looking == TW_USER))
1268 if (looking == TW_GRPNAME)
1272 #else /* !(SOLARIS2 && i386 && !__GNUC__) */
1273 (*tw_end_entry[looking])();
1274 #endif /* !(SOLARIS2 && i386 && !__GNUC__) */
1279 if ((ni = tw_collect_items(command, looking, exp_dir, exp_name,
1282 flags & ~TW_IGN_OK)) >= 0) {
1284 InsideCompletion = 0;
1286 #if defined(SOLARIS2) && defined(i386) && !defined(__GNUC__)
1287 /* Compiler bug? (from PWP) */
1288 if ((looking == TW_LOGNAME) || (looking == TW_USER))
1291 if (looking == TW_GRPNAME)
1295 #else /* !(SOLARIS2 && i386 && !__GNUC__) */
1296 (*tw_end_entry[looking])();
1297 #endif /* !(SOLARIS2 && i386 && !__GNUC__) */
1302 } /* end tw_collect */
1306 * List the items that were found
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)
1314 tw_list_items(looking, numitems, list_max)
1315 int looking, numitems, list_max;
1321 if ((ptr = varval(STRlistmax)) != STRNULL) {
1323 if (!Isdigit(*ptr)) {
1327 max_items = max_items * 10 + *ptr++ - '0';
1329 if ((max_items > 0) && (numitems > max_items) && list_max)
1330 max_items = numitems;
1335 if (max_items == 0 && (ptr = varval(STRlistmaxrows)) != STRNULL) {
1339 if (!Isdigit(*ptr)) {
1343 max_rows = max_rows * 10 + *ptr++ - '0';
1345 if (max_rows != 0 && looking != TW_JOB)
1346 rows = find_rows(tw_item_get(), numitems, TRUE);
1348 rows = numitems; /* underestimate for lines wider than the termH */
1349 if ((max_rows > 0) && (rows > max_rows) && list_max)
1356 if (max_items || max_rows) {
1362 name = CGETS(30, 5, "items");
1366 name = CGETS(30, 6, "rows");
1370 xprintf(CGETS(30, 7, "There are %d %s, list them anyway? [n/y] "),
1373 /* We should be in Rawmode here, so no \n to catch */
1374 (void) read(SHIN, &tc, 1);
1375 xprintf("%c\r\n", tc); /* echo the char, do a newline */
1377 * Perhaps we should use the yesexpr from the
1380 if (strchr(CGETS(30, 13, "Yy"), tc) == NULL)
1384 if (looking != TW_SIGNAL)
1385 qsort((ptr_t) tw_item_get(), (size_t) numitems, sizeof(Char *),
1386 (int (*) __P((const void *, const void *))) fcompare);
1387 if (looking != TW_JOB)
1388 print_by_column(STRNULL, tw_item_get(), numitems, TRUE);
1391 * print one item on every line because jobs can have spaces
1392 * and it is confusing.
1395 Char **w = tw_item_get();
1397 for (i = 0; i < numitems; i++) {
1398 xprintf("%S", w[i]);
1404 } /* end tw_list_items */
1408 * Perform a RECOGNIZE, LIST or SPELL command on string "word".
1411 * >= 0: SPELL command: "distance" (see spdist())
1412 * other: No. of items found
1413 * < 0: Error (message or beep is output)
1417 t_search(word, wp, command, max_word_length, looking, list_max, pat, suf)
1418 Char *word, *wp; /* original end-of-word */
1420 int max_word_length, looking, list_max;
1424 int numitems, /* Number of items matched */
1425 flags = 0, /* search flags */
1426 gpat = pat[0] != '\0', /* Glob pattern search */
1427 nd; /* Normalized directory return */
1428 Char exp_dir[FILSIZ + 1], /* dir after ~ expansion */
1429 dir[FILSIZ + 1], /* /x/y/z/ part in /x/y/z/f */
1430 exp_name[MAXNAMLEN + 1], /* the recognized (extended) */
1431 name[MAXNAMLEN + 1], /* f part in /d/d/d/f name */
1432 *target; /* Target to expand/correct/list */
1438 * bugfix by Marty Grossman (grossman@CC5.BBN.COM): directory listing can
1439 * dump core when interrupted
1443 non_unique_match = FALSE; /* See the recexact code below */
1445 extract_dir_and_name(word, dir, name);
1448 * SPECIAL HARDCODED COMPLETIONS:
1449 * foo$variable -> TW_VARIABLE
1450 * ~user -> TW_LOGNAME
1453 if ((*word == '~') && (Strchr(word, '/') == NULL)) {
1454 looking = TW_LOGNAME;
1456 gpat = 0; /* Override pattern mechanism */
1458 else if ((target = Strrchr(name, '$')) != 0 &&
1459 (Strchr(name, '/') == NULL)) {
1461 looking = TW_VARIABLE;
1462 gpat = 0; /* Override pattern mechanism */
1468 * Try to figure out what we should be looking for
1470 if (looking & TW_PATH) {
1471 gpat = 0; /* pattern holds the pathname to be used */
1472 copyn(exp_dir, pat, MAXNAMLEN);
1473 if (exp_dir[Strlen(exp_dir) - 1] != '/')
1474 catn(exp_dir, STRslash, MAXNAMLEN);
1475 catn(exp_dir, dir, MAXNAMLEN);
1480 switch (looking & ~TW_PATH) {
1489 if (Strchr(word, '/') || (looking & TW_PATH)) {
1491 flags |= TW_EXEC_CHK;
1495 /* PWP: don't even bother when doing ALL of the commands */
1496 if (looking == TW_COMMAND && (*word == '\0'))
1504 gpat = 0; /* pattern holds the name of the variable */
1508 if (command == LIST && pat != NULL) {
1521 * let fignore work only when we are not using a pattern
1523 flags |= (gpat == 0) ? TW_IGN_OK : TW_PAT_OK;
1526 xprintf(CGETS(30, 8, "looking = %d\n"), looking);
1543 if ((nd = expand_dir(dir, exp_dir, &dir_fd, command)) != 0)
1548 flags |= TW_DIR_CHK;
1552 * This is supposed to expand the directory stack.
1555 * 2. directories with the same name
1561 * Supposed to do delayed expansion, but it is inconsistent
1562 * from a user-interface point of view, since it does not
1563 * immediately obey addsuffix
1565 if ((nd = expand_dir(dir, exp_dir, &dir_fd, command)) != 0)
1567 if (isadirectory(exp_dir, name)) {
1568 if (exp_dir[0] != '\0' || name[0] != '\0') {
1569 catn(dir, name, MAXNAMLEN);
1570 if (dir[Strlen(dir) - 1] != '/')
1571 catn(dir, STRslash, MAXNAMLEN);
1572 if ((nd = expand_dir(dir, exp_dir, &dir_fd, command)) != 0)
1574 if (word[Strlen(word) - 1] != '/')
1575 catn(word, STRslash, MAXNAMLEN);
1580 if ((nd = expand_dir(dir, exp_dir, &dir_fd, command)) != 0)
1585 flags |= TW_TEXT_CHK;
1588 if ((nd = expand_dir(dir, exp_dir, &dir_fd, command)) != 0)
1592 case TW_PATH | TW_TEXT:
1593 case TW_PATH | TW_FILE:
1594 case TW_PATH | TW_DIRECTORY:
1595 case TW_PATH | TW_COMMAND:
1596 if ((dir_fd = opendir(short2str(exp_dir))) == NULL) {
1597 xprintf("%S: %s\n", exp_dir, strerror(errno));
1600 if (exp_dir[Strlen(exp_dir) - 1] != '/')
1601 catn(exp_dir, STRslash, MAXNAMLEN);
1603 looking &= ~TW_PATH;
1607 flags |= TW_TEXT_CHK;
1614 flags |= TW_DIR_CHK;
1618 copyn(target, word, MAXNAMLEN); /* so it can match things */
1622 abort(); /* Cannot happen */
1632 * Check if the spelling was already correct
1633 * From: Rob McMahon <cudcv@cu.warwick.ac.uk>
1635 if (command == SPELL && getpwnam(short2str(word)) != NULL) {
1641 copyn(name, word, MAXNAMLEN); /* name sans ~ */
1642 if (looking == TW_LOGNAME)
1649 copyn(target, word, MAXNAMLEN); /* so it can match things */
1653 xprintf(CGETS(30, 9,
1654 "\n%s internal error: I don't know what I'm looking for!\n"),
1660 numitems = tw_collect(command, looking, exp_dir, exp_name,
1661 &target, pat, flags, dir_fd);
1668 case RECOGNIZE_SCROLL:
1672 tw_fixword(looking, word, dir, exp_name, max_word_length);
1674 if (!match_unique_match && is_set(STRaddsuffix) && numitems == 1) {
1679 case 0: /* Automatic suffix */
1680 suffix[0] = tw_suffix(looking, exp_dir, exp_name, target, name);
1683 case -1: /* No suffix */
1686 default: /* completion specified suffix */
1687 suffix[0] = (Char) suf;
1690 catn(word, suffix, max_word_length);
1695 tw_list_items(looking, numitems, list_max);
1700 tw_fixword(looking, word, dir, exp_name, max_word_length);
1704 xprintf("Bad tw_command\n");
1707 } /* end t_search */
1710 /* extract_dir_and_name():
1711 * parse full path in file into 2 parts: directory and file names
1712 * Should leave final slash (/) at end of dir.
1715 extract_dir_and_name(path, dir, name)
1716 Char *path, *dir, *name;
1720 p = Strrchr(path, '/');
1723 p = Strrchr(path, ':');
1724 #endif /* WINNT_NATIVE */
1726 copyn(name, path, MAXNAMLEN);
1731 copyn(name, p, MAXNAMLEN);
1732 copyn(dir, path, p - path);
1734 } /* end extract_dir_and_name */
1738 * expand "/$old1/$old2/old3/"
1739 * to "/value_of_old1/value_of_old2/old3/"
1749 for (space = FILSIZ, p = new; *old && space > 0;)
1755 if (expdollar(&p, &old, &space, QUOTE) == NULL)
1764 * expand ~person/foo to home_directory_of_person/foo
1765 * or =<stack-entry> to <dir in stack entry>
1771 register Char *o, *p;
1775 for (p = new, o = &old[1]; *o && *o != '/'; *p++ = *o++)
1782 (void) Strcat(new, o);
1786 if ((p = globequal(new, old)) == NULL) {
1795 (void) Strcpy(new, old);
1802 * Open the directory given, expanding ~user and $var
1803 * Optionally normalize the path given
1806 expand_dir(dir, edir, dfd, cmd)
1812 Char tdir[MAXPATHLEN + 1];
1814 if ((dollar(tdir, dir) == 0) ||
1815 (tilde(edir, tdir) == 0) ||
1816 !(nd = dnormalize(*edir ? edir : STRdot, symlinks == SYM_IGNORE ||
1817 symlinks == SYM_EXPAND)) ||
1818 ((*dfd = opendir(short2str(nd))) == NULL)) {
1820 if (cmd == SPELL || SearchNoDirErr)
1823 * From: Amos Shapira <amoss@cs.huji.ac.il>
1824 * Print a better message when completion fails
1826 xprintf("\n%S %s\n",
1828 (*tdir ? tdir : dir),
1829 (errno == ENOTDIR ? CGETS(30, 10, "not a directory") :
1830 (errno == ENOENT ? CGETS(30, 11, "not found") :
1831 CGETS(30, 12, "unreadable"))));
1840 * Copy and append a / if there was one
1842 for (p = edir; *p; p++)
1845 for (p = nd; *p; p++)
1850 for (d = edir, s = nd; (*d++ = *s++) != '\0';)
1860 } /* end expand_dir */
1864 * Returns true if the directory should not be stat'd,
1866 * This way, things won't grind to a halt when you complete in /afs
1867 * or very large directories.
1876 if ((vp = adrof(STRnostat)) == NULL || (cp = vp->vec) == NULL)
1878 for (; *cp != NULL; cp++) {
1879 if (Strcmp(*cp, STRstar) == 0)
1881 if (Gmatch(dir, *cp))
1889 * Return a character that signifies a filetype
1890 * symbology from 4.3 ls command.
1902 * From: veals@crchh84d.bnr.ca (Percy Veals)
1903 * An extra stat is required for HPUX CDF files.
1905 struct stat hpstatb;
1906 #endif /* S_ISCDF */
1908 if (nostat(dir)) return(' ');
1910 (void) Strcpy(path, dir);
1911 catn(path, file, (int) (sizeof(path) / sizeof(Char)));
1913 if (lstat(ptr = short2str(path), &statb) != -1)
1914 /* see above #define of lstat */
1917 if (S_ISLNK(statb.st_mode)) { /* Symbolic link */
1918 if (adrof(STRlistlinks)) {
1919 if (stat(ptr, &statb) == -1)
1921 else if (S_ISDIR(statb.st_mode))
1931 if (S_ISSOCK(statb.st_mode)) /* Socket */
1935 if (S_ISFIFO(statb.st_mode)) /* Named Pipe */
1939 if (S_ISHIDDEN(statb.st_mode)) /* Hidden Directory [aix] */
1943 (void) strcat(ptr, "+"); /* Must append a '+' and re-stat(). */
1944 if ((stat(ptr, &hpstatb) != -1) && S_ISCDF(hpstatb.st_mode))
1945 return ('+'); /* Context Dependent Files [hpux] */
1948 if (S_ISNWK(statb.st_mode)) /* Network Special [hpux] */
1952 if (S_ISCHR(statb.st_mode)) /* char device */
1956 if (S_ISBLK(statb.st_mode)) /* block device */
1960 if (S_ISDIR(statb.st_mode)) /* normal Directory */
1963 if (statb.st_mode & (S_IXUSR|S_IXGRP|S_IXOTH))
1968 } /* end filetype */
1972 * Return trus if the file is a directory
1975 isadirectory(dir, file) /* return 1 if dir/file is a directory */
1976 Char *dir, *file; /* uses stat rather than lstat to get dest. */
1979 Char path[MAXPATHLEN];
1982 (void) Strcpy(path, dir);
1983 catn(path, file, (int) (sizeof(path) / sizeof(Char)));
1984 if (stat(short2str(path), &statb) >= 0) { /* resolve through
1987 if (S_ISSOCK(statb.st_mode)) /* Socket */
1991 if (S_ISFIFO(statb.st_mode)) /* Named Pipe */
1994 if (S_ISDIR(statb.st_mode)) /* normal Directory */
1999 } /* end isadirectory */
2004 * Return how many rows needed to print sorted down columns
2007 find_rows(items, count, no_file_suffix)
2009 int count, no_file_suffix;
2011 register int i, columns, rows;
2012 unsigned int maxwidth = 0;
2014 for (i = 0; i < count; i++) /* find widest string */
2015 maxwidth = max(maxwidth, (unsigned int) Strlen(items[i]));
2017 maxwidth += no_file_suffix ? 1 : 2; /* for the file tag and space */
2018 columns = (TermH + 1) / maxwidth; /* PWP: terminal size change */
2021 rows = (count + (columns - 1)) / columns;
2024 } /* end rows_needed_by_print_by_column */
2027 /* print_by_column():
2028 * Print sorted down columns or across columns when the first
2029 * word of $listflags shell variable contains 'x'.
2033 print_by_column(dir, items, count, no_file_suffix)
2034 register Char *dir, *items[];
2035 int count, no_file_suffix;
2037 register int i, r, c, columns, rows;
2038 unsigned int w, maxwidth = 0;
2042 lbuffed = 0; /* turn off line buffering */
2045 across = ((val = varval(STRlistflags)) != STRNULL) &&
2046 (Strchr(val, 'x') != NULL);
2048 for (i = 0; i < count; i++) /* find widest string */
2049 maxwidth = max(maxwidth, (unsigned int) Strlen(items[i]));
2051 maxwidth += no_file_suffix ? 1 : 2; /* for the file tag and space */
2052 columns = TermH / maxwidth; /* PWP: terminal size change */
2053 if (!columns || !isatty(didfds ? 1 : SHOUT))
2055 rows = (count + (columns - 1)) / columns;
2058 for (r = 0; r < rows; r++) {
2059 for (c = 0; c < columns; c++) {
2060 i = across ? (i + 1) : (c * rows + r);
2063 w = (unsigned int) Strlen(items[i]);
2066 if (no_file_suffix) {
2067 /* Print the command name */
2068 Char f = items[i][w - 1];
2069 items[i][w - 1] = 0;
2070 print_with_color(items[i], w - 1, f);
2073 /* Print filename followed by '/' or '*' or ' ' */
2074 print_with_color(items[i], w, filetype(dir, items[i]));
2077 #else /* ifndef COLOR_LS_F */
2078 if (no_file_suffix) {
2079 /* Print the command name */
2080 xprintf("%S", items[i]);
2083 /* Print filename followed by '/' or '*' or ' ' */
2084 xprintf("%S%c", items[i],
2085 filetype(dir, items[i]));
2088 #endif /* COLOR_LS_F */
2090 if (c < (columns - 1)) /* Not last column? */
2091 for (; w < maxwidth; w++)
2102 lbuffed = 1; /* turn back on line buffering */
2104 } /* end print_by_column */
2108 * Compare strings ignoring the quoting chars
2112 register Char *str1, *str2;
2114 for (; *str1 && samecase(*str1 & TRIM) == samecase(*str2 & TRIM);
2118 * The following case analysis is necessary so that characters which look
2119 * negative collate low against normal characters but high against the
2120 * end-of-string NUL.
2122 if (*str1 == '\0' && *str2 == '\0')
2124 else if (*str1 == '\0')
2126 else if (*str2 == '\0')
2129 return ((*str1 & TRIM) - (*str2 & TRIM));
2134 * Comparison routine for qsort
2137 fcompare(file1, file2)
2138 Char **file1, **file2;
2140 return (int) collate(*file1, *file2);
2141 } /* end fcompare */
2145 * Concatenate src onto tail of des.
2146 * Des is a string whose maximum length is count.
2147 * Always null terminate.
2150 catn(des, src, count)
2151 register Char *des, *src;
2154 while (--count >= 0 && *des)
2156 while (--count >= 0)
2157 if ((*des++ = *src++) == 0)
2164 * like strncpy but always leave room for trailing \0
2165 * and always null terminate.
2168 copyn(des, src, count)
2169 register Char *des, *src;
2172 while (--count >= 0)
2173 if ((*des++ = *src++) == 0)
2180 * like it's normal string counter-part
2181 * [apollo uses that in tc.os.c, so it cannot be static]
2190 len = (int) Strlen(str);
2191 /* Search the STR_environ for the entry matching str. */
2192 for (var = STR_environ; var != NULL && *var != NULL; var++)
2193 if (Strlen(*var) >= len && (*var)[len] == '=') {
2194 /* Temporarily terminate the string so we can copy the variable
2197 res = StrQcmp(*var, str);
2198 /* Restore the '=' and return a pointer to the value of the
2199 environment variable. */
2202 return (&((*var)[len + 1]));
2208 struct scroll_tab_list *scroll_tab = 0;
2211 add_scroll_tab(item)
2214 struct scroll_tab_list *new_scroll;
2216 new_scroll = (struct scroll_tab_list *) xmalloc((size_t)
2217 sizeof(struct scroll_tab_list));
2218 new_scroll->element = Strsave(item);
2219 new_scroll->next = scroll_tab;
2220 scroll_tab = new_scroll;
2224 choose_scroll_tab(exp_name, cnt)
2228 struct scroll_tab_list *loop;
2232 ptr = (Char **) xmalloc((size_t) sizeof(Char *) * cnt);
2234 for(loop = scroll_tab; loop && (tmp >= 0); loop = loop->next)
2235 ptr[--tmp] = loop->element;
2237 qsort((ptr_t) ptr, (size_t) cnt, sizeof(Char *),
2238 (int (*) __P((const void *, const void *))) fcompare);
2240 copyn(*exp_name, ptr[curchoice], (int) Strlen(ptr[curchoice]));
2247 struct scroll_tab_list *loop;
2251 scroll_tab = scroll_tab->next;
2252 xfree((ptr_t) loop->element);
2253 xfree((ptr_t) loop);