-
-
Notifications
You must be signed in to change notification settings - Fork 0
/
edit.c
5902 lines (5367 loc) · 120 KB
/
edit.c
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/* $OpenBSD: edit.c,v 1.41 2015/09/01 13:12:31 tedu Exp $ */
/* $OpenBSD: edit.h,v 1.9 2011/05/30 17:14:35 martynas Exp $ */
/* $OpenBSD: emacs.c,v 1.52 2015/09/10 22:48:58 nicm Exp $ */
/* $OpenBSD: vi.c,v 1.30 2015/09/10 22:48:58 nicm Exp $ */
/*-
* Copyright (c) 2003, 2004, 2005, 2006, 2007, 2008, 2009, 2010,
* 2011, 2012, 2013, 2014, 2015, 2016, 2017, 2018,
* 2019, 2020, 2021, 2022
* mirabilos <[email protected]>
*
* Provided that these terms and disclaimer and all copyright notices
* are retained or reproduced in an accompanying document, permission
* is granted to deal in this work without restriction, including un-
* limited rights to use, publicly perform, distribute, sell, modify,
* merge, give away, or sublicence.
*
* This work is provided "AS IS" and WITHOUT WARRANTY of any kind, to
* the utmost extent permitted by applicable law, neither express nor
* implied; without malicious intent or gross negligence. In no event
* may a licensor, author or contributor be held liable for indirect,
* direct, other damage, loss, or other issues arising in any way out
* of dealing in the work, even if advised of the possibility of such
* damage or existence of a defect, except proven that it results out
* of said person's immediate fault when using the work as intended.
*/
#include "sh.h"
#ifndef MKSH_NO_CMDLINE_EDITING
__RCSID("$MirOS: src/bin/mksh/edit.c,v 1.400 2022/12/01 23:55:29 tg Exp $");
/*
* in later versions we might use libtermcap for this, but since external
* dependencies are problematic, this has not yet been decided on; another
* good string is KSH_ESC_STRING "c" except on hardware terminals like the
* DEC VT420 which do a full power cycle then...
*/
#ifndef MKSH_CLS_STRING
#define MKSH_CLS_STRING KSH_ESC_STRING "[;H" KSH_ESC_STRING "[J"
#endif
#if !defined(MKSH_SMALL) || !MKSH_S_NOVI
static const char ctrl_x_e[] = "fc -e \"${VISUAL:-${EDITOR:-vi}}\" --";
#endif
/* tty driver characters we are interested in */
#define EDCHAR_DISABLED 0xFFFFU
#define EDCHAR_INITIAL 0xFFFEU
static struct {
unsigned short erase;
unsigned short kill;
unsigned short werase;
unsigned short intr;
unsigned short quit;
unsigned short eof;
} edchars;
#define isched(x,e) ((unsigned short)(unsigned char)(x) == (e))
#define isedchar(x) (!((x) & ~0xFFU))
#define toedchar(x) ((unsigned short)KSH_ISVDIS(x, EDCHAR_DISABLED))
/* x_cf_glob() flags */
#define XCF_COMMAND BIT(0) /* Do command completion */
#define XCF_FILE BIT(1) /* Do file completion */
#define XCF_FULLPATH BIT(2) /* command completion: store full path */
#define XCF_COMMAND_FILE (XCF_COMMAND | XCF_FILE)
#define XCF_IS_COMMAND BIT(3) /* return flag: is command */
#define XCF_IS_NOSPACE BIT(4) /* return flag: do not append a space */
#define XCF_IS_HOMEDIR BIT(5) /* return flag: tilde needs slash */
static char editmode;
static int xx_cols; /* for Emacs mode */
static int modified; /* buffer has been "modified" */
static char *holdbufp; /* place to hold last edit buffer */
/* 0=dumb 1=tmux (for now) */
static kby x_term_mode;
static void x_adjust(void);
static int x_getc(void);
static void x_putcf(int);
static void x_modified(void);
static void x_mode(Wahr);
static int x_do_comment(char *, ssize_t, ssize_t *);
static void x_print_expansions(int, char * const *, Wahr);
static int x_cf_glob(int *, const char *, int, int, int *, int *, char ***);
static size_t x_longest_prefix(int, char * const *);
static char *x_glob_hlp_add_qchar(char *);
static char *x_glob_hlp_tilde_and_rem_qchar(char *, Wahr);
static size_t x_basename(const char *, const char *);
static void x_free_words(int, char **);
static int x_escape(const char *, size_t, int (*)(const char *, size_t));
static ssize_t x_emacs(char *);
#ifdef DF
static void x_emacs_DF(const char *);
#endif
static void x_init_prompt(Wahr);
#if !MKSH_S_NOVI
static ssize_t x_vi(char *);
#endif
static void x_intr(int, int) MKSH_A_NORETURN;
static void x_clrtoeol(int, Wahr);
#define x_flush() shf_flush(shl_out)
#if defined(MKSH_SMALL) && !defined(MKSH_SMALL_BUT_FAST)
#define x_putc(c) x_putcf(c)
#else
#define x_putc(c) shf_putc((c), shl_out)
#endif
static int path_order_cmp(const void *, const void *);
static void glob_table(const char *, XPtrV *, struct table *);
static void glob_path(int, const char *, XPtrV *, const char *);
static int x_file_glob(int *, char *, char ***);
static int x_command_glob(int, char *, char ***);
static int x_locate_word(const char *, int, int, int *, Wahr *);
static int x_e_getmbc(char *);
/* +++ generic editing functions +++ */
/*
* read an edited command line
*/
char *
x_read(char *buf)
{
ssize_t i;
x_mode(Ja);
modified = 1;
if (Flag(FEMACS) || Flag(FGMACS))
i = x_emacs(buf);
#if !MKSH_S_NOVI
else if (Flag(FVI))
i = x_vi(buf);
#endif
else
/* internal error */
i = -1;
editmode = 0;
x_mode(Nee);
if (i < 0) {
/* pdksh had no error handling here, just return null */
return (buf);
}
buf += i;
return (buf);
}
/* tty I/O */
static int
x_getc(void)
{
#ifdef __OS2__
return (_read_kbd(0, 1, 0));
#else
char c;
ssize_t n;
while ((n = blocking_read(0, &c, 1)) < 0 && errno == EINTR)
if (trap) {
x_mode(Nee);
runtraps(0);
#ifdef SIGWINCH
if (got_winch) {
change_winsz();
if (x_cols != xx_cols && editmode == 1) {
/* redraw line in Emacs mode */
xx_cols = x_cols;
x_init_prompt(Nee);
x_adjust();
}
}
#endif
x_mode(Ja);
}
return ((n == 1) ? (int)(unsigned char)c : -1);
#endif
}
static void
x_putcf(int c)
{
shf_putc_i(c, shl_out);
}
/*********************************
* Misc common code for vi/emacs *
*********************************/
/*-
* Handle the commenting/uncommenting of a line.
* Returns:
* 1 if a carriage return is indicated (comment added)
* 0 if no return (comment removed)
* -1 if there is an error (not enough room for comment chars)
* If successful, *lenp contains the new length. Note: cursor should be
* moved to the start of the line after (un)commenting.
*/
static int
x_do_comment(char *buf, ssize_t bsize, ssize_t *lenp)
{
ssize_t i, j, len = *lenp;
if (len == 0)
/* somewhat arbitrary - it's what AT&T ksh does */
return (1);
/* Already commented? */
if (buf[0] == '#') {
Wahr saw_nl = Nee;
for (j = 0, i = 1; i < len; i++) {
if (!saw_nl || buf[i] != '#')
buf[j++] = buf[i];
saw_nl = buf[i] == '\n';
}
*lenp = j;
return (0);
} else {
int n = 1;
/* See if there's room for the #s - 1 per \n */
for (i = 0; i < len; i++)
if (buf[i] == '\n')
n++;
if (len + n >= bsize)
return (-1);
/* Now add them... */
for (i = len, j = len + n; --i >= 0; ) {
if (buf[i] == '\n')
buf[--j] = '#';
buf[--j] = buf[i];
}
buf[0] = '#';
*lenp += n;
return (1);
}
}
/****************************************************
* Common file/command completion code for vi/emacs *
****************************************************/
static void
x_print_expansions(int nwords, char * const *words, Wahr is_command)
{
int i;
char **w;
size_t prefix_len = 0;
Wahr prefix_trim = Nee;
struct columnise_opts co;
struct shf S;
/*
* Check if all matches are in the same directory (in this
* case, we want to omit the directory name)
*/
if (!is_command &&
(prefix_len = x_longest_prefix(nwords, words)) > 0) {
/* Special case for 1 match (prefix is whole word) */
if (nwords == 1)
prefix_len = x_basename(words[0], NULL);
/* Any (non-trailing) slashes in non-common word suffixes? */
for (i = 0; i < nwords; i++)
if (x_basename(words[i] + prefix_len, NULL) >
prefix_len)
break;
/* All in same directory? */
if (i == nwords) {
while (prefix_len > 0 &&
!mksh_cdirsep(words[0][prefix_len - 1]))
prefix_len--;
prefix_trim = Ja;
}
}
/*
* Escape words, trimming prefix_len if needed
*/
if (!prefix_trim)
prefix_len = 0;
w = alloc2((kui)nwords + 1U, sizeof(char *), ATEMP);
for (i = 0; i < nwords; ++i) {
shf_sopen(NULL, 0, SHF_WR | SHF_DYNAMIC, &S);
uprntmbs(words[i] + prefix_len, Nee, &S);
w[i] = shf_sclose(&S);
}
w[nwords] = NULL;
/*
* Enumerate expansions
*/
x_putc('\r');
x_putc('\n');
co.shf = shl_out;
co.linesep = '\n';
co.do_last = Ja;
co.prefcol = Nee;
pr_list(&co, w);
x_free_words(nwords, w);
}
/*
* Convert backslash-escaped string to QCHAR-escaped
* string useful for globbing
*/
static char *
x_glob_hlp_add_qchar(char *cp)
{
char ch, *dp;
Wahr escaping = Nee;
XString xs;
size_t n;
if (memchr(cp, QCHAR, (n = strlen(cp)))) {
Xinit(xs, dp, n, ATEMP);
} else {
xs.len = n + 1;
xs.areap = NULL; /* won’t be used */
xs.beg = dp = cp;
xs.end = xs.beg + xs.len;
}
while ((ch = *cp++)) {
if (ch == '\\' && !escaping) {
escaping = Ja;
continue;
}
/* coverity[var_deref_model : SUPPRESS] */
XcheckN(xs, dp, 2);
if ((escaping && ctype(ch, C_EDGLB)) || ch == QCHAR)
*dp++ = QCHAR;
escaping = Nee;
*dp++ = ch;
}
*dp = '\0';
return (Xstring(xs, dp));
}
/*
* Run tilde expansion on argument string, return the result
* after unescaping; if the flag is set, the original string
* is freed if changed and assumed backslash-escaped, if not
* it is assumed QCHAR-escaped
*/
static char *
x_glob_hlp_tilde_and_rem_qchar(char *s, Wahr magic_flag)
{
char ch, *cp, *dp;
/*
* On the string, check whether we have a tilde expansion,
* and if so, discern "~foo/bar" and "~/baz" from "~blah";
* if we have a directory part (the former), try to expand
*/
if (*s == '~' && (cp = /* not sdirsep */ ucstrchr(s, '/')) != NULL) {
/* ok, so split into "~foo"/"bar" or "~"/"baz" */
*cp++ = 0;
/* try to expand the tilde */
if (!(dp = do_tilde(s + 1))) {
/* nope, revert damage */
*--cp = '/';
} else {
/* ok, expand and replace */
strpathx(cp, dp, cp, 1);
if (magic_flag)
afree(s, ATEMP);
s = cp;
}
}
/* ... convert it from backslash-escaped via QCHAR-escaped... */
if (magic_flag) {
cp = x_glob_hlp_add_qchar(s);
if (cp != s)
afree(s, ATEMP);
s = cp;
}
/* ... to unescaped, for comparison with the matches */
cp = dp = s;
while ((ch = *cp++)) {
if (ch == QCHAR && !(ch = *cp++))
break;
*dp++ = ch;
}
*dp = '\0';
return (s);
}
/**
* Do file globbing:
* - does expansion, checks for no match, etc.
* - sets *wordsp to array of matching strings
* - returns number of matching strings
*/
static int
x_file_glob(int *flagsp, char *toglob, char ***wordsp)
{
char **words, *cp, *qglob;
int nwords;
XPtrV w;
struct source *s, *sold;
/* remove all escaping backward slashes */
qglob = x_glob_hlp_add_qchar(toglob);
/*
* Convert "foo*" (toglob) to an array of strings (words)
*/
sold = source;
s = pushs(SWSTR, ATEMP);
s->start = s->str = qglob;
source = s;
if (yylex(ONEWORD | LQCHAR) != LWORD) {
source = sold;
kwarnf(KWF_INTERNAL | KWF_WARNING | KWF_ONEMSG | KWF_NOERRNO,
Tfg_badsubst);
nwords = 0;
goto out;
}
source = sold;
afree(s, ATEMP);
XPinit(w, 32);
cp = yylval.cp;
while (*cp == CHAR || *cp == QCHAR)
cp += 2;
nwords = DOGLOB | DOTILDE | DOMARKDIRS;
if (*cp != EOS) {
/* probably a $FOO expansion */
*flagsp |= XCF_IS_NOSPACE;
/* this always results in at most one match */
nwords = 0;
}
expand(yylval.cp, &w, nwords);
XPput(w, NULL);
nwords = 0;
while (XPptrv(w)[nwords])
++nwords;
/* XPclose(w) except for nwords plus a trailing NULL for pr_list */
words = aresize2(XPptrv(w), (kui)nwords + 1U, sizeof(void *), ATEMP);
if (nwords == 1) {
struct stat statb;
/* Expand any tilde and drop all QCHAR for comparison */
qglob = x_glob_hlp_tilde_and_rem_qchar(qglob, Nee);
/*
* Check if globbing failed (returned glob pattern),
* but be careful (e.g. toglob == "ab*" when the file
* "ab*" exists is not an error).
* Also, check for empty result - happens if we tried
* to glob something which evaluated to an empty
* string (e.g., "$FOO" when there is no FOO, etc).
*/
if ((strcmp(words[0], qglob) == 0 &&
stat(words[0], &statb) < 0) ||
words[0][0] == '\0') {
x_free_words(nwords, words);
words = NULL;
nwords = 0;
}
}
if ((*wordsp = nwords ? words : NULL) == NULL && words != NULL)
x_free_words(nwords, words);
out:
if (qglob != toglob)
afree(qglob, ATEMP);
return (nwords);
}
/* Data structure used in x_command_glob() */
struct path_order_info {
char *word;
size_t base;
size_t path_order;
};
/* Compare routine used in x_command_glob() */
static int
path_order_cmp(const void *aa, const void *bb)
{
const struct path_order_info *a = (const struct path_order_info *)aa;
const struct path_order_info *b = (const struct path_order_info *)bb;
int t;
if ((t = ascstrcmp(a->word + a->base, b->word + b->base)))
return (t);
if (a->path_order > b->path_order)
return (1);
if (a->path_order < b->path_order)
return (-1);
return (0);
}
static int
x_command_glob(int flags, char *toglob, char ***wordsp)
{
char *pat, *fpath;
size_t nwords;
XPtrV w;
struct block *l;
/* Convert "foo*" (toglob) to a pattern for future use */
pat = evalstr(toglob, DOPAT | DOTILDE);
XPinit(w, 32);
glob_table(pat, &w, &keywords);
glob_table(pat, &w, &aliases);
glob_table(pat, &w, &builtins);
for (l = e->loc; l; l = l->next)
glob_table(pat, &w, &l->funs);
glob_path(flags, pat, &w, path);
if ((fpath = str_val(global(TFPATH))) != null)
glob_path(flags, pat, &w, fpath);
nwords = XPsize(w);
if (!nwords) {
*wordsp = NULL;
XPfree(w);
return (0);
}
/* Sort entries */
if (flags & XCF_FULLPATH) {
/* Sort by basename, then path order */
struct path_order_info *info, *last_info = NULL;
char **words = (char **)XPptrv(w);
size_t i, path_order = 0;
info = (struct path_order_info *)
alloc2(nwords, sizeof(struct path_order_info), ATEMP);
for (i = 0; i < nwords; i++) {
info[i].word = words[i];
info[i].base = x_basename(words[i], NULL);
if (!last_info || info[i].base != last_info->base ||
strncmp(words[i], last_info->word, info[i].base) != 0) {
last_info = &info[i];
path_order++;
}
info[i].path_order = path_order;
}
qsort(info, nwords, sizeof(struct path_order_info),
path_order_cmp);
for (i = 0; i < nwords; i++)
words[i] = info[i].word;
afree(info, ATEMP);
} else {
/* Sort and remove duplicate entries */
char **words = (char **)XPptrv(w);
size_t i, j;
qsort(words, nwords, sizeof(void *), ascpstrcmp);
for (i = j = 0; i < nwords - 1; i++) {
if (strcmp(words[i], words[i + 1]))
words[j++] = words[i];
else
afree(words[i], ATEMP);
}
words[j++] = words[i];
w.len = nwords = j;
}
XPput(w, NULL);
*wordsp = (char **)XPclose(w);
return (nwords);
}
#define IS_WORDC(c) (!ctype(c, C_EDNWC))
static int
x_locate_word(const char *buf, int buflen, int pos, int *startp,
Wahr *is_commandp)
{
int start, end;
/* Bad call? Probably should report error */
if (pos < 0 || pos > buflen) {
*startp = pos;
*is_commandp = Nee;
return (0);
}
/* The case where pos == buflen happens to take care of itself... */
start = pos;
/*
* Keep going backwards to start of word (has effect of allowing
* one blank after the end of a word)
*/
for (; (start > 0 && IS_WORDC(buf[start - 1])) ||
(start > 1 && buf[start - 2] == '\\'); start--)
;
/* Go forwards to end of word */
for (end = start; end < buflen && IS_WORDC(buf[end]); end++) {
if (buf[end] == '\\' && (end + 1) < buflen)
end++;
}
if (is_commandp) {
Wahr iscmd;
int p = start - 1;
/* Figure out if this is a command */
while (p >= 0 && ctype(buf[p], C_SPACE))
p--;
iscmd = p < 0 || ctype(buf[p], C_EDCMD);
if (iscmd) {
/*
* If command has a /, path, etc. is not searched;
* only current directory is searched which is just
* like file globbing.
*/
for (p = start; p < end; p++)
if (mksh_cdirsep(buf[p]))
break;
iscmd = p == end;
}
*is_commandp = iscmd;
}
*startp = start;
return (end - start);
}
static int
x_cf_glob(int *flagsp, const char *buf, int buflen, int pos, int *startp,
int *endp, char ***wordsp)
{
int len, nwords = 0;
char **words = NULL;
Wahr is_command;
len = x_locate_word(buf, buflen, pos, startp, &is_command);
if (!((*flagsp) & XCF_COMMAND))
is_command = Nee;
/*
* Don't do command globing on zero length strings - it takes too
* long and isn't very useful. File globs are more likely to be
* useful, so allow these.
*/
if (len == 0 && is_command)
return (0);
if (len >= 0) {
char *toglob, *s;
/*
* Given a string, copy it and possibly add a '*' to the end.
*/
strndupx(toglob, buf + *startp, len + /* the '*' */ 1, ATEMP);
toglob[len] = '\0';
/*
* If the pathname contains a wildcard (an unquoted '*',
* '?', or '[') or an extglob, then it is globbed based
* on that value (i.e., without the appended '*'). Same
* for parameter substitutions (as in “cat $HOME/.ss↹”)
* without appending a trailing space (LP: #710539), as
* well as for “~foo” (but not “~foo/”).
*/
for (s = toglob; *s; s++) {
if (*s == '\\' && s[1])
s++;
else if (ctype(*s, C_QUEST | C_DOLAR) ||
ord(*s) == ORD('*') || ord(*s) == ORD('[') ||
/* ?() *() +() @() !() but two already checked */
(ord(s[1]) == ORD('(' /*)*/) &&
(ord(*s) == ORD('+') || ord(*s) == ORD('@') ||
ord(*s) == ORD('!')))) {
/*
* just expand based on the extglob
* or parameter
*/
goto dont_add_glob;
}
}
if (*toglob == '~' && /* not vdirsep */ !vstrchr(toglob, '/')) {
/* neither for '~foo' (but '~foo/bar') */
*flagsp |= XCF_IS_HOMEDIR;
goto dont_add_glob;
}
/* append a glob */
toglob[len] = '*';
toglob[len + 1] = '\0';
dont_add_glob:
/*
* Expand (glob) it now.
*/
nwords = is_command ?
x_command_glob(*flagsp, toglob, &words) :
x_file_glob(flagsp, toglob, &words);
afree(toglob, ATEMP);
}
if (nwords == 0) {
*wordsp = NULL;
return (0);
}
if (is_command)
*flagsp |= XCF_IS_COMMAND;
*wordsp = words;
*endp = *startp + len;
return (nwords);
}
/*
* Find longest common prefix
*/
static size_t
x_longest_prefix(int nwords, char * const * words)
{
int i;
size_t j, prefix_len;
char *p;
if (nwords <= 0)
return (0);
prefix_len = strlen(words[0]);
for (i = 1; i < nwords; i++)
for (j = 0, p = words[i]; j < prefix_len; j++)
if (p[j] != words[0][j]) {
prefix_len = j;
break;
}
/* false for nwords==1 as 0 = words[0][prefix_len] then */
if (UTFMODE && prefix_len && (rtt2asc(words[0][prefix_len]) & 0xC0) == 0x80)
while (prefix_len && (rtt2asc(words[0][prefix_len]) & 0xC0) != 0xC0)
--prefix_len;
return (prefix_len);
}
static void
x_free_words(int nwords, char **words)
{
while (nwords)
afree(words[--nwords], ATEMP);
afree(words, ATEMP);
}
/*-
* Return the offset of the basename of string s (which ends at se - need not
* be null terminated). Trailing slashes are ignored. If s is just a slash,
* then the offset is 0 (actually, length - 1).
* s Return
* /etc 1
* /etc/ 1
* /etc// 1
* /etc/fo 5
* foo 0
* /// 2
* 0
*/
static size_t
x_basename(const char *s, const char *se)
{
const char *p;
if (se == NULL)
se = strnul(s);
if (s == se)
return (0);
/* skip trailing directory separators */
p = se - 1;
while (p > s && mksh_cdirsep(*p))
--p;
/* drop last component */
while (p > s && !mksh_cdirsep(*p))
--p;
if (mksh_cdirsep(*p) && p + 1 < se)
++p;
return (p - s);
}
/*
* Apply pattern matching to a table: all table entries that match a pattern
* are added to wp.
*/
static void
glob_table(const char *pat, XPtrV *wp, struct table *tp)
{
struct tstate ts;
struct tbl *te;
ktwalk(&ts, tp);
while ((te = ktnext(&ts)))
if (gmatchx(te->name, pat, Nee)) {
char *cp;
strdupx(cp, te->name, ATEMP);
XPput(*wp, cp);
}
}
static void
glob_path(int flags, const char *pat, XPtrV *wp, const char *lpath)
{
const char *sp = lpath, *p;
char *xp, **words;
size_t pathlen, patlen, oldsize, newsize, i, j;
XString xs;
patlen = strlen(pat);
checkoktoadd(patlen, 129 + X_EXTRA);
++patlen;
Xinit(xs, xp, patlen + 128, ATEMP);
while (sp) {
xp = Xstring(xs, xp);
if (!(p = cstrchr(sp, MKSH_PATHSEPC)))
p = strnul(sp);
pathlen = p - sp;
if (pathlen) {
/*
* Copy sp into xp, stuffing any MAGIC characters
* on the way
*/
const char *s = sp;
XcheckN(xs, xp, pathlen * 2);
while (s < p) {
if (ISMAGIC(*s))
*xp++ = MAGIC;
*xp++ = *s++;
}
*xp++ = '/';
pathlen++;
}
sp = p;
XcheckN(xs, xp, patlen);
memcpy(xp, pat, patlen);
oldsize = XPsize(*wp);
/* mark dirs */
glob_str(Xstring(xs, xp), wp, Ja);
newsize = XPsize(*wp);
/* Check that each match is executable... */
words = (char **)XPptrv(*wp);
for (i = j = oldsize; i < newsize; i++) {
if (ksh_access(words[i], X_OK) == 0) {
words[j] = words[i];
if (!(flags & XCF_FULLPATH))
memmove(words[j], words[j] + pathlen,
strlen(words[j] + pathlen) + 1);
j++;
} else
afree(words[i], ATEMP);
}
wp->len = j;
if (!*sp++)
break;
}
Xfree(xs, xp);
}
/*
* if argument string contains any special characters, they will
* be escaped and the result will be put into edit buffer by
* keybinding-specific function
*/
static int
x_escape(const char *s, size_t len, int (*putbuf_func)(const char *, size_t))
{
size_t add = 0, wlen = len;
int rval = 0;
while (wlen - add > 0)
if (ctype(s[add], C_IFS | C_EDQ)) {
if (putbuf_func(s, add) != 0) {
rval = -1;
break;
}
putbuf_func(s[add] == '\n' ? "'" : "\\", 1);
putbuf_func(&s[add], 1);
if (s[add] == '\n')
putbuf_func("'", 1);
add++;
wlen -= add;
s += add;
add = 0;
} else
++add;
if (wlen > 0 && rval == 0)
rval = putbuf_func(s, wlen);
return (rval);
}
/* +++ emacs editing mode +++ */
/*-
* The input buffer "buf" is pointed to by "xbuf" and its end is
* pointed to by "xend". The current position in "xbuf" and end of
* the edit line are pointed to by "xcp" and "xep" respectively.
* "xbp" points to the start of a display window within "xbuf", and
* "xlp" points to the last visible character on screen, if valid;
* "xdp" points to the end of x_displen, adding one-column bytes if
* necessary when the input line is shorter.
*
* [A] starting position
*
* buf
* |<--------- $COLUMNS -------->|
* |<---- x_displen ------->|
* PS1 |
* +=====+=========+........+.............................+
* |\ \ |\ \ \
* xbuf xbp xcp xlp xep xdp xend
*
* [B] larger input line
*
* buf
* |<--------- $COLUMNS -------->|
* |<---- x_displen ------->|
* PS1 |
* +===========+============+---------------------+.......+
* |\ \ \ \ \
* xbuf xbp xcp xlp=xdp xep xend
*
* [C] scrolled
*
* buf
* | |<--------- $COLUMNS -------->|
* | |<--------- x_displen ------->|
* |
* +-------+==============+==============+--------+.......+
* | \ \ \ \ \
* xbuf xbp xcp xlp=xdp xep xend
*
* In the above -------- represents the current edit line while
* ===== represents that portion which is visible on the screen;
* ....... is unused space in buf. Note that initially xbp == xbuf
* and PS1 is displayed. PS1 uses some of the screen width and thus
* "x_displen" is less than $COLUMNS.
*
* Any time that "xcp" moves outside the region bounded by "xbp"
* and "xbp" + "x_displen", the function x_adjust() is called to
* relocate "xbp" appropriately and redraw the line.
*
* Excessive I/O is avoided where possible. x_goto() for instance
* calculates whether the destination is outside the visible
* region, and if so simply adjusts "xcp" and calls x_adjust()
* directly. Normally though x_adjust() is called from x_putc().
*/
static Area aedit;
#define AEDIT &aedit /* area for kill ring and macro defns */
/* values returned by keyboard functions */
#define KSTD 0
#define KEOL 1 /* ^M, ^J */
#define KINTR 2 /* ^G, ^C */
struct x_ftab {
int (*xf_func)(int c);
const char *xf_name;
short xf_flags;
};
struct x_defbindings {
unsigned char xdb_func; /* XFUNC_* */
unsigned char xdb_tab;
unsigned char xdb_char;
};
#define XF_ARG 1 /* command takes number prefix */
#define XF_NOBIND 2 /* not allowed to bind to function */
#define XF_PREFIX 4 /* function sets prefix */
/*-
* Arguments for do_complete()
* 0 = enumerate M-= complete as much as possible and then list
* 1 = complete M-Esc
* 2 = list M-?
*/
typedef enum {
CT_LIST, /* list the possible completions */
CT_COMPLETE, /* complete to longest prefix */
CT_COMPLIST /* complete and then list (if non-exact) */
} Comp_type;