-
Notifications
You must be signed in to change notification settings - Fork 0
/
lineedit.c
executable file
·2873 lines (2607 loc) · 70.4 KB
/
lineedit.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
/* vi: set sw=4 ts=4: */
/*
* Command line editing.
*
* Copyright (c) 1986-2003 may safely be consumed by a BSD or GPL license.
* Written by: Vladimir Oleynik <[email protected]>
*
* Used ideas:
* Adam Rogoyski <[email protected]>
* Dave Cinege <[email protected]>
* Jakub Jelinek (c) 1995
* Erik Andersen <[email protected]> (Majorly adjusted for busybox)
*
* This code is 'as is' with no warranty.
*/
/*
* Usage and known bugs:
* Terminal key codes are not extensive, more needs to be added.
* This version was created on Debian GNU/Linux 2.x.
* Delete, Backspace, Home, End, and the arrow keys were tested
* to work in an Xterm and console. Ctrl-A also works as Home.
* Ctrl-E also works as End.
*
* The following readline-like commands are not implemented:
* ESC-b -- Move back one word
* ESC-f -- Move forward one word
* ESC-d -- Delete forward one word
* CTL-t -- Transpose two characters
*
* lineedit does not know that the terminal escape sequences do not
* take up space on the screen. The redisplay code assumes, unless
* told otherwise, that each character in the prompt is a printable
* character that takes up one character position on the screen.
* You need to tell lineedit that some sequences of characters
* in the prompt take up no screen space. Compatibly with readline,
* use the \[ escape to begin a sequence of non-printing characters,
* and the \] escape to signal the end of such a sequence. Example:
*
* PS1='\[\033[01;32m\]\u@\h\[\033[01;34m\] \w \$\[\033[00m\] '
*
* Unicode in PS1 is not fully supported: prompt length calulation is wrong,
* resulting in line wrap problems with long (multi-line) input.
*
* Multi-line PS1 (e.g. PS1="\n[\w]\n$ ") has problems with history
* browsing: up/down arrows result in scrolling.
* It stems from simplistic "cmdedit_y = cmdedit_prmt_len / cmdedit_termw"
* calculation of how many lines the prompt takes.
*/
#include "libbb.h"
#include "unicode.h"
#ifndef _POSIX_VDISABLE
# define _POSIX_VDISABLE '\0'
#endif
#ifdef TEST
# define ENABLE_FEATURE_EDITING 0
# define ENABLE_FEATURE_TAB_COMPLETION 0
# define ENABLE_FEATURE_USERNAME_COMPLETION 0
#endif
/* Entire file (except TESTing part) sits inside this #if */
#if ENABLE_FEATURE_EDITING
#define ENABLE_USERNAME_OR_HOMEDIR \
(ENABLE_FEATURE_USERNAME_COMPLETION || ENABLE_FEATURE_EDITING_FANCY_PROMPT)
#define IF_USERNAME_OR_HOMEDIR(...)
#if ENABLE_USERNAME_OR_HOMEDIR
# undef IF_USERNAME_OR_HOMEDIR
# define IF_USERNAME_OR_HOMEDIR(...) __VA_ARGS__
#endif
#undef CHAR_T
#if ENABLE_UNICODE_SUPPORT
# define BB_NUL ((wchar_t)0)
# define CHAR_T wchar_t
static bool BB_isspace(CHAR_T c) { return ((unsigned)c < 256 && isspace(c)); }
# if ENABLE_FEATURE_EDITING_VI
static bool BB_isalnum(CHAR_T c) { return ((unsigned)c < 256 && isalnum(c)); }
# endif
static bool BB_ispunct(CHAR_T c) { return ((unsigned)c < 256 && ispunct(c)); }
# undef isspace
# undef isalnum
# undef ispunct
# undef isprint
# define isspace isspace_must_not_be_used
# define isalnum isalnum_must_not_be_used
# define ispunct ispunct_must_not_be_used
# define isprint isprint_must_not_be_used
#else
# define BB_NUL '\0'
# define CHAR_T char
# define BB_isspace(c) isspace(c)
# define BB_isalnum(c) isalnum(c)
# define BB_ispunct(c) ispunct(c)
#endif
#if ENABLE_UNICODE_PRESERVE_BROKEN
# define unicode_mark_raw_byte(wc) ((wc) | 0x20000000)
# define unicode_is_raw_byte(wc) ((wc) & 0x20000000)
#else
# define unicode_is_raw_byte(wc) 0
#endif
#define ESC "\033"
#define SEQ_CLEAR_TILL_END_OF_SCREEN ESC"[J"
//#define SEQ_CLEAR_TILL_END_OF_LINE ESC"[K"
enum {
MAX_LINELEN = CONFIG_FEATURE_EDITING_MAX_LEN < 0x7ff0
? CONFIG_FEATURE_EDITING_MAX_LEN
: 0x7ff0
};
#if ENABLE_USERNAME_OR_HOMEDIR
static const char null_str[] ALIGN1 = "";
#endif
/* We try to minimize both static and stack usage. */
struct lineedit_statics {
line_input_t *state;
volatile unsigned cmdedit_termw; /* = 80; */ /* actual terminal width */
sighandler_t previous_SIGWINCH_handler;
unsigned cmdedit_x; /* real x (col) terminal position */
unsigned cmdedit_y; /* pseudoreal y (row) terminal position */
unsigned cmdedit_prmt_len; /* length of prompt (without colors etc) */
unsigned cursor;
int command_len; /* must be signed */
/* signed maxsize: we want x in "if (x > S.maxsize)"
* to _not_ be promoted to unsigned */
int maxsize;
CHAR_T *command_ps;
const char *cmdedit_prompt;
#if ENABLE_USERNAME_OR_HOMEDIR
char *user_buf;
char *home_pwd_buf; /* = (char*)null_str; */
#endif
#if ENABLE_FEATURE_TAB_COMPLETION
char **matches;
unsigned num_matches;
#endif
#if ENABLE_FEATURE_EDITING_VI
# define DELBUFSIZ 128
CHAR_T *delptr;
smallint newdelflag; /* whether delbuf should be reused yet */
CHAR_T delbuf[DELBUFSIZ]; /* a place to store deleted characters */
#endif
#if ENABLE_FEATURE_EDITING_ASK_TERMINAL
smallint sent_ESC_br6n;
#endif
};
/* See lineedit_ptr_hack.c */
extern struct lineedit_statics *const lineedit_ptr_to_statics;
#define S (*lineedit_ptr_to_statics)
#define state (S.state )
#define cmdedit_termw (S.cmdedit_termw )
#define previous_SIGWINCH_handler (S.previous_SIGWINCH_handler)
#define cmdedit_x (S.cmdedit_x )
#define cmdedit_y (S.cmdedit_y )
#define cmdedit_prmt_len (S.cmdedit_prmt_len)
#define cursor (S.cursor )
#define command_len (S.command_len )
#define command_ps (S.command_ps )
#define cmdedit_prompt (S.cmdedit_prompt )
#define user_buf (S.user_buf )
#define home_pwd_buf (S.home_pwd_buf )
#define matches (S.matches )
#define num_matches (S.num_matches )
#define delptr (S.delptr )
#define newdelflag (S.newdelflag )
#define delbuf (S.delbuf )
#define INIT_S() do { \
(*(struct lineedit_statics**)&lineedit_ptr_to_statics) = xzalloc(sizeof(S)); \
barrier(); \
cmdedit_termw = 80; \
IF_USERNAME_OR_HOMEDIR(home_pwd_buf = (char*)null_str;) \
IF_FEATURE_EDITING_VI(delptr = delbuf;) \
} while (0)
static void deinit_S(void)
{
#if ENABLE_FEATURE_EDITING_FANCY_PROMPT
/* This one is allocated only if FANCY_PROMPT is on
* (otherwise it points to verbatim prompt (NOT malloced)) */
free((char*)cmdedit_prompt);
#endif
#if ENABLE_USERNAME_OR_HOMEDIR
free(user_buf);
if (home_pwd_buf != null_str)
free(home_pwd_buf);
#endif
free(lineedit_ptr_to_statics);
}
#define DEINIT_S() deinit_S()
#if ENABLE_UNICODE_SUPPORT
static size_t load_string(const char *src)
{
if (unicode_status == UNICODE_ON) {
ssize_t len = mbstowcs(command_ps, src, S.maxsize - 1);
if (len < 0)
len = 0;
command_ps[len] = BB_NUL;
return len;
} else {
unsigned i = 0;
while (src[i] && i < S.maxsize - 1) {
command_ps[i] = src[i];
i++;
}
command_ps[i] = BB_NUL;
return i;
}
}
static unsigned save_string(char *dst, unsigned maxsize)
{
if (unicode_status == UNICODE_ON) {
# if !ENABLE_UNICODE_PRESERVE_BROKEN
ssize_t len = wcstombs(dst, command_ps, maxsize - 1);
if (len < 0)
len = 0;
dst[len] = '\0';
return len;
# else
unsigned dstpos = 0;
unsigned srcpos = 0;
maxsize--;
while (dstpos < maxsize) {
wchar_t wc;
int n = srcpos;
/* Convert up to 1st invalid byte (or up to end) */
while ((wc = command_ps[srcpos]) != BB_NUL
&& !unicode_is_raw_byte(wc)
) {
srcpos++;
}
command_ps[srcpos] = BB_NUL;
n = wcstombs(dst + dstpos, command_ps + n, maxsize - dstpos);
if (n < 0) /* should not happen */
break;
dstpos += n;
if (wc == BB_NUL) /* usually is */
break;
/* We do have invalid byte here! */
command_ps[srcpos] = wc; /* restore it */
srcpos++;
if (dstpos == maxsize)
break;
dst[dstpos++] = (char) wc;
}
dst[dstpos] = '\0';
return dstpos;
# endif
} else {
unsigned i = 0;
while ((dst[i] = command_ps[i]) != 0)
i++;
return i;
}
}
/* I thought just fputwc(c, stdout) would work. But no... */
static void BB_PUTCHAR(wchar_t c)
{
if (unicode_status == UNICODE_ON) {
char buf[MB_CUR_MAX + 1];
mbstate_t mbst = { 0 };
ssize_t len = wcrtomb(buf, c, &mbst);
if (len > 0) {
buf[len] = '\0';
fputs(buf, stdout);
}
} else {
/* In this case, c is always one byte */
putchar(c);
}
}
# if ENABLE_UNICODE_COMBINING_WCHARS || ENABLE_UNICODE_WIDE_WCHARS
static wchar_t adjust_width_and_validate_wc(unsigned *width_adj, wchar_t wc)
# else
static wchar_t adjust_width_and_validate_wc(wchar_t wc)
# define adjust_width_and_validate_wc(width_adj, wc) \
((*(width_adj))++, adjust_width_and_validate_wc(wc))
# endif
{
int w = 1;
if (unicode_status == UNICODE_ON) {
if (wc > CONFIG_LAST_SUPPORTED_WCHAR) {
/* note: also true for unicode_is_raw_byte(wc) */
goto subst;
}
w = wcwidth(wc);
if ((ENABLE_UNICODE_COMBINING_WCHARS && w < 0)
|| (!ENABLE_UNICODE_COMBINING_WCHARS && w <= 0)
|| (!ENABLE_UNICODE_WIDE_WCHARS && w > 1)
) {
subst:
w = 1;
wc = CONFIG_SUBST_WCHAR;
}
}
# if ENABLE_UNICODE_COMBINING_WCHARS || ENABLE_UNICODE_WIDE_WCHARS
*width_adj += w;
#endif
return wc;
}
#else /* !UNICODE */
static size_t load_string(const char *src)
{
safe_strncpy(command_ps, src, S.maxsize);
return strlen(command_ps);
}
# if ENABLE_FEATURE_TAB_COMPLETION
static void save_string(char *dst, unsigned maxsize)
{
safe_strncpy(dst, command_ps, maxsize);
}
# endif
# define BB_PUTCHAR(c) bb_putchar(c)
/* Should never be called: */
int adjust_width_and_validate_wc(unsigned *width_adj, int wc);
#endif
/* Put 'command_ps[cursor]', cursor++.
* Advance cursor on screen. If we reached right margin, scroll text up
* and remove terminal margin effect by printing 'next_char' */
#define HACK_FOR_WRONG_WIDTH 1
static void put_cur_glyph_and_inc_cursor(void)
{
CHAR_T c = command_ps[cursor];
unsigned width = 0;
int ofs_to_right;
if (c == BB_NUL) {
/* erase character after end of input string */
c = ' ';
} else {
/* advance cursor only if we aren't at the end yet */
cursor++;
if (unicode_status == UNICODE_ON) {
IF_UNICODE_WIDE_WCHARS(width = cmdedit_x;)
c = adjust_width_and_validate_wc(&cmdedit_x, c);
IF_UNICODE_WIDE_WCHARS(width = cmdedit_x - width;)
} else {
cmdedit_x++;
}
}
ofs_to_right = cmdedit_x - cmdedit_termw;
if (!ENABLE_UNICODE_WIDE_WCHARS || ofs_to_right <= 0) {
/* c fits on this line */
BB_PUTCHAR(c);
}
if (ofs_to_right >= 0) {
/* we go to the next line */
#if HACK_FOR_WRONG_WIDTH
/* This works better if our idea of term width is wrong
* and it is actually wider (often happens on serial lines).
* Printing CR,LF *forces* cursor to next line.
* OTOH if terminal width is correct AND terminal does NOT
* have automargin (IOW: it is moving cursor to next line
* by itself (which is wrong for VT-10x terminals)),
* this will break things: there will be one extra empty line */
puts("\r"); /* + implicit '\n' */
#else
/* VT-10x terminals don't wrap cursor to next line when last char
* on the line is printed - cursor stays "over" this char.
* Need to print _next_ char too (first one to appear on next line)
* to make cursor move down to next line.
*/
/* Works ok only if cmdedit_termw is correct. */
c = command_ps[cursor];
if (c == BB_NUL)
c = ' ';
BB_PUTCHAR(c);
bb_putchar('\b');
#endif
cmdedit_y++;
if (!ENABLE_UNICODE_WIDE_WCHARS || ofs_to_right == 0) {
width = 0;
} else { /* ofs_to_right > 0 */
/* wide char c didn't fit on prev line */
BB_PUTCHAR(c);
}
cmdedit_x = width;
}
}
/* Move to end of line (by printing all chars till the end) */
static void put_till_end_and_adv_cursor(void)
{
while (cursor < command_len)
put_cur_glyph_and_inc_cursor();
}
/* Go to the next line */
static void goto_new_line(void)
{
put_till_end_and_adv_cursor();
if (cmdedit_x != 0)
bb_putchar('\n');
}
static void beep(void)
{
bb_putchar('\007');
}
static void put_prompt(void)
{
unsigned w;
fputs(cmdedit_prompt, stdout);
fflush_all();
cursor = 0;
w = cmdedit_termw; /* read volatile var once */
cmdedit_y = cmdedit_prmt_len / w; /* new quasireal y */
cmdedit_x = cmdedit_prmt_len % w;
}
/* Move back one character */
/* (optimized for slow terminals) */
static void input_backward(unsigned num)
{
if (num > cursor)
num = cursor;
if (num == 0)
return;
cursor -= num;
if ((ENABLE_UNICODE_COMBINING_WCHARS || ENABLE_UNICODE_WIDE_WCHARS)
&& unicode_status == UNICODE_ON
) {
/* correct NUM to be equal to _screen_ width */
int n = num;
num = 0;
while (--n >= 0)
adjust_width_and_validate_wc(&num, command_ps[cursor + n]);
if (num == 0)
return;
}
if (cmdedit_x >= num) {
cmdedit_x -= num;
if (num <= 4) {
/* This is longer by 5 bytes on x86.
* Also gets miscompiled for ARM users
* (busybox.net/bugs/view.php?id=2274).
* printf(("\b\b\b\b" + 4) - num);
* return;
*/
do {
bb_putchar('\b');
} while (--num);
return;
}
printf(ESC"[%uD", num);
return;
}
/* Need to go one or more lines up */
if (ENABLE_UNICODE_WIDE_WCHARS) {
/* With wide chars, it is hard to "backtrack"
* and reliably figure out where to put cursor.
* Example (<> is a wide char; # is an ordinary char, _ cursor):
* |prompt: <><> |
* |<><><><><><> |
* |_ |
* and user presses left arrow. num = 1, cmdedit_x = 0,
* We need to go up one line, and then - how do we know that
* we need to go *10* positions to the right? Because
* |prompt: <>#<>|
* |<><><>#<><><>|
* |_ |
* in this situation we need to go *11* positions to the right.
*
* A simpler thing to do is to redraw everything from the start
* up to new cursor position (which is already known):
*/
unsigned sv_cursor;
/* go to 1st column; go up to first line */
printf("\r" ESC"[%uA", cmdedit_y);
cmdedit_y = 0;
sv_cursor = cursor;
put_prompt(); /* sets cursor to 0 */
while (cursor < sv_cursor)
put_cur_glyph_and_inc_cursor();
} else {
int lines_up;
unsigned width;
/* num = chars to go back from the beginning of current line: */
num -= cmdedit_x;
width = cmdedit_termw; /* read volatile var once */
/* num=1...w: one line up, w+1...2w: two, etc: */
lines_up = 1 + (num - 1) / width;
cmdedit_x = (width * cmdedit_y - num) % width;
cmdedit_y -= lines_up;
/* go to 1st column; go up */
printf("\r" ESC"[%uA", lines_up);
/* go to correct column.
* xterm, konsole, Linux VT interpret 0 as 1 below! wow.
* need to *make sure* we skip it if cmdedit_x == 0 */
if (cmdedit_x)
printf(ESC"[%uC", cmdedit_x);
}
}
/* draw prompt, editor line, and clear tail */
static void redraw(int y, int back_cursor)
{
if (y > 0) /* up y lines */
printf(ESC"[%uA", y);
bb_putchar('\r');
put_prompt();
put_till_end_and_adv_cursor();
printf(SEQ_CLEAR_TILL_END_OF_SCREEN);
input_backward(back_cursor);
}
/* Delete the char in front of the cursor, optionally saving it
* for later putback */
#if !ENABLE_FEATURE_EDITING_VI
static void input_delete(void)
#define input_delete(save) input_delete()
#else
static void input_delete(int save)
#endif
{
int j = cursor;
if (j == (int)command_len)
return;
#if ENABLE_FEATURE_EDITING_VI
if (save) {
if (newdelflag) {
delptr = delbuf;
newdelflag = 0;
}
if ((delptr - delbuf) < DELBUFSIZ)
*delptr++ = command_ps[j];
}
#endif
memmove(command_ps + j, command_ps + j + 1,
/* (command_len + 1 [because of NUL]) - (j + 1)
* simplified into (command_len - j) */
(command_len - j) * sizeof(command_ps[0]));
command_len--;
put_till_end_and_adv_cursor();
/* Last char is still visible, erase it (and more) */
printf(SEQ_CLEAR_TILL_END_OF_SCREEN);
input_backward(cursor - j); /* back to old pos cursor */
}
#if ENABLE_FEATURE_EDITING_VI
static void put(void)
{
int ocursor;
int j = delptr - delbuf;
if (j == 0)
return;
ocursor = cursor;
/* open hole and then fill it */
memmove(command_ps + cursor + j, command_ps + cursor,
(command_len - cursor + 1) * sizeof(command_ps[0]));
memcpy(command_ps + cursor, delbuf, j * sizeof(command_ps[0]));
command_len += j;
put_till_end_and_adv_cursor();
input_backward(cursor - ocursor - j + 1); /* at end of new text */
}
#endif
/* Delete the char in back of the cursor */
static void input_backspace(void)
{
if (cursor > 0) {
input_backward(1);
input_delete(0);
}
}
/* Move forward one character */
static void input_forward(void)
{
if (cursor < command_len)
put_cur_glyph_and_inc_cursor();
}
#if ENABLE_FEATURE_TAB_COMPLETION
//FIXME:
//needs to be more clever: currently it thinks that "foo\ b<TAB>
//matches the file named "foo bar", which is untrue.
//Also, perhaps "foo b<TAB> needs to complete to "foo bar" <cursor>,
//not "foo bar <cursor>...
static void free_tab_completion_data(void)
{
if (matches) {
while (num_matches)
free(matches[--num_matches]);
free(matches);
matches = NULL;
}
}
static void add_match(char *matched)
{
matches = xrealloc_vector(matches, 4, num_matches);
matches[num_matches] = matched;
num_matches++;
}
# if ENABLE_FEATURE_USERNAME_COMPLETION
/* Replace "~user/..." with "/homedir/...".
* The parameter is malloced, free it or return it
* unchanged if no user is matched.
*/
static char *username_path_completion(char *ud)
{
struct passwd *entry;
char *tilde_name = ud;
char *home = NULL;
ud++; /* skip ~ */
if (*ud == '/') { /* "~/..." */
home = home_pwd_buf;
} else {
/* "~user/..." */
ud = strchr(ud, '/');
*ud = '\0'; /* "~user" */
entry = getpwnam(tilde_name + 1);
*ud = '/'; /* restore "~user/..." */
if (entry)
home = entry->pw_dir;
}
if (home) {
ud = concat_path_file(home, ud);
free(tilde_name);
tilde_name = ud;
}
return tilde_name;
}
/* ~use<tab> - find all users with this prefix.
* Return the length of the prefix used for matching.
*/
static NOINLINE unsigned complete_username(const char *ud)
{
struct passwd *pw;
unsigned userlen;
ud++; /* skip ~ */
userlen = strlen(ud);
setpwent();
while ((pw = getpwent()) != NULL) {
/* Null usernames should result in all users as possible completions. */
if (/* !ud[0] || */ is_prefixed_with(pw->pw_name, ud)) {
add_match(xasprintf("~%s/", pw->pw_name));
}
}
endpwent(); /* don't keep password file open */
return 1 + userlen;
}
# endif /* FEATURE_USERNAME_COMPLETION */
enum {
FIND_EXE_ONLY = 0,
FIND_DIR_ONLY = 1,
FIND_FILE_ONLY = 2,
};
static int path_parse(char ***p)
{
int npth;
const char *pth;
char *tmp;
char **res;
if (state->flags & WITH_PATH_LOOKUP)
pth = state->path_lookup;
else
pth = getenv("PATH");
/* PATH="" or PATH=":"? */
if (!pth || !pth[0] || LONE_CHAR(pth, ':'))
return 1;
tmp = (char*)pth;
npth = 1; /* path component count */
while (1) {
tmp = strchr(tmp, ':');
if (!tmp)
break;
tmp++;
if (*tmp == '\0')
break; /* :<empty> */
npth++;
}
*p = res = xmalloc(npth * sizeof(res[0]));
res[0] = tmp = xstrdup(pth);
npth = 1;
while (1) {
tmp = strchr(tmp, ':');
if (!tmp)
break;
*tmp++ = '\0'; /* ':' -> '\0' */
if (*tmp == '\0')
break; /* :<empty> */
res[npth++] = tmp;
}
return npth;
}
/* Complete command, directory or file name.
* Return the length of the prefix used for matching.
*/
static NOINLINE unsigned complete_cmd_dir_file(const char *command, int type)
{
char *path1[1];
char **paths = path1;
int npaths;
int i;
unsigned pf_len;
const char *pfind;
char *dirbuf = NULL;
npaths = 1;
path1[0] = (char*)".";
pfind = strrchr(command, '/');
if (!pfind) {
if (type == FIND_EXE_ONLY)
npaths = path_parse(&paths);
pfind = command;
} else {
/* point to 'l' in "..../last_component" */
pfind++;
/* dirbuf = ".../.../.../" */
dirbuf = xstrndup(command, pfind - command);
# if ENABLE_FEATURE_USERNAME_COMPLETION
if (dirbuf[0] == '~') /* ~/... or ~user/... */
dirbuf = username_path_completion(dirbuf);
# endif
path1[0] = dirbuf;
}
pf_len = strlen(pfind);
for (i = 0; i < npaths; i++) {
DIR *dir;
struct dirent *next;
struct stat st;
char *found;
dir = opendir(paths[i]);
if (!dir)
continue; /* don't print an error */
while ((next = readdir(dir)) != NULL) {
unsigned len;
const char *name_found = next->d_name;
/* .../<tab>: bash 3.2.0 shows dotfiles, but not . and .. */
if (!pfind[0] && DOT_OR_DOTDOT(name_found))
continue;
/* match? */
if (!is_prefixed_with(name_found, pfind))
continue; /* no */
found = concat_path_file(paths[i], name_found);
/* NB: stat() first so that we see is it a directory;
* but if that fails, use lstat() so that
* we still match dangling links */
if (stat(found, &st) && lstat(found, &st))
goto cont; /* hmm, remove in progress? */
/* Save only name */
len = strlen(name_found);
found = xrealloc(found, len + 2); /* +2: for slash and NUL */
strcpy(found, name_found);
if (S_ISDIR(st.st_mode)) {
/* name is a directory, add slash */
found[len] = '/';
found[len + 1] = '\0';
} else {
/* skip files if looking for dirs only (example: cd) */
if (type == FIND_DIR_ONLY)
goto cont;
}
/* add it to the list */
add_match(found);
continue;
cont:
free(found);
}
closedir(dir);
} /* for every path */
if (paths != path1) {
free(paths[0]); /* allocated memory is only in first member */
free(paths);
}
free(dirbuf);
return pf_len;
}
/* build_match_prefix:
* On entry, match_buf contains everything up to cursor at the moment <tab>
* was pressed. This function looks at it, figures out what part of it
* constitutes the command/file/directory prefix to use for completion,
* and rewrites match_buf to contain only that part.
*/
#define dbg_bmp 0
/* Helpers: */
/* QUOT is used on elements of int_buf[], which are bytes,
* not Unicode chars. Therefore it works correctly even in Unicode mode.
*/
#define QUOT (UCHAR_MAX+1)
static void remove_chunk(int16_t *int_buf, int beg, int end)
{
/* beg must be <= end */
if (beg == end)
return;
while ((int_buf[beg] = int_buf[end]) != 0)
beg++, end++;
if (dbg_bmp) {
int i;
for (i = 0; int_buf[i]; i++)
bb_putchar((unsigned char)int_buf[i]);
bb_putchar('\n');
}
}
/* Caller ensures that match_buf points to a malloced buffer
* big enough to hold strlen(match_buf)*2 + 2
*/
static NOINLINE int build_match_prefix(char *match_buf)
{
int i, j;
int command_mode;
int16_t *int_buf = (int16_t*)match_buf;
if (dbg_bmp) printf("\n%s\n", match_buf);
/* Copy in reverse order, since they overlap */
i = strlen(match_buf);
do {
int_buf[i] = (unsigned char)match_buf[i];
i--;
} while (i >= 0);
/* Mark every \c as "quoted c" */
for (i = 0; int_buf[i]; i++) {
if (int_buf[i] == '\\') {
remove_chunk(int_buf, i, i + 1);
int_buf[i] |= QUOT;
}
}
/* Quote-mark "chars" and 'chars', drop delimiters */
{
int in_quote = 0;
i = 0;
while (int_buf[i]) {
int cur = int_buf[i];
if (!cur)
break;
if (cur == '\'' || cur == '"') {
if (!in_quote || (cur == in_quote)) {
in_quote ^= cur;
remove_chunk(int_buf, i, i + 1);
continue;
}
}
if (in_quote)
int_buf[i] = cur | QUOT;
i++;
}
}
/* Remove everything up to command delimiters:
* ';' ';;' '&' '|' '&&' '||',
* but careful with '>&' '<&' '>|'
*/
for (i = 0; int_buf[i]; i++) {
int cur = int_buf[i];
if (cur == ';' || cur == '&' || cur == '|') {
int prev = i ? int_buf[i - 1] : 0;
if (cur == '&' && (prev == '>' || prev == '<')) {
continue;
} else if (cur == '|' && prev == '>') {
continue;
}
remove_chunk(int_buf, 0, i + 1 + (cur == int_buf[i + 1]));
i = -1; /* back to square 1 */
}
}
/* Remove all `cmd` */
for (i = 0; int_buf[i]; i++) {
if (int_buf[i] == '`') {
for (j = i + 1; int_buf[j]; j++) {
if (int_buf[j] == '`') {
/* `cmd` should count as a word:
* `cmd` c<tab> should search for files c*,
* not commands c*. Therefore we don't drop
* `cmd` entirely, we replace it with single `.
*/
remove_chunk(int_buf, i, j);
goto next;
}
}
/* No closing ` - command mode, remove all up to ` */
remove_chunk(int_buf, 0, i + 1);
break;
next: ;
}
}
/* Remove "cmd (" and "cmd {"
* Example: "if { c<tab>"
* In this example, c should be matched as command pfx.
*/
for (i = 0; int_buf[i]; i++) {
if (int_buf[i] == '(' || int_buf[i] == '{') {
remove_chunk(int_buf, 0, i + 1);
i = -1; /* back to square 1 */
}
}
/* Remove leading unquoted spaces */
for (i = 0; int_buf[i]; i++)
if (int_buf[i] != ' ')
break;
remove_chunk(int_buf, 0, i);
/* Determine completion mode */
command_mode = FIND_EXE_ONLY;
for (i = 0; int_buf[i]; i++) {
if (int_buf[i] == ' ' || int_buf[i] == '<' || int_buf[i] == '>') {
if (int_buf[i] == ' '
&& command_mode == FIND_EXE_ONLY
&& (char)int_buf[0] == 'c'
&& (char)int_buf[1] == 'd'
&& i == 2 /* -> int_buf[2] == ' ' */
) {
command_mode = FIND_DIR_ONLY;
} else {
command_mode = FIND_FILE_ONLY;
break;
}
}
}
if (dbg_bmp) printf("command_mode(0:exe/1:dir/2:file):%d\n", command_mode);
/* Remove everything except last word */
for (i = 0; int_buf[i]; i++) /* quasi-strlen(int_buf) */
continue;
for (--i; i >= 0; i--) {
int cur = int_buf[i];
if (cur == ' ' || cur == '<' || cur == '>' || cur == '|' || cur == '&') {
remove_chunk(int_buf, 0, i + 1);
break;
}
}
/* Convert back to string of _chars_ */
i = 0;
while ((match_buf[i] = int_buf[i]) != '\0')
i++;