1 /* $Header: /src/pub/tcsh/sh.file.c,v 3.22 2002/07/01 20:53:00 christos Exp $ */
3 * sh.file.c: File completion for csh. This file is not used in tcsh.
6 * Copyright (c) 1980, 1991 The Regents of the University of California.
9 * Redistribution and use in source and binary forms, with or without
10 * modification, are permitted provided that the following conditions
12 * 1. Redistributions of source code must retain the above copyright
13 * notice, this list of conditions and the following disclaimer.
14 * 2. Redistributions in binary form must reproduce the above copyright
15 * notice, this list of conditions and the following disclaimer in the
16 * documentation and/or other materials provided with the distribution.
17 * 3. Neither the name of the University nor the names of its contributors
18 * may be used to endorse or promote products derived from this software
19 * without specific prior written permission.
21 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
22 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
23 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
24 * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
25 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
26 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
27 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
28 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
29 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
30 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
36 RCSID("$Id: sh.file.c,v 3.22 2002/07/01 20:53:00 christos Exp $")
38 #if defined(FILEC) && defined(TIOCSTI)
41 * Tenex style file name recognition, .. and more.
43 * Author: Ken Greer, Sept. 1975, CMU.
44 * Finally got around to adding to the Cshell., Ken Greer, Dec. 1981.
56 #define ESC CTL_ESC('\033')
62 static void setup_tty __P((int));
63 static void back_to_col_1 __P((void));
64 static void pushback __P((Char *));
65 static void catn __P((Char *, Char *, int));
66 static void copyn __P((Char *, Char *, int));
67 static Char filetype __P((Char *, Char *));
68 static void print_by_column __P((Char *, Char *[], int));
69 static Char *tilde __P((Char *, Char *));
70 static void retype __P((void));
71 static void beep __P((void));
72 static void print_recognized_stuff __P((Char *));
73 static void extract_dir_and_name __P((Char *, Char *, Char *));
74 static Char *getitem __P((DIR *, int));
75 static void free_items __P((Char **));
76 static int tsearch __P((Char *, COMMAND, int));
77 static int compare __P((const ptr_t, const ptr_t));
78 static int recognize __P((Char *, Char *, int, int));
79 static int is_prefix __P((Char *, Char *));
80 static int is_suffix __P((Char *, Char *));
81 static int ignored __P((Char *));
85 * Put this here so the binary can be patched with adb to enable file
86 * completion by default. Filec controls completion, nobeep controls
87 * ringing the terminal bell on incomplete expansions.
97 struct termios tchars;
103 (void) tcgetattr(SHIN, &tchars);
105 (void) ioctl(SHIN, TCGETA, (ioctl_t) &tchars);
108 tchars.c_cc[VEOL] = ESC;
109 if (tchars.c_lflag & ICANON)
121 tchars.c_lflag |= ICANON;
126 tchars.c_cc[VEOL] = _POSIX_VDISABLE;
134 (void) tcsetattr(SHIN, on, &tchars);
136 (void) ioctl(SHIN, on, (ioctl_t) &tchars);
140 static struct tchars tchars;/* INT, QUIT, XON, XOFF, EOF, BRK */
143 (void) ioctl(SHIN, TIOCGETC, (ioctl_t) & tchars);
145 (void) ioctl(SHIN, TIOCSETC, (ioctl_t) & tchars);
147 * This must be done after every command: if the tty gets into raw or
148 * cbreak mode the user can't even type 'reset'.
150 (void) ioctl(SHIN, TIOCGETP, (ioctl_t) & sgtty);
151 if (sgtty.sg_flags & (RAW | CBREAK)) {
152 sgtty.sg_flags &= ~(RAW | CBREAK);
153 (void) ioctl(SHIN, TIOCSETP, (ioctl_t) & sgtty);
158 (void) ioctl(SHIN, TIOCSETC, (ioctl_t) & tchars);
164 * Move back to beginning of current line
171 struct termios tty, tty_normal;
173 struct termio tty, tty_normal;
176 struct sgttyb tty, tty_normal;
180 sigmask_t omask = sigblock(sigmask(SIGINT));
182 (void) sighold(SIGINT);
183 # endif /* BSDSIGS */
187 (void) tcgetattr(SHOUT, &tty);
189 (void) ioctl(SHOUT, TCGETA, (ioctl_t) &tty_normal);
192 tty.c_iflag &= ~INLCR;
193 tty.c_oflag &= ~ONLCR;
195 (void) tcsetattr(SHOUT, TCSANOW, &tty);
197 (void) ioctl(SHOUT, TCSETAW, (ioctl_t) &tty);
199 (void) write(SHOUT, "\r", 1);
201 (void) tcsetattr(SHOUT, TCSANOW, &tty_normal);
203 (void) ioctl(SHOUT, TCSETAW, (ioctl_t) &tty_normal);
206 (void) ioctl(SHIN, TIOCGETP, (ioctl_t) & tty);
208 tty.sg_flags &= ~CRMOD;
209 (void) ioctl(SHIN, TIOCSETN, (ioctl_t) & tty);
210 (void) write(SHOUT, "\r", 1);
211 (void) ioctl(SHIN, TIOCSETN, (ioctl_t) & tty_normal);
215 (void) sigsetmask(omask);
217 (void) sigrelse(SIGINT);
218 # endif /* BSDISGS */
222 * Push string contents back into tty queue
232 struct termios tty, tty_normal;
234 struct termio tty, tty_normal;
237 struct sgttyb tty, tty_normal;
241 sigmask_t omask = sigblock(sigmask(SIGINT));
243 (void) sighold(SIGINT);
248 (void) tcgetattr(SHOUT, &tty);
250 (void) ioctl(SHOUT, TCSETAW, (ioctl_t) &tty);
253 tty.c_lflag &= ~(ECHOKE | ECHO | ECHOE | ECHOK | ECHONL | ECHOPRT | ECHOCTL);
255 (void) tcsetattr(SHOUT, TCSANOW, &tty);
257 (void) ioctl(SHOUT, TCSETAW, (ioctl_t) &tty);
260 for (p = string; (c = *p) != '\0'; p++)
261 (void) ioctl(SHOUT, TIOCSTI, (ioctl_t) & c);
263 (void) tcsetattr(SHOUT, TCSANOW, &tty_normal);
265 (void) ioctl(SHOUT, TCSETAW, (ioctl_t) &tty_normal);
268 (void) ioctl(SHOUT, TIOCGETP, (ioctl_t) & tty);
270 tty.sg_flags &= ~ECHO;
271 (void) ioctl(SHOUT, TIOCSETN, (ioctl_t) & tty);
273 for (p = string; c = *p; p++)
274 (void) ioctl(SHOUT, TIOCSTI, (ioctl_t) & c);
275 (void) ioctl(SHOUT, TIOCSETN, (ioctl_t) & tty_normal);
279 (void) sigsetmask(omask);
281 (void) sigrelse(SIGINT);
282 # endif /* BSDISGS */
286 * Concatenate src onto tail of des.
287 * Des is a string whose maximum length is count.
288 * Always null terminate.
291 catn(des, src, count)
295 while (--count >= 0 && *des)
298 if ((*des++ = *src++) == 0)
304 * Like strncpy but always leave room for trailing \0
305 * and always null terminate.
308 copyn(des, src, count)
313 if ((*des++ = *src++) == 0)
322 Char path[MAXPATHLEN];
325 catn(Strcpy(path, dir), file, sizeof(path) / sizeof(Char));
326 if (lstat(short2str(path), &statb) == 0) {
327 switch (statb.st_mode & S_IFMT) {
332 if (stat(short2str(path), &statb) == 0 && /* follow it out */
333 S_ISDIR(statb.st_mode))
342 if (statb.st_mode & 0111)
349 static struct winsize win;
352 * Print sorted down columns
355 print_by_column(dir, items, count)
359 int i, rows, r, c, maxwidth = 0, columns;
361 if (ioctl(SHOUT, TIOCGWINSZ, (ioctl_t) & win) < 0 || win.ws_col == 0)
363 for (i = 0; i < count; i++)
364 maxwidth = maxwidth > (r = Strlen(items[i])) ? maxwidth : r;
365 maxwidth += 2; /* for the file tag and space */
366 columns = win.ws_col / maxwidth;
369 rows = (count + (columns - 1)) / columns;
370 for (r = 0; r < rows; r++) {
371 for (c = 0; c < columns; c++) {
376 xprintf("%S", items[i]);
377 xputchar(dir ? filetype(dir, items[i]) : ' ');
378 if (c < columns - 1) { /* last column? */
379 w = Strlen(items[i]) + 1;
380 for (; w < maxwidth; w++)
391 * Expand file name with possible tilde usage
394 * home_directory_of_person/mumble
402 static Char person[40];
405 return (Strcpy(new, old));
407 for (p = person, o = &old[1]; *o && *o != '/'; *p++ = *o++);
409 if (person[0] == '\0')
410 (void) Strcpy(new, varval(STRhome));
412 pw = getpwnam(short2str(person));
415 (void) Strcpy(new, str2short(pw->pw_dir));
417 (void) Strcat(new, o);
422 * Cause pending line to be printed
431 (void) tcgetattr(SHOUT, &tty);
435 (void) ioctl(SHOUT, TCGETA, (ioctl_t) &tty);
438 tty.c_lflag |= PENDIN;
441 (void) tcsetattr(SHOUT, TCSANOW, &tty);
443 (void) ioctl(SHOUT, TCSETAW, (ioctl_t) &tty);
446 int pending_input = LPENDIN;
448 (void) ioctl(SHOUT, TIOCLBIS, (ioctl_t) & pending_input);
455 if (adrof(STRnobeep) == 0)
457 (void) write(SHOUT, "\007", 1);
460 unsigned char beep_ch = CTL_ESC('\007');
461 (void) write(SHOUT, &beep_ch, 1);
467 * Erase that silly ^[ and
468 * print the recognized part of the string
471 print_recognized_stuff(recognized_part)
472 Char *recognized_part;
474 /* An optimized erasing of that silly ^[ */
477 switch (Strlen(recognized_part)) {
479 case 0: /* erase two Characters: ^[ */
486 case 1: /* overstrike the ^, erase the [ */
487 xprintf("%S", recognized_part);
492 default: /* overstrike both Characters ^[ */
493 xprintf("%S", recognized_part);
500 * Parse full path in file into 2 parts: directory and file names
501 * Should leave final slash (/) at end of dir.
504 extract_dir_and_name(path, dir, name)
505 Char *path, *dir, *name;
509 p = Strrchr(path, '/');
511 copyn(name, path, MAXNAMLEN);
515 copyn(name, ++p, MAXNAMLEN);
516 copyn(dir, path, p - path);
519 /* atp vmsposix - I need to remove all the setpwent
520 * getpwent endpwent stuff. VMS_POSIX has getpwnam getpwuid
521 * and getlogin. This needs fixing. (There is no access to
522 * pw->passwd in VMS - a secure system benefit :-| )
525 getitem(dir_fd, looking_for_lognames)
527 int looking_for_lognames;
532 if (looking_for_lognames) {
536 if ((pw = getpwent()) == NULL)
538 return (str2short(pw->pw_name));
539 #endif /* atp vmsposix */
541 if ((dirp = readdir(dir_fd)) != NULL)
542 return (str2short(dirp->d_name));
552 for (i = 0; items[i]; i++)
553 xfree((ptr_t) items[i]);
554 xfree((ptr_t) items);
558 # define FREE_ITEMS(items) { \
561 omask = sigblock(sigmask(SIGINT));\
564 (void) sigsetmask(omask);\
567 # define FREE_ITEMS(items) { \
568 (void) sighold(SIGINT);\
571 (void) sigrelse(SIGINT);\
576 * Perform a RECOGNIZE or LIST command on string "word".
579 tsearch(word, command, max_word_length)
584 static Char **items = NULL;
586 int numitems = 0, ignoring = TRUE, nignored = 0;
587 int name_length, looking_for_lognames;
588 Char tilded_dir[MAXPATHLEN + 1], dir[MAXPATHLEN + 1];
589 Char name[MAXNAMLEN + 1], extended_name[MAXNAMLEN + 1];
592 #define MAXITEMS 1024
597 looking_for_lognames = (*word == '~') && (Strchr(word, '/') == NULL);
598 if (looking_for_lognames) {
601 #endif /*atp vmsposix */
602 copyn(name, &word[1], MAXNAMLEN); /* name sans ~ */
606 extract_dir_and_name(word, dir, name);
607 if (tilde(tilded_dir, dir) == 0)
609 dir_fd = opendir(*tilded_dir ? short2str(tilded_dir) : ".");
614 again: /* search for matches */
615 name_length = Strlen(name);
617 (item = getitem(dir_fd, looking_for_lognames)) != NULL;) {
618 if (!is_prefix(name, item))
620 /* Don't match . files on null prefix match */
621 if (name_length == 0 && item[0] == '.' &&
622 !looking_for_lognames)
624 if (command == LIST) {
625 if (numitems >= MAXITEMS) {
626 xprintf(CGETS(14, 1, "\nYikes!! Too many %s!!\n"),
627 looking_for_lognames ?
628 CGETS(14, 2, "names in password file") :
629 CGETS(14, 3, "files"));
633 * From Beto Appleton (beto@aixwiz.austin.ibm.com)
634 * typing "./control-d" will cause the csh to core-dump.
635 * the problem can be reproduce as following:
638 * 3. create a directory with 1050 files
639 * 4. typing "./control-d" will cause the csh to core-dump
640 * Solution: Add + 1 to MAXITEMS
643 items = (Char **) xcalloc(sizeof(items[0]), MAXITEMS + 1);
644 items[numitems] = (Char *) xmalloc((size_t) (Strlen(item) + 1) *
646 copyn(items[numitems], item, MAXNAMLEN);
649 else { /* RECOGNIZE command */
650 if (ignoring && ignored(item))
652 else if (recognize(extended_name,
653 item, name_length, ++numitems))
657 if (ignoring && numitems == 0 && nignored > 0) {
660 if (looking_for_lognames)
663 #endif /* atp vmsposix */
669 if (looking_for_lognames)
672 #endif /*atp vmsposix */
674 (void) closedir(dir_fd);
677 if (command == RECOGNIZE) {
678 if (looking_for_lognames)
679 copyn(word, STRtilde, 1);
681 /* put back dir part */
682 copyn(word, dir, max_word_length);
683 /* add extended name */
684 catn(word, extended_name, max_word_length);
688 qsort((ptr_t) items, (size_t) numitems, sizeof(items[0]),
689 (int (*) __P((const void *, const void *))) compare);
690 print_by_column(looking_for_lognames ? NULL : tilded_dir,
703 #if defined(NLS) && !defined(NOSTRCOLL)
704 errno = 0; /* strcoll sets errno, another brain-damage */
706 return (strcoll(*(char **) p, *(char **) q));
708 return (strcmp(*(char **) p, *(char **) q));
709 #endif /* NLS && !NOSTRCOLL */
713 * Object: extend what user typed up to an ambiguity.
715 * On first match, copy full item (assume it'll be the only match)
716 * On subsequent matches, shorten extended_name to the first
717 * Character mismatch between extended_name and item.
718 * If we shorten it back to the prefix length, stop searching.
721 recognize(extended_name, item, name_length, numitems)
722 Char *extended_name, *item;
723 int name_length, numitems;
725 if (numitems == 1) /* 1st match */
726 copyn(extended_name, item, MAXNAMLEN);
727 else { /* 2nd & subsequent matches */
732 for (ent = item; *x && *x == *ent++; x++, len++);
733 *x = '\0'; /* Shorten at 1st Char diff */
734 if (len == name_length) /* Ambiguous to prefix? */
735 return (-1); /* So stop now and save time */
741 * Return true if check matches initial Chars in template.
742 * This differs from PWB imatch in that if check is null
743 * it matches anything.
746 is_prefix(check, template)
747 Char *check, *template;
752 while (*check++ == *template++);
757 * Return true if the Chars in template appear at the
758 * end of check, I.e., are it's suffix.
761 is_suffix(check, template)
762 Char *check, *template;
766 for (c = check; *c++;);
767 for (t = template; *t++;);
771 if (c == check || *--t != *--c)
777 tenex(inputline, inputline_size)
781 int numitems, num_read;
782 char tinputline[BUFSIZE];
787 while ((num_read = read(SHIN, tinputline, BUFSIZE)) > 0) {
789 static Char delims[] = {' ', '\'', '"', '\t', ';', '&', '<',
790 '>', '(', ')', '|', '^', '%', '\0'};
791 Char *str_end, *word_start, last_Char, should_retype;
795 for (i = 0; i < num_read; i++)
796 inputline[i] = (unsigned char) tinputline[i];
797 last_Char = inputline[num_read - 1] & ASCII;
799 if (last_Char == '\n' || num_read == inputline_size)
801 command = (last_Char == ESC) ? RECOGNIZE : LIST;
804 str_end = &inputline[num_read];
805 if (last_Char == ESC)
806 --str_end; /* wipeout trailing cmd Char */
809 * Find LAST occurence of a delimiter in the inputline. The word start
810 * is one Character past it.
812 for (word_start = str_end; word_start > inputline; --word_start)
813 if (Strchr(delims, word_start[-1]))
815 space_left = inputline_size - (word_start - inputline) - 1;
816 numitems = tsearch(word_start, command, space_left);
818 if (command == RECOGNIZE) {
819 /* print from str_end on */
820 print_recognized_stuff(str_end);
821 if (numitems != 1) /* Beep = No match/ambiguous */
826 * Tabs in the input line cause trouble after a pushback. tty driver
827 * won't backspace over them because column positions are now
828 * incorrect. This is solved by retyping over current line.
830 should_retype = FALSE;
831 if (Strchr(inputline, '\t')) { /* tab Char in input line? */
833 should_retype = TRUE;
835 if (command == LIST) /* Always retype after a LIST */
836 should_retype = TRUE;
838 printprompt(0, NULL);
854 if ((vp = adrof(STRfignore)) == NULL || (cp = vp->vec) == NULL)
856 for (; *cp != NULL; cp++)
857 if (is_suffix(item, *cp))
861 #endif /* FILEC && TIOCSTI */