edit.c revision 1.3 1 /* $NetBSD: edit.c,v 1.3 1997/07/20 17:42:00 christos Exp $ */
2
3 /*
4 * Command line editing - common code
5 *
6 */
7
8 #include "config.h"
9 #ifdef EDIT
10
11 #include "sh.h"
12 #include "tty.h"
13 #define EXTERN
14 #include "edit.h"
15 #undef EXTERN
16 #ifdef OS_SCO /* SCO Unix 3.2v4.1 */
17 # include <sys/stream.h> /* needed for <sys/ptem.h> */
18 # include <sys/ptem.h> /* needed for struct winsize */
19 #endif /* OS_SCO */
20 #include <ctype.h>
21 #include <sys/ioctl.h>
22 #include "ksh_stat.h"
23
24
25 #if defined(TIOCGWINSZ)
26 static RETSIGTYPE x_sigwinch ARGS((int sig));
27 static int got_sigwinch;
28 static void check_sigwinch ARGS((void));
29 #endif /* TIOCGWINSZ */
30
31 static int x_file_glob ARGS((int flags, const char *str, int slen,
32 char ***wordsp));
33 static int x_command_glob ARGS((int flags, const char *str, int slen,
34 char ***wordsp));
35 static int x_locate_word ARGS((const char *buf, int buflen, int pos,
36 int *startp, int *is_command));
37 static int path_order_cmp ARGS((const void *, const void *));
38
39 static char vdisable_c;
40
41
42 /* Called from main */
43 void
44 x_init()
45 {
46 /* set to -1 to force initial binding */
47 edchars.erase = edchars.kill = edchars.intr = edchars.quit
48 = edchars.eof = -1;
49 /* default value for deficient systems */
50 edchars.werase = 027; /* ^W */
51
52 #ifdef TIOCGWINSZ
53 # ifdef SIGWINCH
54 if (setsig(&sigtraps[SIGWINCH], x_sigwinch, SS_RESTORE_ORIG|SS_SHTRAP))
55 sigtraps[SIGWINCH].flags |= TF_SHELL_USES;
56 # endif /* SIGWINCH */
57 got_sigwinch = 1; /* force initial check */
58 check_sigwinch();
59 #endif /* TIOCGWINSZ */
60
61 #ifdef EMACS
62 x_init_emacs();
63 #endif /* EMACS */
64
65 /* Bizarreness to figure out how to disable
66 * a struct termios.c_cc[] char
67 */
68 #ifdef _POSIX_VDISABLE
69 if (_POSIX_VDISABLE >= 0)
70 vdisable_c = (char) _POSIX_VDISABLE;
71 else
72 /* `feature not available' */
73 vdisable_c = (char) 0377;
74 #else
75 # if defined(HAVE_PATHCONF) && defined(_PC_VDISABLE)
76 vdisable_c = fpathconf(tty_fd, _PC_VDISABLE);
77 # else
78 vdisable_c = (char) 0377; /* default to old BSD value */
79 # endif
80 #endif /* _POSIX_VDISABLE */
81 }
82
83 #if defined(TIOCGWINSZ)
84 static RETSIGTYPE
85 x_sigwinch(sig)
86 int sig;
87 {
88 got_sigwinch = 1;
89 return RETSIGVAL;
90 }
91
92 static void
93 check_sigwinch ARGS((void))
94 {
95 if (got_sigwinch) {
96 struct winsize ws;
97
98 got_sigwinch = 0;
99 if (procpid == kshpid && ioctl(tty_fd, TIOCGWINSZ, &ws) >= 0) {
100 struct tbl *vp;
101
102 /* Do NOT export COLUMNS/LINES. Many applications
103 * check COLUMNS/LINES before checking ws.ws_col/row,
104 * so if the app is started with C/L in the environ
105 * and the window is then resized, the app won't
106 * see the change cause the environ doesn't change.
107 */
108 if (ws.ws_col) {
109 x_cols = ws.ws_col < MIN_COLS ? MIN_COLS
110 : ws.ws_col;
111
112 if ((vp = typeset("COLUMNS", 0, 0, 0, 0)))
113 setint(vp, (long) ws.ws_col);
114 }
115 if (ws.ws_row
116 && (vp = typeset("LINES", 0, 0, 0, 0)))
117 setint(vp, (long) ws.ws_row);
118 }
119 }
120 }
121 #endif /* TIOCGWINSZ */
122
123 /*
124 * read an edited command line
125 */
126 int
127 x_read(buf, len)
128 char *buf;
129 size_t len;
130 {
131 int i;
132
133 #if defined(TIOCGWINSZ)
134 if (got_sigwinch)
135 check_sigwinch();
136 #endif /* TIOCGWINSZ */
137
138 x_mode(TRUE);
139 #ifdef EMACS
140 if (Flag(FEMACS) || Flag(FGMACS))
141 i = x_emacs(buf, len);
142 else
143 #endif
144 #ifdef VI
145 if (Flag(FVI))
146 i = x_vi(buf, len);
147 else
148 #endif
149 i = -1; /* internal error */
150 x_mode(FALSE);
151 return i;
152 }
153
154 /* tty I/O */
155
156 int
157 x_getc()
158 {
159 #ifdef OS2
160 unsigned char c = _read_kbd(0, 1, 0);
161 return c == 0 ? 0xE0 : c;
162 #else /* OS2 */
163 char c;
164 int n;
165
166 while ((n = blocking_read(0, &c, 1)) < 0 && errno == EINTR)
167 if (trap) {
168 x_mode(FALSE);
169 runtraps(0);
170 x_mode(TRUE);
171 }
172 if (n != 1)
173 return -1;
174 return (int) (unsigned char) c;
175 #endif /* OS2 */
176 }
177
178 void
179 x_flush()
180 {
181 shf_flush(shl_out);
182 }
183
184 void
185 x_putc(c)
186 int c;
187 {
188 shf_putc(c, shl_out);
189 }
190
191 void
192 x_puts(s)
193 const char *s;
194 {
195 while (*s != 0)
196 shf_putc(*s++, shl_out);
197 }
198
199 bool_t
200 x_mode(onoff)
201 bool_t onoff;
202 {
203 static bool_t x_cur_mode;
204 bool_t prev;
205
206 if (x_cur_mode == onoff)
207 return x_cur_mode;
208 prev = x_cur_mode;
209 x_cur_mode = onoff;
210
211 if (onoff) {
212 TTY_state cb;
213 X_chars oldchars;
214
215 oldchars = edchars;
216 cb = tty_state;
217
218 #if defined(HAVE_TERMIOS_H) || defined(HAVE_TERMIO_H)
219 edchars.erase = cb.c_cc[VERASE];
220 edchars.kill = cb.c_cc[VKILL];
221 edchars.intr = cb.c_cc[VINTR];
222 edchars.quit = cb.c_cc[VQUIT];
223 edchars.eof = cb.c_cc[VEOF];
224 # ifdef VWERASE
225 edchars.werase = cb.c_cc[VWERASE];
226 # endif
227 # ifdef _CRAY2 /* brain-damaged terminal handler */
228 cb.c_lflag &= ~(ICANON|ECHO);
229 /* rely on print routine to map '\n' to CR,LF */
230 # else
231 cb.c_iflag &= ~(INLCR|ICRNL);
232 # ifdef _BSD_SYSV /* need to force CBREAK instead of RAW (need CRMOD on output) */
233 cb.c_lflag &= ~(ICANON|ECHO);
234 # else
235 # ifdef SWTCH /* need CBREAK to handle swtch char */
236 cb.c_lflag &= ~(ICANON|ECHO);
237 cb.c_lflag |= ISIG;
238 cb.c_cc[VINTR] = vdisable_c;
239 cb.c_cc[VQUIT] = vdisable_c;
240 # else
241 cb.c_lflag &= ~(ISIG|ICANON|ECHO);
242 # endif
243 # endif
244 # ifdef VLNEXT
245 /* osf/1 processes lnext when ~icanon */
246 cb.c_cc[VLNEXT] = vdisable_c;
247 # endif /* VLNEXT */
248 # ifdef VDISCARD
249 /* sunos 4.1.x & osf/1 processes discard(flush) when ~icanon */
250 cb.c_cc[VDISCARD] = vdisable_c;
251 # endif /* VDISCARD */
252 cb.c_cc[VTIME] = 0;
253 cb.c_cc[VMIN] = 1;
254 # endif /* _CRAY2 */
255 #else
256 /* Assume BSD tty stuff. */
257 edchars.erase = cb.sgttyb.sg_erase;
258 edchars.kill = cb.sgttyb.sg_kill;
259 cb.sgttyb.sg_flags &= ~ECHO;
260 cb.sgttyb.sg_flags |= CBREAK;
261 # ifdef TIOCGATC
262 edchars.intr = cb.lchars.tc_intrc;
263 edchars.quit = cb.lchars.tc_quitc;
264 edchars.eof = cb.lchars.tc_eofc;
265 edchars.werase = cb.lchars.tc_werasc;
266 cb.lchars.tc_suspc = -1;
267 cb.lchars.tc_dsuspc = -1;
268 cb.lchars.tc_lnextc = -1;
269 cb.lchars.tc_statc = -1;
270 cb.lchars.tc_intrc = -1;
271 cb.lchars.tc_quitc = -1;
272 cb.lchars.tc_rprntc = -1;
273 # else
274 edchars.intr = cb.tchars.t_intrc;
275 edchars.quit = cb.tchars.t_quitc;
276 edchars.eof = cb.tchars.t_eofc;
277 cb.tchars.t_intrc = -1;
278 cb.tchars.t_quitc = -1;
279 # ifdef TIOCGLTC
280 edchars.werase = cb.ltchars.t_werasc;
281 cb.ltchars.t_suspc = -1;
282 cb.ltchars.t_dsuspc = -1;
283 cb.ltchars.t_lnextc = -1;
284 cb.ltchars.t_rprntc = -1;
285 # endif
286 # endif /* TIOCGATC */
287 #endif /* HAVE_TERMIOS_H || HAVE_TERMIO_H */
288
289 set_tty(tty_fd, &cb, TF_WAIT);
290
291 if (memcmp(&edchars, &oldchars, sizeof(edchars)) != 0) {
292 #ifdef EMACS
293 x_emacs_keys(&edchars);
294 #endif
295 }
296 } else
297 /* TF_WAIT doesn't seem to be necessary when leaving xmode */
298 set_tty(tty_fd, &tty_state, TF_NONE);
299
300 return prev;
301 }
302
303 /* NAME:
304 * promptlen - calculate the length of PS1 etc.
305 *
306 * DESCRIPTION:
307 * This function is based on a fix from guy (at) demon.co.uk
308 * It fixes a bug in that if PS1 contains '!', the length
309 * given by strlen() is probably wrong.
310 *
311 * RETURN VALUE:
312 * length
313 */
314 int
315 promptlen(cp, spp)
316 const char *cp;
317 const char **spp;
318 {
319 int count = 0;
320 const char *sp = cp;
321 char delimiter = 0;
322 int indelimit = 0;
323
324 /* Undocumented AT&T ksh feature:
325 * If the second char in the prompt string is \r then the first char
326 * is taken to be a non-printing delimiter and any chars between two
327 * instances of the delimiter are not considered to be part of the
328 * prompt length
329 */
330 if (*cp && cp[1] == '\r') {
331 delimiter = *cp;
332 cp += 2;
333 }
334
335 for (; *cp; cp++) {
336 if (indelimit && *cp != delimiter)
337 ;
338 else if (*cp == '\n' || *cp == '\r') {
339 count = 0;
340 sp = cp + 1;
341 } else if (*cp == '\t') {
342 count = (count | 7) + 1;
343 } else if (*cp == '\b') {
344 if (count > 0)
345 count--;
346 } else if (*cp == delimiter)
347 indelimit = !indelimit;
348 else
349 count++;
350 }
351 if (spp)
352 *spp = sp;
353 return count;
354 }
355
356 void
357 set_editmode(ed)
358 const char *ed;
359 {
360 static const enum sh_flag edit_flags[] = {
361 #ifdef EMACS
362 FEMACS, FGMACS,
363 #endif
364 #ifdef VI
365 FVI,
366 #endif
367 };
368 char *rcp;
369 int i;
370
371 if ((rcp = ksh_strrchr_dirsep(ed)))
372 ed = ++rcp;
373 for (i = 0; i < NELEM(edit_flags); i++)
374 if (strstr(ed, options[(int) edit_flags[i]].name)) {
375 change_flag(edit_flags[i], OF_SPECIAL, 1);
376 return;
377 }
378 }
379
380 /* ------------------------------------------------------------------------- */
381 /* Misc common code for vi/emacs */
382
383 /* Handle the commenting/uncommenting of a line.
384 * Returns:
385 * 1 if a carriage return is indicated (comment added)
386 * 0 if no return (comment removed)
387 * -1 if there is an error (not enough room for comment chars)
388 * If successful, *lenp contains the new length. Note: cursor should be
389 * moved to the start of the line after (un)commenting.
390 */
391 int
392 x_do_comment(buf, bsize, lenp)
393 char *buf;
394 int bsize;
395 int *lenp;
396 {
397 int i, j;
398 int len = *lenp;
399
400 if (len == 0)
401 return 1; /* somewhat arbitrary - it's what at&t ksh does */
402
403 /* Already commented? */
404 if (buf[0] == '#') {
405 int saw_nl = 0;
406
407 for (j = 0, i = 1; i < len; i++) {
408 if (!saw_nl || buf[i] != '#')
409 buf[j++] = buf[i];
410 saw_nl = buf[i] == '\n';
411 }
412 *lenp = j;
413 return 0;
414 } else {
415 int n = 1;
416
417 /* See if there's room for the #'s - 1 per \n */
418 for (i = 0; i < len; i++)
419 if (buf[i] == '\n')
420 n++;
421 if (len + n >= bsize)
422 return -1;
423 /* Now add them... */
424 for (i = len, j = len + n; --i >= 0; ) {
425 if (buf[i] == '\n')
426 buf[--j] = '#';
427 buf[--j] = buf[i];
428 }
429 buf[0] = '#';
430 *lenp += n;
431 return 1;
432 }
433 }
434
435 /* ------------------------------------------------------------------------- */
436 /* Common file/command completion code for vi/emacs */
437
438
439 static char *add_glob ARGS((const char *str, int slen));
440 static void glob_table ARGS((const char *pat, XPtrV *wp, struct table *tp));
441 static void glob_path ARGS((int flags, const char *pat, XPtrV *wp,
442 const char *path));
443
444 #if 0 /* not used... */
445 int x_complete_word ARGS((const char *str, int slen, int is_command,
446 int *multiple, char **ret));
447 int
448 x_complete_word(str, slen, is_command, nwordsp, ret)
449 const char *str;
450 int slen;
451 int is_command;
452 int *nwordsp;
453 char **ret;
454 {
455 int nwords;
456 int prefix_len;
457 char **words;
458
459 nwords = (is_command ? x_command_glob : x_file_glob)(XCF_FULLPATH,
460 str, slen, &words);
461 *nwordsp = nwords;
462 if (nwords == 0) {
463 *ret = (char *) 0;
464 return -1;
465 }
466
467 prefix_len = x_longest_prefix(nwords, words);
468 *ret = str_nsave(words[0], prefix_len, ATEMP);
469 x_free_words(nwords, words);
470 return prefix_len;
471 }
472 #endif /* 0 */
473
474 void
475 x_print_expansions(nwords, words, is_command)
476 int nwords;
477 char *const *words;
478 int is_command;
479 {
480 int use_copy = 0;
481 int prefix_len;
482 XPtrV l;
483
484 /* Check if all matches are in the same directory (in this
485 * case, we want to omitt the directory name)
486 */
487 if (!is_command
488 && (prefix_len = x_longest_prefix(nwords, words)) > 0)
489 {
490 int i;
491
492 /* Special case for 1 match (prefix is whole word) */
493 if (nwords == 1)
494 prefix_len = x_basename(words[0], (char *) 0);
495 /* Any (non-trailing) slashes in non-common word suffixes? */
496 for (i = 0; i < nwords; i++)
497 if (x_basename(words[i] + prefix_len, (char *) 0)
498 > prefix_len)
499 break;
500 /* All in same directory? */
501 if (i == nwords) {
502 while (prefix_len > 0
503 && !ISDIRSEP(words[0][prefix_len - 1]))
504 prefix_len--;
505 use_copy = 1;
506 XPinit(l, nwords + 1);
507 for (i = 0; i < nwords; i++)
508 XPput(l, words[i] + prefix_len);
509 XPput(l, (char *) 0);
510 }
511 }
512
513 /*
514 * Enumerate expansions
515 */
516 x_putc('\r');
517 x_putc('\n');
518 pr_menu(use_copy ? (char **) XPptrv(l) : words);
519
520 if (use_copy)
521 XPfree(l); /* not x_free_words() */
522 }
523
524 /*
525 * Do file globbing:
526 * - appends * to (copy of) str if no globbing chars found
527 * - does expansion, checks for no match, etc.
528 * - sets *wordsp to array of matching strings
529 * - returns number of matching strings
530 */
531 static int
532 x_file_glob(flags, str, slen, wordsp)
533 int flags;
534 const char *str;
535 int slen;
536 char ***wordsp;
537 {
538 char *toglob;
539 char **words;
540 int nwords;
541 XPtrV w;
542 struct source *s, *sold;
543
544 if (slen < 0)
545 return 0;
546
547 toglob = add_glob(str, slen);
548
549 /*
550 * Convert "foo*" (toglob) to an array of strings (words)
551 */
552 sold = source;
553 s = pushs(SWSTR, ATEMP);
554 s->start = s->str = toglob;
555 source = s;
556 if (yylex(ONEWORD) != LWORD) {
557 source = sold;
558 internal_errorf(0, "fileglob: substitute error");
559 return 0;
560 }
561 source = sold;
562 XPinit(w, 32);
563 expand(yylval.cp, &w, DOGLOB|DOTILDE|DOMARKDIRS);
564 XPput(w, NULL);
565 words = (char **) XPclose(w);
566
567 for (nwords = 0; words[nwords]; nwords++)
568 ;
569 if (nwords == 1) {
570 struct stat statb;
571
572 /* Check if globbing failed (returned glob pattern),
573 * but be careful (E.g. toglob == "ab*" when the file
574 * "ab*" exists is not an error).
575 * Also, check for empty result - happens if we tried
576 * to glob something which evaluated to an empty
577 * string (e.g., "$FOO" when there is no FOO, etc).
578 */
579 if ((strcmp(words[0], toglob) == 0
580 && stat(words[0], &statb) < 0)
581 || words[0][0] == '\0')
582 {
583 x_free_words(nwords, words);
584 nwords = 0;
585 }
586 }
587 afree(toglob, ATEMP);
588
589 *wordsp = nwords ? words : (char **) 0;
590
591 return nwords;
592 }
593
594 /* Data structure used in x_command_glob() */
595 struct path_order_info {
596 char *word;
597 int base;
598 int path_order;
599 };
600
601 /* Compare routine used in x_command_glob() */
602 static int
603 path_order_cmp(aa, bb)
604 const void *aa;
605 const void *bb;
606 {
607 const struct path_order_info *a = (const struct path_order_info *) aa;
608 const struct path_order_info *b = (const struct path_order_info *) bb;
609 int t;
610
611 t = FILECMP(a->word + a->base, b->word + b->base);
612 return t ? t : a->path_order - b->path_order;
613 }
614
615 static int
616 x_command_glob(flags, str, slen, wordsp)
617 int flags;
618 const char *str;
619 int slen;
620 char ***wordsp;
621 {
622 char *toglob;
623 char *pat;
624 char *fpath;
625 int nwords;
626 XPtrV w;
627 struct block *l;
628
629 if (slen < 0)
630 return 0;
631
632 toglob = add_glob(str, slen);
633
634 /* Convert "foo*" (toglob) to a pattern for future use */
635 pat = evalstr(toglob, DOPAT|DOTILDE);
636 afree(toglob, ATEMP);
637
638 XPinit(w, 32);
639
640 glob_table(pat, &w, &keywords);
641 glob_table(pat, &w, &aliases);
642 glob_table(pat, &w, &builtins);
643 for (l = e->loc; l; l = l->next)
644 glob_table(pat, &w, &l->funs);
645
646 glob_path(flags, pat, &w, path);
647 if ((fpath = str_val(global("FPATH"))) != null)
648 glob_path(flags, pat, &w, fpath);
649
650 nwords = XPsize(w);
651
652 if (!nwords) {
653 *wordsp = (char **) 0;
654 XPfree(w);
655 return 0;
656 }
657
658 /* Sort entries */
659 if (flags & XCF_FULLPATH) {
660 /* Sort by basename, then path order */
661 struct path_order_info *info;
662 struct path_order_info *last_info = 0;
663 char **words = (char **) XPptrv(w);
664 int path_order = 0;
665 int i;
666
667 info = (struct path_order_info *)
668 alloc(sizeof(struct path_order_info) * nwords, ATEMP);
669 for (i = 0; i < nwords; i++) {
670 info[i].word = words[i];
671 info[i].base = x_basename(words[i], (char *) 0);
672 if (!last_info || info[i].base != last_info->base
673 || FILENCMP(words[i],
674 last_info->word, info[i].base) != 0)
675 {
676 last_info = &info[i];
677 path_order++;
678 }
679 info[i].path_order = path_order;
680 }
681 qsort(info, nwords, sizeof(struct path_order_info),
682 path_order_cmp);
683 for (i = 0; i < nwords; i++)
684 words[i] = info[i].word;
685 afree((void *) info, ATEMP);
686 } else {
687 /* Sort and remove duplicate entries */
688 char **words = (char **) XPptrv(w);
689 int i, j;
690
691 qsortp(XPptrv(w), (size_t) nwords, xstrcmp);
692
693 for (i = j = 0; i < nwords - 1; i++) {
694 if (strcmp(words[i], words[i + 1]))
695 words[j++] = words[i];
696 else
697 afree(words[i], ATEMP);
698 }
699 words[j++] = words[i];
700 nwords = j;
701 w.cur = (void **) &words[j];
702 }
703
704 XPput(w, NULL);
705 *wordsp = (char **) XPclose(w);
706
707 return nwords;
708 }
709
710 #define IS_WORDC(c) !isspace(c)
711
712 static int
713 x_locate_word(buf, buflen, pos, startp, is_commandp)
714 const char *buf;
715 int buflen;
716 int pos;
717 int *startp;
718 int *is_commandp;
719 {
720 int p;
721 int start, end;
722
723 /* Bad call? Probably should report error */
724 if (pos < 0 || pos > buflen) {
725 *startp = pos;
726 *is_commandp = 0;
727 return 0;
728 }
729
730 if (pos == buflen) {
731 if (pos == 0) { /* empty buffer? */
732 *startp = pos;
733 *is_commandp = 1;
734 return 0;
735 }
736 pos--;
737 }
738
739 start = pos;
740 /* Keep going backwards to start of word (has effect of allowing
741 * one blank after the end of a word)
742 */
743 for (; start > 0 && IS_WORDC(buf[start - 1]); start--)
744 ;
745 /* Go forwards to end of word */
746 for (end = start; end < buflen && IS_WORDC(buf[end]); end++)
747 ;
748
749 if (is_commandp) {
750 int iscmd;
751
752 /* Figure out if this is a command */
753 for (p = start - 1; p >= 0 && isspace(buf[p]); p--)
754 ;
755 iscmd = p < 0 || strchr(";|&()", buf[p]);
756 if (iscmd) {
757 /* If command has a /, path, etc. is not searched;
758 * only current directory is searched, which is just
759 * like file globbing.
760 */
761 for (p = start; p < end; p++)
762 if (ISDIRSEP(buf[p]))
763 break;
764 iscmd = p == end;
765 }
766 *is_commandp = iscmd;
767 }
768
769 *startp = start;
770
771 return end - start;
772 }
773
774 int
775 x_cf_glob(flags, buf, buflen, pos, startp, endp, wordsp, is_commandp)
776 int flags;
777 const char *buf;
778 int buflen;
779 int pos;
780 int *startp;
781 int *endp;
782 char ***wordsp;
783 int *is_commandp;
784 {
785 int len;
786 int nwords;
787 char **words;
788 int is_command;
789
790 len = x_locate_word(buf, buflen, pos, startp, &is_command);
791 if (!(flags & XCF_COMMAND))
792 is_command = 0;
793 /* Don't do command globing on zero length strings - it takes too
794 * long and isn't very useful. File globs are more likely to be
795 * useful, so allow these.
796 */
797 if (len == 0 && is_command)
798 return 0;
799
800 nwords = (is_command ? x_command_glob : x_file_glob)(flags,
801 buf + *startp, len, &words);
802 if (nwords == 0) {
803 *wordsp = (char **) 0;
804 return 0;
805 }
806
807 if (is_commandp)
808 *is_commandp = is_command;
809 *wordsp = words;
810 *endp = *startp + len;
811
812 return nwords;
813 }
814
815 /* Given a string, copy it and possibly add a '*' to the end. The
816 * new string is returned.
817 */
818 static char *
819 add_glob(str, slen)
820 const char *str;
821 int slen;
822 {
823 char *toglob;
824 char *s;
825 bool_t saw_slash = FALSE;
826
827 if (slen < 0)
828 return (char *) 0;
829
830 toglob = str_nsave(str, slen + 1, ATEMP); /* + 1 for "*" */
831 toglob[slen] = '\0';
832
833 /*
834 * If the pathname contains a wildcard (an unquoted '*',
835 * '?', or '[') or parameter expansion ('$'), or a ~username
836 * with no trailing slash, then it is globbed based on that
837 * value (i.e., without the appended '*').
838 */
839 for (s = toglob; *s; s++) {
840 if (*s == '\\' && s[1])
841 s++;
842 else if (*s == '*' || *s == '[' || *s == '?' || *s == '$'
843 || (s[1] == '(' /*)*/ && strchr("*+?@!", *s)))
844 break;
845 else if (ISDIRSEP(*s))
846 saw_slash = TRUE;
847 }
848 if (!*s && (*toglob != '~' || saw_slash)) {
849 toglob[slen] = '*';
850 toglob[slen + 1] = '\0';
851 }
852
853 return toglob;
854 }
855
856 /*
857 * Find longest common prefix
858 */
859 int
860 x_longest_prefix(nwords, words)
861 int nwords;
862 char *const *words;
863 {
864 int i, j;
865 int prefix_len;
866 char *p;
867
868 if (nwords <= 0)
869 return 0;
870
871 prefix_len = strlen(words[0]);
872 for (i = 1; i < nwords; i++)
873 for (j = 0, p = words[i]; j < prefix_len; j++)
874 if (FILECHCONV(p[j]) != FILECHCONV(words[0][j])) {
875 prefix_len = j;
876 break;
877 }
878 return prefix_len;
879 }
880
881 void
882 x_free_words(nwords, words)
883 int nwords;
884 char **words;
885 {
886 int i;
887
888 for (i = 0; i < nwords; i++)
889 if (words[i])
890 afree(words[i], ATEMP);
891 afree(words, ATEMP);
892 }
893
894 /* Return the offset of the basename of string s (which ends at se - need not
895 * be null terminated). Trailing slashes are ignored. If s is just a slash,
896 * then the offset is 0 (actually, length - 1).
897 * s Return
898 * /etc 1
899 * /etc/ 1
900 * /etc// 1
901 * /etc/fo 5
902 * foo 0
903 * /// 2
904 * 0
905 */
906 int
907 x_basename(s, se)
908 const char *s;
909 const char *se;
910 {
911 const char *p;
912
913 if (se == (char *) 0)
914 se = s + strlen(s);
915 if (s == se)
916 return 0;
917
918 /* Skip trailing slashes */
919 for (p = se - 1; p > s && ISDIRSEP(*p); p--)
920 ;
921 for (; p > s && !ISDIRSEP(*p); p--)
922 ;
923 if (ISDIRSEP(*p) && p + 1 < se)
924 p++;
925
926 return p - s;
927 }
928
929 /*
930 * Apply pattern matching to a table: all table entries that match a pattern
931 * are added to wp.
932 */
933 static void
934 glob_table(pat, wp, tp)
935 const char *pat;
936 XPtrV *wp;
937 struct table *tp;
938 {
939 struct tstate ts;
940 struct tbl *te;
941
942 for (twalk(&ts, tp); (te = tnext(&ts)); ) {
943 if (gmatch(te->name, pat, FALSE))
944 XPput(*wp, str_save(te->name, ATEMP));
945 }
946 }
947
948 static void
949 glob_path(flags, pat, wp, path)
950 int flags;
951 const char *pat;
952 XPtrV *wp;
953 const char *path;
954 {
955 const char *sp, *p;
956 char *xp;
957 int pathlen;
958 int patlen;
959 int oldsize, newsize, i, j;
960 char **words;
961 XString xs;
962
963 patlen = strlen(pat) + 1;
964 sp = path;
965 Xinit(xs, xp, patlen + 128, ATEMP);
966 while (sp) {
967 xp = Xstring(xs, xp);
968 if (!(p = strchr(sp, PATHSEP)))
969 p = sp + strlen(sp);
970 pathlen = p - sp;
971 if (pathlen) {
972 /* Copy sp into xp, stuffing any MAGIC characters
973 * on the way
974 */
975 const char *s = sp;
976
977 XcheckN(xs, xp, pathlen * 2);
978 while (s < p) {
979 if (ISMAGIC(*s))
980 *xp++ = MAGIC;
981 *xp++ = *s++;
982 }
983 *xp++ = DIRSEP;
984 pathlen++;
985 }
986 sp = p;
987 XcheckN(xs, xp, patlen);
988 memcpy(xp, pat, patlen);
989
990 oldsize = XPsize(*wp);
991 glob_str(Xstring(xs, xp), wp, 0);
992 newsize = XPsize(*wp);
993
994 /* Check that each match is executable... */
995 words = (char **) XPptrv(*wp);
996 for (i = j = oldsize; i < newsize; i++) {
997 if (search_access(words[i], X_OK, (int *) 0) >= 0) {
998 words[j] = words[i];
999 if (!(flags & XCF_FULLPATH))
1000 memmove(words[j], words[j] + pathlen,
1001 strlen(words[j] + pathlen) + 1);
1002 j++;
1003 } else
1004 afree(words[i], ATEMP);
1005 }
1006 wp->cur = (void **) &words[j];
1007
1008 if (!*sp++)
1009 break;
1010 }
1011 Xfree(xs, xp);
1012 }
1013
1014 #endif /* EDIT */
1015