1 /* $Header: /p/tcsh/cvsroot/tcsh/sh.file.c,v 3.36 2007/07/05 14:13:06 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("$tcsh: sh.file.c,v 3.36 2007/07/05 14:13:06 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 (int);
63 static void back_to_col_1 (void);
64 static void pushback (const Char *);
65 static int filetype (const Char *, const Char *);
66 static void print_by_column (const Char *, Char *[], size_t);
67 static Char *tilde (const Char *);
68 static void retype (void);
69 static void beep (void);
70 static void print_recognized_stuff (const Char *);
71 static void extract_dir_and_name (const Char *, Char **, const Char **);
72 static Char *getitem (DIR *, int);
73 static size_t tsearch (Char *, COMMAND, size_t);
74 static int compare (const void *, const void *);
75 static int recognize (Char **, Char *, size_t, size_t);
76 static int is_prefix (const Char *, const Char *);
77 static int is_suffix (const Char *, const Char *);
78 static int ignored (const Char *);
82 * Put this here so the binary can be patched with adb to enable file
83 * completion by default. Filec controls completion, nobeep controls
84 * ringing the terminal bell on incomplete expansions.
93 struct termios tchars;
99 (void) tcgetattr(SHIN, &tchars);
101 (void) ioctl(SHIN, TCGETA, (ioctl_t) &tchars);
104 tchars.c_cc[VEOL] = ESC;
105 if (tchars.c_lflag & ICANON)
117 tchars.c_lflag |= ICANON;
122 tchars.c_cc[VEOL] = _POSIX_VDISABLE;
130 (void) xtcsetattr(SHIN, on, &tchars);
132 (void) ioctl(SHIN, on, (ioctl_t) &tchars);
136 static struct tchars tchars;/* INT, QUIT, XON, XOFF, EOF, BRK */
139 (void) ioctl(SHIN, TIOCGETC, (ioctl_t) & tchars);
141 (void) ioctl(SHIN, TIOCSETC, (ioctl_t) & tchars);
143 * This must be done after every command: if the tty gets into raw or
144 * cbreak mode the user can't even type 'reset'.
146 (void) ioctl(SHIN, TIOCGETP, (ioctl_t) & sgtty);
147 if (sgtty.sg_flags & (RAW | CBREAK)) {
148 sgtty.sg_flags &= ~(RAW | CBREAK);
149 (void) ioctl(SHIN, TIOCSETP, (ioctl_t) & sgtty);
154 (void) ioctl(SHIN, TIOCSETC, (ioctl_t) & tchars);
160 * Move back to beginning of current line
167 struct termios tty, tty_normal;
169 struct termio tty, tty_normal;
172 struct sgttyb tty, tty_normal;
176 cleanup_push(&pintr_disabled, disabled_cleanup);
180 (void) tcgetattr(SHOUT, &tty);
182 (void) ioctl(SHOUT, TCGETA, (ioctl_t) &tty_normal);
185 tty.c_iflag &= ~INLCR;
186 tty.c_oflag &= ~ONLCR;
188 (void) xtcsetattr(SHOUT, TCSANOW, &tty);
190 (void) ioctl(SHOUT, TCSETAW, (ioctl_t) &tty);
192 (void) xwrite(SHOUT, "\r", 1);
194 (void) xtcsetattr(SHOUT, TCSANOW, &tty_normal);
196 (void) ioctl(SHOUT, TCSETAW, (ioctl_t) &tty_normal);
199 (void) ioctl(SHIN, TIOCGETP, (ioctl_t) & tty);
201 tty.sg_flags &= ~CRMOD;
202 (void) ioctl(SHIN, TIOCSETN, (ioctl_t) & tty);
203 (void) xwrite(SHOUT, "\r", 1);
204 (void) ioctl(SHIN, TIOCSETN, (ioctl_t) & tty_normal);
207 cleanup_until(&pintr_disabled);
211 * Push string contents back into tty queue
214 pushback(const Char *string)
219 struct termios tty, tty_normal;
221 struct termio tty, tty_normal;
224 struct sgttyb tty, tty_normal;
228 cleanup_push(&pintr_disabled, disabled_cleanup);
232 (void) tcgetattr(SHOUT, &tty);
234 (void) ioctl(SHOUT, TCSETAW, (ioctl_t) &tty);
237 tty.c_lflag &= ~(ECHOKE | ECHO | ECHOE | ECHOK | ECHONL |
243 (void) xtcsetattr(SHOUT, TCSANOW, &tty);
245 (void) ioctl(SHOUT, TCSETAW, (ioctl_t) &tty);
248 for (p = string; *p != '\0'; p++) {
249 char buf[MB_LEN_MAX];
252 len = one_wctomb(buf, *p & CHAR);
253 for (i = 0; i < len; i++)
254 (void) ioctl(SHOUT, TIOCSTI, (ioctl_t) &buf[i]);
257 (void) xtcsetattr(SHOUT, TCSANOW, &tty_normal);
259 (void) ioctl(SHOUT, TCSETAW, (ioctl_t) &tty_normal);
262 (void) ioctl(SHOUT, TIOCGETP, (ioctl_t) & tty);
264 tty.sg_flags &= ~ECHO;
265 (void) ioctl(SHOUT, TIOCSETN, (ioctl_t) & tty);
267 for (p = string; c = *p; p++)
268 (void) ioctl(SHOUT, TIOCSTI, (ioctl_t) & c);
269 (void) ioctl(SHOUT, TIOCSETN, (ioctl_t) & tty_normal);
272 cleanup_until(&pintr_disabled);
276 filetype(const Char *dir, const Char *file)
282 path = Strspl(dir, file);
283 spath = short2str(path);
285 if (lstat(spath, &statb) == 0) {
286 switch (statb.st_mode & S_IFMT) {
291 if (stat(spath, &statb) == 0 && /* follow it out */
292 S_ISDIR(statb.st_mode))
301 if (statb.st_mode & 0111)
309 * Print sorted down columns
312 print_by_column(const Char *dir, Char *items[], size_t count)
316 int rows, r, c, maxwidth = 0, columns;
318 if (ioctl(SHOUT, TIOCGWINSZ, (ioctl_t) & win) < 0 || win.ws_col == 0)
320 for (i = 0; i < count; i++)
321 maxwidth = maxwidth > (r = Strlen(items[i])) ? maxwidth : r;
322 maxwidth += 2; /* for the file tag and space */
323 columns = win.ws_col / maxwidth;
326 rows = (count + (columns - 1)) / columns;
327 for (r = 0; r < rows; r++) {
328 for (c = 0; c < columns; c++) {
333 xprintf("%S", items[i]);
334 xputchar(dir ? filetype(dir, items[i]) : ' ');
335 if (c < columns - 1) { /* last column? */
336 w = Strlen(items[i]) + 1;
337 for (; w < maxwidth; w++)
348 * Expand file name with possible tilde usage
351 * home_directory_of_person/mumble
354 tilde(const Char *old)
356 const Char *o, *home;
360 return (Strsave(old));
363 for (o = old; *o != '\0' && *o != '/'; o++)
366 home = varval(STRhome);
370 person = Strnsave(old, o - old);
371 pw = xgetpwnam(short2str(person));
375 home = str2short(pw->pw_dir);
377 return Strspl(home, o);
381 * Cause pending line to be printed
390 (void) tcgetattr(SHOUT, &tty);
394 (void) ioctl(SHOUT, TCGETA, (ioctl_t) &tty);
398 tty.c_lflag |= PENDIN;
402 (void) xtcsetattr(SHOUT, TCSANOW, &tty);
404 (void) ioctl(SHOUT, TCSETAW, (ioctl_t) &tty);
407 int pending_input = LPENDIN;
409 (void) ioctl(SHOUT, TIOCLBIS, (ioctl_t) & pending_input);
416 if (adrof(STRnobeep) == 0)
418 (void) xwrite(SHOUT, "\007", 1);
421 unsigned char beep_ch = CTL_ESC('\007');
422 (void) xwrite(SHOUT, &beep_ch, 1);
428 * Erase that silly ^[ and
429 * print the recognized part of the string
432 print_recognized_stuff(const Char *recognized_part)
434 /* An optimized erasing of that silly ^[ */
437 switch (Strlen(recognized_part)) {
439 case 0: /* erase two Characters: ^[ */
446 case 1: /* overstrike the ^, erase the [ */
447 xprintf("%S", recognized_part);
452 default: /* overstrike both Characters ^[ */
453 xprintf("%S", recognized_part);
460 * Parse full path in file into 2 parts: directory and file names
461 * Should leave final slash (/) at end of dir.
464 extract_dir_and_name(const Char *path, Char **dir, const Char **name)
468 p = Strrchr(path, '/');
474 *dir = Strnsave(path, p - path);
478 getitem(DIR *dir_fd, int looking_for_lognames)
483 if (looking_for_lognames) {
484 #ifndef HAVE_GETPWENT
487 if ((pw = getpwent()) == NULL)
489 return (str2short(pw->pw_name));
490 #endif /* atp vmsposix */
492 if ((dirp = readdir(dir_fd)) != NULL)
493 return (str2short(dirp->d_name));
498 * Perform a RECOGNIZE or LIST command on string "word".
501 tsearch(Char *word, COMMAND command, size_t max_word_length)
504 int ignoring = TRUE, nignored = 0;
505 int looking_for_lognames;
506 Char *tilded_dir = NULL, *dir = NULL;
507 Char *extended_name = NULL;
510 struct blk_buf items = BLK_BUF_INIT;
513 looking_for_lognames = (*word == '~') && (Strchr(word, '/') == NULL);
514 if (looking_for_lognames) {
518 name = word + 1; /* name sans ~ */
520 cleanup_push(dir, xfree);
523 extract_dir_and_name(word, &dir, &name);
524 cleanup_push(dir, xfree);
525 tilded_dir = tilde(dir);
526 if (tilded_dir == NULL)
528 cleanup_push(tilded_dir, xfree);
529 dir_fd = opendir(*tilded_dir ? short2str(tilded_dir) : ".");
534 name_length = Strlen(name);
535 cleanup_push(&extended_name, xfree_indirect);
536 cleanup_push(&items, bb_cleanup);
537 again: /* search for matches */
538 while ((item = getitem(dir_fd, looking_for_lognames)) != NULL) {
539 if (!is_prefix(name, item))
541 /* Don't match . files on null prefix match */
542 if (name_length == 0 && item[0] == '.' &&
543 !looking_for_lognames)
546 bb_append(&items, Strsave(item));
547 else { /* RECOGNIZE command */
548 if (ignoring && ignored(item))
550 else if (recognize(&extended_name, item, name_length, ++items.len))
554 if (ignoring && items.len == 0 && nignored > 0) {
557 if (looking_for_lognames) {
560 #endif /* atp vmsposix */
566 if (looking_for_lognames) {
567 #ifndef HAVE_GETPWENT
572 if (items.len != 0) {
573 if (command == RECOGNIZE) {
574 if (looking_for_lognames)
575 copyn(word, STRtilde, 2);/*FIXBUF, sort of */
577 /* put back dir part */
578 copyn(word, dir, max_word_length);/*FIXBUF*/
579 /* add extended name */
580 catn(word, extended_name, max_word_length);/*FIXBUF*/
583 qsort(items.vec, items.len, sizeof(items.vec[0]), compare);
584 print_by_column(looking_for_lognames ? NULL : tilded_dir,
585 items.vec, items.len);
595 compare(const void *p, const void *q)
600 return (wcscoll(*(Char *const *) p, *(Char *const *) q));
605 p1 = strsave(short2str(*(Char *const *) p));
606 q1 = strsave(short2str(*(Char *const *) q));
607 # if defined(NLS) && defined(HAVE_STRCOLL)
608 res = strcoll(p1, q1);
610 res = strcmp(p1, q1);
611 # endif /* NLS && HAVE_STRCOLL */
615 #endif /* not WIDE_STRINGS */
619 * Object: extend what user typed up to an ambiguity.
621 * On first match, copy full item (assume it'll be the only match)
622 * On subsequent matches, shorten extended_name to the first
623 * Character mismatch between extended_name and item.
624 * If we shorten it back to the prefix length, stop searching.
627 recognize(Char **extended_name, Char *item, size_t name_length,
630 if (numitems == 1) /* 1st match */
631 *extended_name = Strsave(item);
632 else { /* 2nd & subsequent matches */
637 for (ent = item; *x && *x == *ent++; x++, len++);
638 *x = '\0'; /* Shorten at 1st Char diff */
639 if (len == name_length) /* Ambiguous to prefix? */
640 return (-1); /* So stop now and save time */
646 * Return true if check matches initial Chars in template.
647 * This differs from PWB imatch in that if check is null
648 * it matches anything.
651 is_prefix(const Char *check, const Char *template)
656 while (*check++ == *template++);
661 * Return true if the Chars in template appear at the
662 * end of check, I.e., are it's suffix.
665 is_suffix(const Char *check, const Char *template)
669 for (c = check; *c++;);
670 for (t = template; *t++;);
674 if (c == check || *--t != *--c)
680 setup_tty_cleanup(void *dummy)
687 tenex(Char *inputline, size_t inputline_size)
691 char tinputline[BUFSIZE + 1];/*FIXBUF*/
694 cleanup_push(&num_read, setup_tty_cleanup); /* num_read is only a marker */
696 while ((num_read = xread(SHIN, tinputline, BUFSIZE)) > 0) {/*FIXBUF*/
697 static const Char delims[] = {' ', '\'', '"', '\t', ';', '&', '<',
698 '>', '(', ')', '|', '^', '%', '\0'};
699 Char *str_end, *word_start, last_Char, should_retype;
703 tinputline[num_read] = 0;
704 Strcpy(inputline, str2short(tinputline));/*FIXBUF*/
705 num_read = Strlen(inputline);
706 last_Char = CTL_ESC(ASC(inputline[num_read - 1]) & ASCII);
708 if (last_Char == '\n' || (size_t)num_read == inputline_size)
710 command = (last_Char == ESC) ? RECOGNIZE : LIST;
713 str_end = &inputline[num_read];
714 if (last_Char == ESC)
715 --str_end; /* wipeout trailing cmd Char */
718 * Find LAST occurence of a delimiter in the inputline. The word start
719 * is one Character past it.
721 for (word_start = str_end; word_start > inputline; --word_start)
722 if (Strchr(delims, word_start[-1]))
724 space_left = inputline_size - (word_start - inputline) - 1;
725 numitems = tsearch(word_start, command, space_left);
727 if (command == RECOGNIZE) {
728 /* print from str_end on */
729 print_recognized_stuff(str_end);
730 if (numitems != 1) /* Beep = No match/ambiguous */
735 * Tabs in the input line cause trouble after a pushback. tty driver
736 * won't backspace over them because column positions are now
737 * incorrect. This is solved by retyping over current line.
739 should_retype = FALSE;
740 if (Strchr(inputline, '\t')) { /* tab Char in input line? */
742 should_retype = TRUE;
744 if (command == LIST) /* Always retype after a LIST */
745 should_retype = TRUE;
747 printprompt(0, NULL);
752 cleanup_until(&num_read);
757 ignored(const Char *item)
762 if ((vp = adrof(STRfignore)) == NULL || (cp = vp->vec) == NULL)
764 for (; *cp != NULL; cp++)
765 if (is_suffix(item, *cp))
769 #endif /* FILEC && TIOCSTI */