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