2 * sh.file.c: File completion for csh. This file is not used in tcsh.
5 * Copyright (c) 1980, 1991 The Regents of the University of California.
8 * Redistribution and use in source and binary forms, with or without
9 * modification, are permitted provided that the following conditions
11 * 1. Redistributions of source code must retain the above copyright
12 * notice, this list of conditions and the following disclaimer.
13 * 2. Redistributions in binary form must reproduce the above copyright
14 * notice, this list of conditions and the following disclaimer in the
15 * documentation and/or other materials provided with the distribution.
16 * 3. Neither the name of the University nor the names of its contributors
17 * may be used to endorse or promote products derived from this software
18 * without specific prior written permission.
20 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
21 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
22 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
23 * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
24 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
25 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
26 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
27 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
28 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
29 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
35 #if defined(FILEC) && defined(TIOCSTI)
38 * Tenex style file name recognition, .. and more.
40 * Author: Ken Greer, Sept. 1975, CMU.
41 * Finally got around to adding to the Cshell., Ken Greer, Dec. 1981.
53 #define ESC CTL_ESC('\033')
59 static void setup_tty (int);
60 static void back_to_col_1 (void);
61 static void pushback (const Char *);
62 static int filetype (const Char *, const Char *);
63 static void print_by_column (const Char *, Char *[], size_t);
64 static Char *tilde (const Char *);
65 static void retype (void);
66 static void beep (void);
67 static void print_recognized_stuff (const Char *);
68 static void extract_dir_and_name (const Char *, Char **, const Char **);
69 static Char *getitem (DIR *, int);
70 static size_t tsearch (Char *, COMMAND, size_t);
71 static int compare (const void *, const void *);
72 static int recognize (Char **, Char *, size_t, size_t);
73 static int is_prefix (const Char *, const Char *);
74 static int is_suffix (const Char *, const Char *);
75 static int ignored (const Char *);
79 * Put this here so the binary can be patched with adb to enable file
80 * completion by default. Filec controls completion, nobeep controls
81 * ringing the terminal bell on incomplete expansions.
90 struct termios tchars;
96 (void) tcgetattr(SHIN, &tchars);
98 (void) ioctl(SHIN, TCGETA, (ioctl_t) &tchars);
101 tchars.c_cc[VEOL] = ESC;
102 if (tchars.c_lflag & ICANON)
114 tchars.c_lflag |= ICANON;
119 tchars.c_cc[VEOL] = _POSIX_VDISABLE;
127 (void) xtcsetattr(SHIN, on, &tchars);
129 (void) ioctl(SHIN, on, (ioctl_t) &tchars);
133 static struct tchars tchars;/* INT, QUIT, XON, XOFF, EOF, BRK */
136 (void) ioctl(SHIN, TIOCGETC, (ioctl_t) & tchars);
138 (void) ioctl(SHIN, TIOCSETC, (ioctl_t) & tchars);
140 * This must be done after every command: if the tty gets into raw or
141 * cbreak mode the user can't even type 'reset'.
143 (void) ioctl(SHIN, TIOCGETP, (ioctl_t) & sgtty);
144 if (sgtty.sg_flags & (RAW | CBREAK)) {
145 sgtty.sg_flags &= ~(RAW | CBREAK);
146 (void) ioctl(SHIN, TIOCSETP, (ioctl_t) & sgtty);
151 (void) ioctl(SHIN, TIOCSETC, (ioctl_t) & tchars);
157 * Move back to beginning of current line
164 struct termios tty, tty_normal;
166 struct termio tty, tty_normal;
169 struct sgttyb tty, tty_normal;
173 cleanup_push(&pintr_disabled, disabled_cleanup);
177 (void) tcgetattr(SHOUT, &tty);
179 (void) ioctl(SHOUT, TCGETA, (ioctl_t) &tty_normal);
182 tty.c_iflag &= ~INLCR;
183 tty.c_oflag &= ~ONLCR;
185 (void) xtcsetattr(SHOUT, TCSANOW, &tty);
187 (void) ioctl(SHOUT, TCSETAW, (ioctl_t) &tty);
189 (void) xwrite(SHOUT, "\r", 1);
191 (void) xtcsetattr(SHOUT, TCSANOW, &tty_normal);
193 (void) ioctl(SHOUT, TCSETAW, (ioctl_t) &tty_normal);
196 (void) ioctl(SHIN, TIOCGETP, (ioctl_t) & tty);
198 tty.sg_flags &= ~CRMOD;
199 (void) ioctl(SHIN, TIOCSETN, (ioctl_t) & tty);
200 (void) xwrite(SHOUT, "\r", 1);
201 (void) ioctl(SHIN, TIOCSETN, (ioctl_t) & tty_normal);
204 cleanup_until(&pintr_disabled);
208 * Push string contents back into tty queue
211 pushback(const Char *string)
216 struct termios tty, tty_normal;
218 struct termio tty, tty_normal;
221 struct sgttyb tty, tty_normal;
225 cleanup_push(&pintr_disabled, disabled_cleanup);
229 (void) tcgetattr(SHOUT, &tty);
231 (void) ioctl(SHOUT, TCGETA, (ioctl_t) &tty);
234 tty.c_lflag &= ~(ECHOKE | ECHO | ECHOE | ECHOK | ECHONL |
240 (void) xtcsetattr(SHOUT, TCSANOW, &tty);
242 (void) ioctl(SHOUT, TCSETAW, (ioctl_t) &tty);
245 for (p = string; *p != '\0'; p++) {
246 char buf[MB_LEN_MAX];
249 len = one_wctomb(buf, *p);
250 for (i = 0; i < len; i++)
251 (void) ioctl(SHOUT, TIOCSTI, (ioctl_t) &buf[i]);
254 (void) xtcsetattr(SHOUT, TCSANOW, &tty_normal);
256 (void) ioctl(SHOUT, TCSETAW, (ioctl_t) &tty_normal);
259 (void) ioctl(SHOUT, TIOCGETP, (ioctl_t) & tty);
261 tty.sg_flags &= ~ECHO;
262 (void) ioctl(SHOUT, TIOCSETN, (ioctl_t) & tty);
264 for (p = string; c = *p; p++)
265 (void) ioctl(SHOUT, TIOCSTI, (ioctl_t) & c);
266 (void) ioctl(SHOUT, TIOCSETN, (ioctl_t) & tty_normal);
269 cleanup_until(&pintr_disabled);
273 filetype(const Char *dir, const Char *file)
279 path = Strspl(dir, file);
280 spath = short2str(path);
282 if (lstat(spath, &statb) == 0) {
283 switch (statb.st_mode & S_IFMT) {
288 if (stat(spath, &statb) == 0 && /* follow it out */
289 S_ISDIR(statb.st_mode))
298 if (statb.st_mode & 0111)
306 * Print sorted down columns
309 print_by_column(const Char *dir, Char *items[], size_t count)
313 int rows, r, c, maxwidth = 0, columns;
315 if (ioctl(SHOUT, TIOCGWINSZ, (ioctl_t) & win) < 0 || win.ws_col == 0)
317 for (i = 0; i < count; i++)
318 maxwidth = maxwidth > (r = Strlen(items[i])) ? maxwidth : r;
319 maxwidth += 2; /* for the file tag and space */
320 columns = win.ws_col / maxwidth;
323 rows = (count + (columns - 1)) / columns;
324 for (r = 0; r < rows; r++) {
325 for (c = 0; c < columns; c++) {
330 xprintf("%S", items[i]);
331 xputchar(dir ? filetype(dir, items[i]) : ' ');
332 if (c < columns - 1) { /* last column? */
333 w = Strlen(items[i]) + 1;
334 for (; w < maxwidth; w++)
345 * Expand file name with possible tilde usage
348 * home_directory_of_person/mumble
351 tilde(const Char *old)
353 const Char *o, *home;
357 return (Strsave(old));
360 for (o = old; *o != '\0' && *o != '/'; o++)
363 home = varval(STRhome);
367 person = Strnsave(old, o - old);
368 pw = xgetpwnam(short2str(person));
372 home = str2short(pw->pw_dir);
374 return Strspl(home, o);
378 * Cause pending line to be printed
387 (void) tcgetattr(SHOUT, &tty);
391 (void) ioctl(SHOUT, TCGETA, (ioctl_t) &tty);
395 tty.c_lflag |= PENDIN;
399 (void) xtcsetattr(SHOUT, TCSANOW, &tty);
401 (void) ioctl(SHOUT, TCSETAW, (ioctl_t) &tty);
404 int pending_input = LPENDIN;
406 (void) ioctl(SHOUT, TIOCLBIS, (ioctl_t) & pending_input);
413 if (adrof(STRnobeep) == 0)
415 (void) xwrite(SHOUT, "\007", 1);
418 unsigned char beep_ch = CTL_ESC('\007');
419 (void) xwrite(SHOUT, &beep_ch, 1);
425 * Erase that silly ^[ and
426 * print the recognized part of the string
429 print_recognized_stuff(const Char *recognized_part)
431 /* An optimized erasing of that silly ^[ */
434 switch (Strlen(recognized_part)) {
436 case 0: /* erase two Characters: ^[ */
443 case 1: /* overstrike the ^, erase the [ */
444 xprintf("%S", recognized_part);
449 default: /* overstrike both Characters ^[ */
450 xprintf("%S", recognized_part);
457 * Parse full path in file into 2 parts: directory and file names
458 * Should leave final slash (/) at end of dir.
461 extract_dir_and_name(const Char *path, Char **dir, const Char **name)
465 p = Strrchr(path, '/');
471 *dir = Strnsave(path, p - path);
475 getitem(DIR *dir_fd, int looking_for_lognames)
480 if (looking_for_lognames) {
481 #ifndef HAVE_GETPWENT
484 if ((pw = getpwent()) == NULL)
486 return (str2short(pw->pw_name));
487 #endif /* atp vmsposix */
489 if ((dirp = readdir(dir_fd)) != NULL)
490 return (str2short(dirp->d_name));
495 * Perform a RECOGNIZE or LIST command on string "word".
498 tsearch(Char *word, COMMAND command, size_t max_word_length)
501 int ignoring = TRUE, nignored = 0;
502 int looking_for_lognames;
503 Char *tilded_dir = NULL, *dir = NULL;
504 Char *extended_name = NULL;
507 struct blk_buf items = BLK_BUF_INIT;
510 looking_for_lognames = (*word == '~') && (Strchr(word, '/') == NULL);
511 if (looking_for_lognames) {
515 name = word + 1; /* name sans ~ */
517 cleanup_push(dir, xfree);
520 extract_dir_and_name(word, &dir, &name);
521 cleanup_push(dir, xfree);
522 tilded_dir = tilde(dir);
523 if (tilded_dir == NULL)
525 cleanup_push(tilded_dir, xfree);
526 dir_fd = opendir(*tilded_dir ? short2str(tilded_dir) : ".");
531 name_length = Strlen(name);
532 cleanup_push(&extended_name, xfree_indirect);
533 cleanup_push(&items, bb_cleanup);
534 again: /* search for matches */
535 while ((item = getitem(dir_fd, looking_for_lognames)) != NULL) {
536 if (!is_prefix(name, item))
538 /* Don't match . files on null prefix match */
539 if (name_length == 0 && item[0] == '.' &&
540 !looking_for_lognames)
543 bb_append(&items, Strsave(item));
544 else { /* RECOGNIZE command */
545 if (ignoring && ignored(item))
547 else if (recognize(&extended_name, item, name_length, ++items.len))
551 if (ignoring && items.len == 0 && nignored > 0) {
554 if (looking_for_lognames) {
557 #endif /* atp vmsposix */
563 if (looking_for_lognames) {
569 if (items.len != 0) {
570 if (command == RECOGNIZE) {
571 if (looking_for_lognames)
572 copyn(word, STRtilde, 2);/*FIXBUF, sort of */
574 /* put back dir part */
575 copyn(word, dir, max_word_length);/*FIXBUF*/
576 /* add extended name */
577 catn(word, extended_name, max_word_length);/*FIXBUF*/
580 qsort(items.vec, items.len, sizeof(items.vec[0]), compare);
581 print_by_column(looking_for_lognames ? NULL : tilded_dir,
582 items.vec, items.len);
592 compare(const void *p, const void *q)
594 #if defined (WIDE_STRINGS) && !defined (UTF16_STRING)
597 return (wcscoll(*(Char *const *) p, *(Char *const *) q));
602 p1 = strsave(short2str(*(Char *const *) p));
603 q1 = strsave(short2str(*(Char *const *) q));
604 # if defined(NLS) && defined(HAVE_STRCOLL)
605 res = strcoll(p1, q1);
607 res = strcmp(p1, q1);
608 # endif /* NLS && HAVE_STRCOLL */
612 #endif /* not WIDE_STRINGS */
616 * Object: extend what user typed up to an ambiguity.
618 * On first match, copy full item (assume it'll be the only match)
619 * On subsequent matches, shorten extended_name to the first
620 * Character mismatch between extended_name and item.
621 * If we shorten it back to the prefix length, stop searching.
624 recognize(Char **extended_name, Char *item, size_t name_length,
627 if (numitems == 1) /* 1st match */
628 *extended_name = Strsave(item);
629 else { /* 2nd & subsequent matches */
634 for (ent = item; *x && *x == *ent++; x++, len++);
635 *x = '\0'; /* Shorten at 1st Char diff */
636 if (len == name_length) /* Ambiguous to prefix? */
637 return (-1); /* So stop now and save time */
643 * Return true if check matches initial Chars in template.
644 * This differs from PWB imatch in that if check is null
645 * it matches anything.
648 is_prefix(const Char *check, const Char *template)
653 while (*check++ == *template++);
658 * Return true if the Chars in template appear at the
659 * end of check, I.e., are it's suffix.
662 is_suffix(const Char *check, const Char *template)
666 for (c = check; *c++;);
667 for (t = template; *t++;);
671 if (c == check || *--t != *--c)
677 setup_tty_cleanup(void *dummy)
684 tenex(Char *inputline, size_t inputline_size)
688 char tinputline[BUFSIZE + 1];/*FIXBUF*/
691 cleanup_push(&num_read, setup_tty_cleanup); /* num_read is only a marker */
693 while ((num_read = xread(SHIN, tinputline, BUFSIZE)) > 0) {/*FIXBUF*/
694 static const Char delims[] = {' ', '\'', '"', '\t', ';', '&', '<',
695 '>', '(', ')', '|', '^', '%', '\0'};
696 Char *str_end, *word_start, last_Char, should_retype;
700 tinputline[num_read] = 0;
701 Strcpy(inputline, str2short(tinputline));/*FIXBUF*/
702 num_read = Strlen(inputline);
703 last_Char = CTL_ESC(ASC(inputline[num_read - 1]) & ASCII);
705 if (last_Char == '\n' || (size_t)num_read == inputline_size)
707 command = (last_Char == ESC) ? RECOGNIZE : LIST;
710 str_end = &inputline[num_read];
711 if (last_Char == ESC)
712 --str_end; /* wipeout trailing cmd Char */
715 * Find LAST occurence of a delimiter in the inputline. The word start
716 * is one Character past it.
718 for (word_start = str_end; word_start > inputline; --word_start)
719 if (Strchr(delims, word_start[-1]))
721 space_left = inputline_size - (word_start - inputline) - 1;
722 numitems = tsearch(word_start, command, space_left);
724 if (command == RECOGNIZE) {
725 /* print from str_end on */
726 print_recognized_stuff(str_end);
727 if (numitems != 1) /* Beep = No match/ambiguous */
732 * Tabs in the input line cause trouble after a pushback. tty driver
733 * won't backspace over them because column positions are now
734 * incorrect. This is solved by retyping over current line.
736 should_retype = FALSE;
737 if (Strchr(inputline, '\t')) { /* tab Char in input line? */
739 should_retype = TRUE;
741 if (command == LIST) /* Always retype after a LIST */
742 should_retype = TRUE;
744 printprompt(0, NULL);
749 cleanup_until(&num_read);
754 ignored(const Char *item)
759 if ((vp = adrof(STRfignore)) == NULL || (cp = vp->vec) == NULL)
761 for (; *cp != NULL; cp++)
762 if (is_suffix(item, *cp))
766 #endif /* FILEC && TIOCSTI */