Complie libbb/duration.c if ping[6] is selected
[oweals/busybox.git] / libbb / lineedit.c
1 /* vi: set sw=4 ts=4: */
2 /*
3  * Command line editing.
4  *
5  * Copyright (c) 1986-2003 may safely be consumed by a BSD or GPL license.
6  * Written by:   Vladimir Oleynik <dzo@simtreas.ru>
7  *
8  * Used ideas:
9  *      Adam Rogoyski    <rogoyski@cs.utexas.edu>
10  *      Dave Cinege      <dcinege@psychosis.com>
11  *      Jakub Jelinek (c) 1995
12  *      Erik Andersen    <andersen@codepoet.org> (Majorly adjusted for busybox)
13  *
14  * This code is 'as is' with no warranty.
15  */
16 /*
17  * Usage and known bugs:
18  * Terminal key codes are not extensive, more needs to be added.
19  * This version was created on Debian GNU/Linux 2.x.
20  * Delete, Backspace, Home, End, and the arrow keys were tested
21  * to work in an Xterm and console. Ctrl-A also works as Home.
22  * Ctrl-E also works as End.
23  *
24  * The following readline-like commands are not implemented:
25  * CTL-t -- Transpose two characters
26  *
27  * lineedit does not know that the terminal escape sequences do not
28  * take up space on the screen. The redisplay code assumes, unless
29  * told otherwise, that each character in the prompt is a printable
30  * character that takes up one character position on the screen.
31  * You need to tell lineedit that some sequences of characters
32  * in the prompt take up no screen space. Compatibly with readline,
33  * use the \[ escape to begin a sequence of non-printing characters,
34  * and the \] escape to signal the end of such a sequence. Example:
35  *
36  * PS1='\[\033[01;32m\]\u@\h\[\033[01;34m\] \w \$\[\033[00m\] '
37  *
38  * Unicode in PS1 is not fully supported: prompt length calulation is wrong,
39  * resulting in line wrap problems with long (multi-line) input.
40  */
41 #include "busybox.h"
42 #include "NUM_APPLETS.h"
43 #include "unicode.h"
44 #ifndef _POSIX_VDISABLE
45 # define _POSIX_VDISABLE '\0'
46 #endif
47
48
49 #ifdef TEST
50 # define ENABLE_FEATURE_EDITING 0
51 # define ENABLE_FEATURE_TAB_COMPLETION 0
52 # define ENABLE_FEATURE_USERNAME_COMPLETION 0
53 #endif
54
55
56 /* Entire file (except TESTing part) sits inside this #if */
57 #if ENABLE_FEATURE_EDITING
58
59
60 #define ENABLE_USERNAME_OR_HOMEDIR \
61         (ENABLE_FEATURE_USERNAME_COMPLETION || ENABLE_FEATURE_EDITING_FANCY_PROMPT)
62 #define IF_USERNAME_OR_HOMEDIR(...)
63 #if ENABLE_USERNAME_OR_HOMEDIR
64 # undef IF_USERNAME_OR_HOMEDIR
65 # define IF_USERNAME_OR_HOMEDIR(...) __VA_ARGS__
66 #endif
67
68
69 #undef CHAR_T
70 #if ENABLE_UNICODE_SUPPORT
71 # define BB_NUL ((wchar_t)0)
72 # define CHAR_T wchar_t
73 static bool BB_isspace(CHAR_T c) { return ((unsigned)c < 256 && isspace(c)); }
74 # if ENABLE_FEATURE_EDITING_VI
75 static bool BB_isalnum_or_underscore(CHAR_T c) {
76         return ((unsigned)c < 256 && isalnum(c)) || c == '_';
77 }
78 # endif
79 static bool BB_ispunct(CHAR_T c) { return ((unsigned)c < 256 && ispunct(c)); }
80 # undef isspace
81 # undef isalnum
82 # undef ispunct
83 # undef isprint
84 # define isspace isspace_must_not_be_used
85 # define isalnum isalnum_must_not_be_used
86 # define ispunct ispunct_must_not_be_used
87 # define isprint isprint_must_not_be_used
88 #else
89 # define BB_NUL '\0'
90 # define CHAR_T char
91 # define BB_isspace(c) isspace(c)
92 # if ENABLE_FEATURE_EDITING_VI
93 static bool BB_isalnum_or_underscore(CHAR_T c)
94 {
95         return ((unsigned)c < 256 && isalnum(c)) || c == '_';
96 }
97 # endif
98 # define BB_ispunct(c) ispunct(c)
99 #endif
100 #if ENABLE_UNICODE_PRESERVE_BROKEN
101 # define unicode_mark_raw_byte(wc)   ((wc) | 0x20000000)
102 # define unicode_is_raw_byte(wc)     ((wc) & 0x20000000)
103 #else
104 # define unicode_is_raw_byte(wc)     0
105 #endif
106
107
108 #define ESC "\033"
109
110 #define SEQ_CLEAR_TILL_END_OF_SCREEN  ESC"[J"
111 //#define SEQ_CLEAR_TILL_END_OF_LINE  ESC"[K"
112
113
114 enum {
115         MAX_LINELEN = CONFIG_FEATURE_EDITING_MAX_LEN < 0x7ff0
116                       ? CONFIG_FEATURE_EDITING_MAX_LEN
117                       : 0x7ff0
118 };
119
120 #if ENABLE_USERNAME_OR_HOMEDIR
121 static const char null_str[] ALIGN1 = "";
122 #endif
123
124 /* We try to minimize both static and stack usage. */
125 struct lineedit_statics {
126         line_input_t *state;
127
128         unsigned cmdedit_termw; /* = 80; */ /* actual terminal width */
129
130         unsigned cmdedit_x;        /* real x (col) terminal position */
131         unsigned cmdedit_y;        /* pseudoreal y (row) terminal position */
132         unsigned cmdedit_prmt_len; /* on-screen length of last/sole prompt line */
133
134         unsigned cursor;
135         int command_len; /* must be signed */
136         /* signed maxsize: we want x in "if (x > S.maxsize)"
137          * to _not_ be promoted to unsigned */
138         int maxsize;
139         CHAR_T *command_ps;
140
141         const char *cmdedit_prompt;
142         const char *prompt_last_line;  /* last/sole prompt line */
143
144 #if ENABLE_USERNAME_OR_HOMEDIR
145         char *user_buf;
146         char *home_pwd_buf; /* = (char*)null_str; */
147 #endif
148
149 #if ENABLE_FEATURE_TAB_COMPLETION
150         char **matches;
151         unsigned num_matches;
152 #endif
153
154 #if ENABLE_FEATURE_EDITING_WINCH
155         unsigned SIGWINCH_saved;
156         volatile unsigned SIGWINCH_count;
157         volatile smallint ok_to_redraw;
158 #endif
159
160 #if ENABLE_FEATURE_EDITING_VI
161 # define DELBUFSIZ 128
162         smallint newdelflag;     /* whether delbuf should be reused yet */
163         CHAR_T *delptr;
164         CHAR_T delbuf[DELBUFSIZ];  /* a place to store deleted characters */
165 #endif
166 #if ENABLE_FEATURE_EDITING_ASK_TERMINAL
167         smallint sent_ESC_br6n;
168 #endif
169
170 #if ENABLE_FEATURE_EDITING_WINCH
171         /* Largish struct, keeping it last results in smaller code */
172         struct sigaction SIGWINCH_handler;
173 #endif
174 };
175
176 /* See lineedit_ptr_hack.c */
177 extern struct lineedit_statics *const lineedit_ptr_to_statics;
178
179 #define S (*lineedit_ptr_to_statics)
180 #define state            (S.state           )
181 #define cmdedit_termw    (S.cmdedit_termw   )
182 #define cmdedit_x        (S.cmdedit_x       )
183 #define cmdedit_y        (S.cmdedit_y       )
184 #define cmdedit_prmt_len (S.cmdedit_prmt_len)
185 #define cursor           (S.cursor          )
186 #define command_len      (S.command_len     )
187 #define command_ps       (S.command_ps      )
188 #define cmdedit_prompt   (S.cmdedit_prompt  )
189 #define prompt_last_line (S.prompt_last_line)
190 #define user_buf         (S.user_buf        )
191 #define home_pwd_buf     (S.home_pwd_buf    )
192 #define matches          (S.matches         )
193 #define num_matches      (S.num_matches     )
194 #define delptr           (S.delptr          )
195 #define newdelflag       (S.newdelflag      )
196 #define delbuf           (S.delbuf          )
197
198 #define INIT_S() do { \
199         (*(struct lineedit_statics**)&lineedit_ptr_to_statics) = xzalloc(sizeof(S)); \
200         barrier(); \
201         cmdedit_termw = 80; \
202         IF_USERNAME_OR_HOMEDIR(home_pwd_buf = (char*)null_str;) \
203         IF_FEATURE_EDITING_VI(delptr = delbuf;) \
204 } while (0)
205
206 static void deinit_S(void)
207 {
208 #if ENABLE_FEATURE_EDITING_FANCY_PROMPT
209         /* This one is allocated only if FANCY_PROMPT is on
210          * (otherwise it points to verbatim prompt (NOT malloced)) */
211         free((char*)cmdedit_prompt);
212 #endif
213 #if ENABLE_USERNAME_OR_HOMEDIR
214         free(user_buf);
215         if (home_pwd_buf != null_str)
216                 free(home_pwd_buf);
217 #endif
218         free(lineedit_ptr_to_statics);
219 }
220 #define DEINIT_S() deinit_S()
221
222
223 #if ENABLE_UNICODE_SUPPORT
224 static size_t load_string(const char *src)
225 {
226         if (unicode_status == UNICODE_ON) {
227                 ssize_t len = mbstowcs(command_ps, src, S.maxsize - 1);
228                 if (len < 0)
229                         len = 0;
230                 command_ps[len] = BB_NUL;
231                 return len;
232         } else {
233                 unsigned i = 0;
234                 while (src[i] && i < S.maxsize - 1) {
235                         command_ps[i] = src[i];
236                         i++;
237                 }
238                 command_ps[i] = BB_NUL;
239                 return i;
240         }
241 }
242 static unsigned save_string(char *dst, unsigned maxsize)
243 {
244         if (unicode_status == UNICODE_ON) {
245 # if !ENABLE_UNICODE_PRESERVE_BROKEN
246                 ssize_t len = wcstombs(dst, command_ps, maxsize - 1);
247                 if (len < 0)
248                         len = 0;
249                 dst[len] = '\0';
250                 return len;
251 # else
252                 unsigned dstpos = 0;
253                 unsigned srcpos = 0;
254
255                 maxsize--;
256                 while (dstpos < maxsize) {
257                         wchar_t wc;
258                         int n = srcpos;
259
260                         /* Convert up to 1st invalid byte (or up to end) */
261                         while ((wc = command_ps[srcpos]) != BB_NUL
262                             && !unicode_is_raw_byte(wc)
263                         ) {
264                                 srcpos++;
265                         }
266                         command_ps[srcpos] = BB_NUL;
267                         n = wcstombs(dst + dstpos, command_ps + n, maxsize - dstpos);
268                         if (n < 0) /* should not happen */
269                                 break;
270                         dstpos += n;
271                         if (wc == BB_NUL) /* usually is */
272                                 break;
273
274                         /* We do have invalid byte here! */
275                         command_ps[srcpos] = wc; /* restore it */
276                         srcpos++;
277                         if (dstpos == maxsize)
278                                 break;
279                         dst[dstpos++] = (char) wc;
280                 }
281                 dst[dstpos] = '\0';
282                 return dstpos;
283 # endif
284         } else {
285                 unsigned i = 0;
286                 while ((dst[i] = command_ps[i]) != 0)
287                         i++;
288                 return i;
289         }
290 }
291 /* I thought just fputwc(c, stdout) would work. But no... */
292 static void BB_PUTCHAR(wchar_t c)
293 {
294         if (unicode_status == UNICODE_ON) {
295                 char buf[MB_CUR_MAX + 1];
296                 mbstate_t mbst = { 0 };
297                 ssize_t len = wcrtomb(buf, c, &mbst);
298                 if (len > 0) {
299                         buf[len] = '\0';
300                         fputs(buf, stdout);
301                 }
302         } else {
303                 /* In this case, c is always one byte */
304                 putchar(c);
305         }
306 }
307 # if ENABLE_UNICODE_COMBINING_WCHARS || ENABLE_UNICODE_WIDE_WCHARS
308 static wchar_t adjust_width_and_validate_wc(unsigned *width_adj, wchar_t wc)
309 # else
310 static wchar_t adjust_width_and_validate_wc(wchar_t wc)
311 #  define adjust_width_and_validate_wc(width_adj, wc) \
312         ((*(width_adj))++, adjust_width_and_validate_wc(wc))
313 # endif
314 {
315         int w = 1;
316
317         if (unicode_status == UNICODE_ON) {
318                 if (wc > CONFIG_LAST_SUPPORTED_WCHAR) {
319                         /* note: also true for unicode_is_raw_byte(wc) */
320                         goto subst;
321                 }
322                 w = wcwidth(wc);
323                 if ((ENABLE_UNICODE_COMBINING_WCHARS && w < 0)
324                  || (!ENABLE_UNICODE_COMBINING_WCHARS && w <= 0)
325                  || (!ENABLE_UNICODE_WIDE_WCHARS && w > 1)
326                 ) {
327  subst:
328                         w = 1;
329                         wc = CONFIG_SUBST_WCHAR;
330                 }
331         }
332
333 # if ENABLE_UNICODE_COMBINING_WCHARS || ENABLE_UNICODE_WIDE_WCHARS
334         *width_adj += w;
335 #endif
336         return wc;
337 }
338 #else /* !UNICODE */
339 static size_t load_string(const char *src)
340 {
341         safe_strncpy(command_ps, src, S.maxsize);
342         return strlen(command_ps);
343 }
344 # if ENABLE_FEATURE_TAB_COMPLETION
345 static void save_string(char *dst, unsigned maxsize)
346 {
347         safe_strncpy(dst, command_ps, maxsize);
348 }
349 # endif
350 # define BB_PUTCHAR(c) bb_putchar(c)
351 /* Should never be called: */
352 int adjust_width_and_validate_wc(unsigned *width_adj, int wc);
353 #endif
354
355
356 /* Put 'command_ps[cursor]', cursor++.
357  * Advance cursor on screen. If we reached right margin, scroll text up
358  * and remove terminal margin effect by printing 'next_char' */
359 #define HACK_FOR_WRONG_WIDTH 1
360 static void put_cur_glyph_and_inc_cursor(void)
361 {
362         CHAR_T c = command_ps[cursor];
363         unsigned width = 0;
364         int ofs_to_right;
365
366         if (c == BB_NUL) {
367                 /* erase character after end of input string */
368                 c = ' ';
369         } else {
370                 /* advance cursor only if we aren't at the end yet */
371                 cursor++;
372                 if (unicode_status == UNICODE_ON) {
373                         IF_UNICODE_WIDE_WCHARS(width = cmdedit_x;)
374                         c = adjust_width_and_validate_wc(&cmdedit_x, c);
375                         IF_UNICODE_WIDE_WCHARS(width = cmdedit_x - width;)
376                 } else {
377                         cmdedit_x++;
378                 }
379         }
380
381         ofs_to_right = cmdedit_x - cmdedit_termw;
382         if (!ENABLE_UNICODE_WIDE_WCHARS || ofs_to_right <= 0) {
383                 /* c fits on this line */
384                 BB_PUTCHAR(c);
385         }
386
387         if (ofs_to_right >= 0) {
388                 /* we go to the next line */
389 #if HACK_FOR_WRONG_WIDTH
390                 /* This works better if our idea of term width is wrong
391                  * and it is actually wider (often happens on serial lines).
392                  * Printing CR,LF *forces* cursor to next line.
393                  * OTOH if terminal width is correct AND terminal does NOT
394                  * have automargin (IOW: it is moving cursor to next line
395                  * by itself (which is wrong for VT-10x terminals)),
396                  * this will break things: there will be one extra empty line */
397                 puts("\r"); /* + implicit '\n' */
398 #else
399                 /* VT-10x terminals don't wrap cursor to next line when last char
400                  * on the line is printed - cursor stays "over" this char.
401                  * Need to print _next_ char too (first one to appear on next line)
402                  * to make cursor move down to next line.
403                  */
404                 /* Works ok only if cmdedit_termw is correct. */
405                 c = command_ps[cursor];
406                 if (c == BB_NUL)
407                         c = ' ';
408                 BB_PUTCHAR(c);
409                 bb_putchar('\b');
410 #endif
411                 cmdedit_y++;
412                 if (!ENABLE_UNICODE_WIDE_WCHARS || ofs_to_right == 0) {
413                         width = 0;
414                 } else { /* ofs_to_right > 0 */
415                         /* wide char c didn't fit on prev line */
416                         BB_PUTCHAR(c);
417                 }
418                 cmdedit_x = width;
419         }
420 }
421
422 /* Move to end of line (by printing all chars till the end) */
423 static void put_till_end_and_adv_cursor(void)
424 {
425         while (cursor < command_len)
426                 put_cur_glyph_and_inc_cursor();
427 }
428
429 /* Go to the next line */
430 static void goto_new_line(void)
431 {
432         put_till_end_and_adv_cursor();
433         /* "cursor == 0" is only if prompt is "" and user input is empty */
434         if (cursor == 0 || cmdedit_x != 0)
435                 bb_putchar('\n');
436 }
437
438 static void beep(void)
439 {
440         bb_putchar('\007');
441 }
442
443 /* Full or last/sole prompt line, reset edit cursor, calculate terminal cursor.
444  * cmdedit_y is always calculated for the last/sole prompt line.
445  */
446 static void put_prompt_custom(bool is_full)
447 {
448         fputs((is_full ? cmdedit_prompt : prompt_last_line), stdout);
449         cursor = 0;
450         cmdedit_y = cmdedit_prmt_len / cmdedit_termw; /* new quasireal y */
451         cmdedit_x = cmdedit_prmt_len % cmdedit_termw;
452 }
453
454 #define put_prompt_last_line() put_prompt_custom(0)
455 #define put_prompt()           put_prompt_custom(1)
456
457 /* Move back one character */
458 /* (optimized for slow terminals) */
459 static void input_backward(unsigned num)
460 {
461         if (num > cursor)
462                 num = cursor;
463         if (num == 0)
464                 return;
465         cursor -= num;
466
467         if ((ENABLE_UNICODE_COMBINING_WCHARS || ENABLE_UNICODE_WIDE_WCHARS)
468          && unicode_status == UNICODE_ON
469         ) {
470                 /* correct NUM to be equal to _screen_ width */
471                 int n = num;
472                 num = 0;
473                 while (--n >= 0)
474                         adjust_width_and_validate_wc(&num, command_ps[cursor + n]);
475                 if (num == 0)
476                         return;
477         }
478
479         if (cmdedit_x >= num) {
480                 cmdedit_x -= num;
481                 if (num <= 4) {
482                         /* This is longer by 5 bytes on x86.
483                          * Also gets miscompiled for ARM users
484                          * (busybox.net/bugs/view.php?id=2274).
485                          * printf(("\b\b\b\b" + 4) - num);
486                          * return;
487                          */
488                         do {
489                                 bb_putchar('\b');
490                         } while (--num);
491                         return;
492                 }
493                 printf(ESC"[%uD", num);
494                 return;
495         }
496
497         /* Need to go one or more lines up */
498         if (ENABLE_UNICODE_WIDE_WCHARS) {
499                 /* With wide chars, it is hard to "backtrack"
500                  * and reliably figure out where to put cursor.
501                  * Example (<> is a wide char; # is an ordinary char, _ cursor):
502                  * |prompt: <><> |
503                  * |<><><><><><> |
504                  * |_            |
505                  * and user presses left arrow. num = 1, cmdedit_x = 0,
506                  * We need to go up one line, and then - how do we know that
507                  * we need to go *10* positions to the right? Because
508                  * |prompt: <>#<>|
509                  * |<><><>#<><><>|
510                  * |_            |
511                  * in this situation we need to go *11* positions to the right.
512                  *
513                  * A simpler thing to do is to redraw everything from the start
514                  * up to new cursor position (which is already known):
515                  */
516                 unsigned sv_cursor;
517                 /* go to 1st column; go up to first line */
518                 printf("\r" ESC"[%uA", cmdedit_y);
519                 cmdedit_y = 0;
520                 sv_cursor = cursor;
521                 put_prompt_last_line(); /* sets cursor to 0 */
522                 while (cursor < sv_cursor)
523                         put_cur_glyph_and_inc_cursor();
524         } else {
525                 int lines_up;
526                 /* num = chars to go back from the beginning of current line: */
527                 num -= cmdedit_x;
528                 /* num=1...w: one line up, w+1...2w: two, etc: */
529                 lines_up = 1 + (num - 1) / cmdedit_termw;
530                 cmdedit_x = (cmdedit_termw * cmdedit_y - num) % cmdedit_termw;
531                 cmdedit_y -= lines_up;
532                 /* go to 1st column; go up */
533                 printf("\r" ESC"[%uA", lines_up);
534                 /* go to correct column.
535                  * xterm, konsole, Linux VT interpret 0 as 1 below! wow.
536                  * need to *make sure* we skip it if cmdedit_x == 0 */
537                 if (cmdedit_x)
538                         printf(ESC"[%uC", cmdedit_x);
539         }
540 }
541
542 /* See redraw and draw_full below */
543 static void draw_custom(int y, int back_cursor, bool is_full)
544 {
545         if (y > 0) /* up y lines */
546                 printf(ESC"[%uA", y);
547         bb_putchar('\r');
548         put_prompt_custom(is_full);
549         put_till_end_and_adv_cursor();
550         printf(SEQ_CLEAR_TILL_END_OF_SCREEN);
551         input_backward(back_cursor);
552 }
553
554 /* Move y lines up, draw last/sole prompt line, editor line[s], and clear tail.
555  * goal: redraw the prompt+input+cursor in-place, overwriting the previous */
556 #define redraw(y, back_cursor) draw_custom((y), (back_cursor), 0)
557
558 /* Like above, but without moving up, and while using all the prompt lines.
559  * goal: draw a full prompt+input+cursor unrelated to a previous position.
560  * note: cmdedit_y always ends up relating to the last/sole prompt line */
561 #define draw_full(back_cursor) draw_custom(0, (back_cursor), 1)
562
563 /* Delete the char in front of the cursor, optionally saving it
564  * for later putback */
565 #if !ENABLE_FEATURE_EDITING_VI
566 static void input_delete(void)
567 #define input_delete(save) input_delete()
568 #else
569 static void input_delete(int save)
570 #endif
571 {
572         int j = cursor;
573
574         if (j == (int)command_len)
575                 return;
576
577 #if ENABLE_FEATURE_EDITING_VI
578         if (save) {
579                 if (newdelflag) {
580                         delptr = delbuf;
581                         newdelflag = 0;
582                 }
583                 if ((delptr - delbuf) < DELBUFSIZ)
584                         *delptr++ = command_ps[j];
585         }
586 #endif
587
588         memmove(command_ps + j, command_ps + j + 1,
589                         /* (command_len + 1 [because of NUL]) - (j + 1)
590                          * simplified into (command_len - j) */
591                         (command_len - j) * sizeof(command_ps[0]));
592         command_len--;
593         put_till_end_and_adv_cursor();
594         /* Last char is still visible, erase it (and more) */
595         printf(SEQ_CLEAR_TILL_END_OF_SCREEN);
596         input_backward(cursor - j);     /* back to old pos cursor */
597 }
598
599 #if ENABLE_FEATURE_EDITING_VI
600 static void put(void)
601 {
602         int ocursor;
603         int j = delptr - delbuf;
604
605         if (j == 0)
606                 return;
607         ocursor = cursor;
608         /* open hole and then fill it */
609         memmove(command_ps + cursor + j, command_ps + cursor,
610                         (command_len - cursor + 1) * sizeof(command_ps[0]));
611         memcpy(command_ps + cursor, delbuf, j * sizeof(command_ps[0]));
612         command_len += j;
613         put_till_end_and_adv_cursor();
614         input_backward(cursor - ocursor - j + 1); /* at end of new text */
615 }
616 #endif
617
618 /* Delete the char in back of the cursor */
619 static void input_backspace(void)
620 {
621         if (cursor > 0) {
622                 input_backward(1);
623                 input_delete(0);
624         }
625 }
626
627 /* Move forward one character */
628 static void input_forward(void)
629 {
630         if (cursor < command_len)
631                 put_cur_glyph_and_inc_cursor();
632 }
633
634 #if ENABLE_FEATURE_TAB_COMPLETION
635
636 //FIXME:
637 //needs to be more clever: currently it thinks that "foo\ b<TAB>
638 //matches the file named "foo bar", which is untrue.
639 //Also, perhaps "foo b<TAB> needs to complete to "foo bar" <cursor>,
640 //not "foo bar <cursor>...
641
642 static void free_tab_completion_data(void)
643 {
644         if (matches) {
645                 while (num_matches)
646                         free(matches[--num_matches]);
647                 free(matches);
648                 matches = NULL;
649         }
650 }
651
652 static void add_match(char *matched)
653 {
654         unsigned char *p = (unsigned char*)matched;
655         while (*p) {
656                 /* ESC attack fix: drop any string with control chars */
657                 if (*p < ' '
658                  || (!ENABLE_UNICODE_SUPPORT && *p >= 0x7f)
659                  || (ENABLE_UNICODE_SUPPORT && *p == 0x7f)
660                 ) {
661                         free(matched);
662                         return;
663                 }
664                 p++;
665         }
666         matches = xrealloc_vector(matches, 4, num_matches);
667         matches[num_matches] = matched;
668         num_matches++;
669 }
670
671 # if ENABLE_FEATURE_USERNAME_COMPLETION
672 /* Replace "~user/..." with "/homedir/...".
673  * The parameter is malloced, free it or return it
674  * unchanged if no user is matched.
675  */
676 static char *username_path_completion(char *ud)
677 {
678         struct passwd *entry;
679         char *tilde_name = ud;
680         char *home = NULL;
681
682         ud++; /* skip ~ */
683         if (*ud == '/') {       /* "~/..." */
684                 home = home_pwd_buf;
685         } else {
686                 /* "~user/..." */
687                 ud = strchr(ud, '/');
688                 *ud = '\0';           /* "~user" */
689                 entry = getpwnam(tilde_name + 1);
690                 *ud = '/';            /* restore "~user/..." */
691                 if (entry)
692                         home = entry->pw_dir;
693         }
694         if (home) {
695                 ud = concat_path_file(home, ud);
696                 free(tilde_name);
697                 tilde_name = ud;
698         }
699         return tilde_name;
700 }
701
702 /* ~use<tab> - find all users with this prefix.
703  * Return the length of the prefix used for matching.
704  */
705 static NOINLINE unsigned complete_username(const char *ud)
706 {
707         struct passwd *pw;
708         unsigned userlen;
709
710         ud++; /* skip ~ */
711         userlen = strlen(ud);
712
713         setpwent();
714         while ((pw = getpwent()) != NULL) {
715                 /* Null usernames should result in all users as possible completions. */
716                 if (/* !ud[0] || */ is_prefixed_with(pw->pw_name, ud)) {
717                         add_match(xasprintf("~%s/", pw->pw_name));
718                 }
719         }
720         endpwent(); /* don't keep password file open */
721
722         return 1 + userlen;
723 }
724 # endif  /* FEATURE_USERNAME_COMPLETION */
725
726 enum {
727         FIND_EXE_ONLY = 0,
728         FIND_DIR_ONLY = 1,
729         FIND_FILE_ONLY = 2,
730 };
731
732 static int path_parse(char ***p)
733 {
734         int npth;
735         const char *pth;
736         char *tmp;
737         char **res;
738
739         if (state->flags & WITH_PATH_LOOKUP)
740                 pth = state->path_lookup;
741         else
742                 pth = getenv("PATH");
743
744         /* PATH="" or PATH=":"? */
745         if (!pth || !pth[0] || LONE_CHAR(pth, ':'))
746                 return 1;
747
748         tmp = (char*)pth;
749         npth = 1; /* path component count */
750         while (1) {
751                 tmp = strchr(tmp, ':');
752                 if (!tmp)
753                         break;
754                 tmp++;
755                 if (*tmp == '\0')
756                         break;  /* :<empty> */
757                 npth++;
758         }
759
760         *p = res = xmalloc(npth * sizeof(res[0]));
761         res[0] = tmp = xstrdup(pth);
762         npth = 1;
763         while (1) {
764                 tmp = strchr(tmp, ':');
765                 if (!tmp)
766                         break;
767                 *tmp++ = '\0'; /* ':' -> '\0' */
768                 if (*tmp == '\0')
769                         break; /* :<empty> */
770                 res[npth++] = tmp;
771         }
772         return npth;
773 }
774
775 /* Complete command, directory or file name.
776  * Return the length of the prefix used for matching.
777  */
778 static NOINLINE unsigned complete_cmd_dir_file(const char *command, int type)
779 {
780         char *path1[1];
781         char **paths = path1;
782         int npaths;
783         int i;
784         unsigned pf_len;
785         const char *pfind;
786         char *dirbuf = NULL;
787
788         npaths = 1;
789         path1[0] = (char*)".";
790
791         pfind = strrchr(command, '/');
792         if (!pfind) {
793                 if (type == FIND_EXE_ONLY)
794                         npaths = path_parse(&paths);
795                 pfind = command;
796         } else {
797                 /* point to 'l' in "..../last_component" */
798                 pfind++;
799                 /* dirbuf = ".../.../.../" */
800                 dirbuf = xstrndup(command, pfind - command);
801 # if ENABLE_FEATURE_USERNAME_COMPLETION
802                 if (dirbuf[0] == '~')   /* ~/... or ~user/... */
803                         dirbuf = username_path_completion(dirbuf);
804 # endif
805                 path1[0] = dirbuf;
806         }
807         pf_len = strlen(pfind);
808
809 # if ENABLE_FEATURE_SH_STANDALONE && NUM_APPLETS != 1
810         if (type == FIND_EXE_ONLY && !dirbuf) {
811                 const char *p = applet_names;
812
813                 while (*p) {
814                         if (strncmp(pfind, p, pf_len) == 0)
815                                 add_match(xstrdup(p));
816                         while (*p++ != '\0')
817                                 continue;
818                 }
819         }
820 # endif
821
822         for (i = 0; i < npaths; i++) {
823                 DIR *dir;
824                 struct dirent *next;
825                 struct stat st;
826                 char *found;
827
828                 dir = opendir(paths[i]);
829                 if (!dir)
830                         continue; /* don't print an error */
831
832                 while ((next = readdir(dir)) != NULL) {
833                         unsigned len;
834                         const char *name_found = next->d_name;
835
836                         /* .../<tab>: bash 3.2.0 shows dotfiles, but not . and .. */
837                         if (!pfind[0] && DOT_OR_DOTDOT(name_found))
838                                 continue;
839                         /* match? */
840                         if (!is_prefixed_with(name_found, pfind))
841                                 continue; /* no */
842
843                         found = concat_path_file(paths[i], name_found);
844                         /* NB: stat() first so that we see is it a directory;
845                          * but if that fails, use lstat() so that
846                          * we still match dangling links */
847                         if (stat(found, &st) && lstat(found, &st))
848                                 goto cont; /* hmm, remove in progress? */
849
850                         /* Save only name */
851                         len = strlen(name_found);
852                         found = xrealloc(found, len + 2); /* +2: for slash and NUL */
853                         strcpy(found, name_found);
854
855                         if (S_ISDIR(st.st_mode)) {
856                                 /* name is a directory, add slash */
857                                 found[len] = '/';
858                                 found[len + 1] = '\0';
859                         } else {
860                                 /* skip files if looking for dirs only (example: cd) */
861                                 if (type == FIND_DIR_ONLY)
862                                         goto cont;
863                         }
864                         /* add it to the list */
865                         add_match(found);
866                         continue;
867  cont:
868                         free(found);
869                 }
870                 closedir(dir);
871         } /* for every path */
872
873         if (paths != path1) {
874                 free(paths[0]); /* allocated memory is only in first member */
875                 free(paths);
876         }
877         free(dirbuf);
878
879         return pf_len;
880 }
881
882 /* build_match_prefix:
883  * On entry, match_buf contains everything up to cursor at the moment <tab>
884  * was pressed. This function looks at it, figures out what part of it
885  * constitutes the command/file/directory prefix to use for completion,
886  * and rewrites match_buf to contain only that part.
887  */
888 #define dbg_bmp 0
889 /* Helpers: */
890 /* QUOT is used on elements of int_buf[], which are bytes,
891  * not Unicode chars. Therefore it works correctly even in Unicode mode.
892  */
893 #define QUOT (UCHAR_MAX+1)
894 static void remove_chunk(int16_t *int_buf, int beg, int end)
895 {
896         /* beg must be <= end */
897         if (beg == end)
898                 return;
899
900         while ((int_buf[beg] = int_buf[end]) != 0)
901                 beg++, end++;
902
903         if (dbg_bmp) {
904                 int i;
905                 for (i = 0; int_buf[i]; i++)
906                         bb_putchar((unsigned char)int_buf[i]);
907                 bb_putchar('\n');
908         }
909 }
910 /* Caller ensures that match_buf points to a malloced buffer
911  * big enough to hold strlen(match_buf)*2 + 2
912  */
913 static NOINLINE int build_match_prefix(char *match_buf)
914 {
915         int i, j;
916         int command_mode;
917         int16_t *int_buf = (int16_t*)match_buf;
918
919         if (dbg_bmp) printf("\n%s\n", match_buf);
920
921         /* Copy in reverse order, since they overlap */
922         i = strlen(match_buf);
923         do {
924                 int_buf[i] = (unsigned char)match_buf[i];
925                 i--;
926         } while (i >= 0);
927
928         /* Mark every \c as "quoted c" */
929         for (i = 0; int_buf[i]; i++) {
930                 if (int_buf[i] == '\\') {
931                         remove_chunk(int_buf, i, i + 1);
932                         int_buf[i] |= QUOT;
933                 }
934         }
935         /* Quote-mark "chars" and 'chars', drop delimiters */
936         {
937                 int in_quote = 0;
938                 i = 0;
939                 while (int_buf[i]) {
940                         int cur = int_buf[i];
941                         if (!cur)
942                                 break;
943                         if (cur == '\'' || cur == '"') {
944                                 if (!in_quote || (cur == in_quote)) {
945                                         in_quote ^= cur;
946                                         remove_chunk(int_buf, i, i + 1);
947                                         continue;
948                                 }
949                         }
950                         if (in_quote)
951                                 int_buf[i] = cur | QUOT;
952                         i++;
953                 }
954         }
955
956         /* Remove everything up to command delimiters:
957          * ';' ';;' '&' '|' '&&' '||',
958          * but careful with '>&' '<&' '>|'
959          */
960         for (i = 0; int_buf[i]; i++) {
961                 int cur = int_buf[i];
962                 if (cur == ';' || cur == '&' || cur == '|') {
963                         int prev = i ? int_buf[i - 1] : 0;
964                         if (cur == '&' && (prev == '>' || prev == '<')) {
965                                 continue;
966                         } else if (cur == '|' && prev == '>') {
967                                 continue;
968                         }
969                         remove_chunk(int_buf, 0, i + 1 + (cur == int_buf[i + 1]));
970                         i = -1;  /* back to square 1 */
971                 }
972         }
973         /* Remove all `cmd` */
974         for (i = 0; int_buf[i]; i++) {
975                 if (int_buf[i] == '`') {
976                         for (j = i + 1; int_buf[j]; j++) {
977                                 if (int_buf[j] == '`') {
978                                         /* `cmd` should count as a word:
979                                          * `cmd` c<tab> should search for files c*,
980                                          * not commands c*. Therefore we don't drop
981                                          * `cmd` entirely, we replace it with single `.
982                                          */
983                                         remove_chunk(int_buf, i, j);
984                                         goto next;
985                                 }
986                         }
987                         /* No closing ` - command mode, remove all up to ` */
988                         remove_chunk(int_buf, 0, i + 1);
989                         break;
990  next: ;
991                 }
992         }
993
994         /* Remove "cmd (" and "cmd {"
995          * Example: "if { c<tab>"
996          * In this example, c should be matched as command pfx.
997          */
998         for (i = 0; int_buf[i]; i++) {
999                 if (int_buf[i] == '(' || int_buf[i] == '{') {
1000                         remove_chunk(int_buf, 0, i + 1);
1001                         i = -1;  /* back to square 1 */
1002                 }
1003         }
1004
1005         /* Remove leading unquoted spaces */
1006         for (i = 0; int_buf[i]; i++)
1007                 if (int_buf[i] != ' ')
1008                         break;
1009         remove_chunk(int_buf, 0, i);
1010
1011         /* Determine completion mode */
1012         command_mode = FIND_EXE_ONLY;
1013         for (i = 0; int_buf[i]; i++) {
1014                 if (int_buf[i] == ' ' || int_buf[i] == '<' || int_buf[i] == '>') {
1015                         if (int_buf[i] == ' '
1016                          && command_mode == FIND_EXE_ONLY
1017                          && (char)int_buf[0] == 'c'
1018                          && (char)int_buf[1] == 'd'
1019                          && i == 2 /* -> int_buf[2] == ' ' */
1020                         ) {
1021                                 command_mode = FIND_DIR_ONLY;
1022                         } else {
1023                                 command_mode = FIND_FILE_ONLY;
1024                                 break;
1025                         }
1026                 }
1027         }
1028         if (dbg_bmp) printf("command_mode(0:exe/1:dir/2:file):%d\n", command_mode);
1029
1030         /* Remove everything except last word */
1031         for (i = 0; int_buf[i]; i++) /* quasi-strlen(int_buf) */
1032                 continue;
1033         for (--i; i >= 0; i--) {
1034                 int cur = int_buf[i];
1035                 if (cur == ' ' || cur == '<' || cur == '>' || cur == '|' || cur == '&') {
1036                         remove_chunk(int_buf, 0, i + 1);
1037                         break;
1038                 }
1039         }
1040
1041         /* Convert back to string of _chars_ */
1042         i = 0;
1043         while ((match_buf[i] = int_buf[i]) != '\0')
1044                 i++;
1045
1046         if (dbg_bmp) printf("final match_buf:'%s'\n", match_buf);
1047
1048         return command_mode;
1049 }
1050
1051 /*
1052  * Display by column (original idea from ls applet,
1053  * very optimized by me [Vladimir] :)
1054  */
1055 static void showfiles(void)
1056 {
1057         int ncols, row;
1058         int column_width = 0;
1059         int nfiles = num_matches;
1060         int nrows = nfiles;
1061         int l;
1062
1063         /* find the longest file name - use that as the column width */
1064         for (row = 0; row < nrows; row++) {
1065                 l = unicode_strwidth(matches[row]);
1066                 if (column_width < l)
1067                         column_width = l;
1068         }
1069         column_width += 2;              /* min space for columns */
1070         ncols = cmdedit_termw / column_width;
1071
1072         if (ncols > 1) {
1073                 nrows /= ncols;
1074                 if (nfiles % ncols)
1075                         nrows++;        /* round up fractionals */
1076         } else {
1077                 ncols = 1;
1078         }
1079         for (row = 0; row < nrows; row++) {
1080                 int n = row;
1081                 int nc;
1082
1083                 for (nc = 1; nc < ncols && n+nrows < nfiles; n += nrows, nc++) {
1084                         printf("%s%-*s", matches[n],
1085                                 (int)(column_width - unicode_strwidth(matches[n])), ""
1086                         );
1087                 }
1088                 if (ENABLE_UNICODE_SUPPORT)
1089                         puts(printable_string(NULL, matches[n]));
1090                 else
1091                         puts(matches[n]);
1092         }
1093 }
1094
1095 static const char *is_special_char(char c)
1096 {
1097         return strchr(" `\"#$%^&*()=+{}[]:;'|\\<>", c);
1098 }
1099
1100 static char *quote_special_chars(char *found)
1101 {
1102         int l = 0;
1103         char *s = xzalloc((strlen(found) + 1) * 2);
1104
1105         while (*found) {
1106                 if (is_special_char(*found))
1107                         s[l++] = '\\';
1108                 s[l++] = *found++;
1109         }
1110         /* s[l] = '\0'; - already is */
1111         return s;
1112 }
1113
1114 /* Do TAB completion */
1115 static NOINLINE void input_tab(smallint *lastWasTab)
1116 {
1117         char *chosen_match;
1118         char *match_buf;
1119         size_t len_found;
1120         /* Length of string used for matching */
1121         unsigned match_pfx_len = match_pfx_len;
1122         int find_type;
1123 # if ENABLE_UNICODE_SUPPORT
1124         /* cursor pos in command converted to multibyte form */
1125         int cursor_mb;
1126 # endif
1127         if (!(state->flags & TAB_COMPLETION))
1128                 return;
1129
1130         if (*lastWasTab) {
1131                 /* The last char was a TAB too.
1132                  * Print a list of all the available choices.
1133                  */
1134                 if (num_matches > 0) {
1135                         /* cursor will be changed by goto_new_line() */
1136                         int sav_cursor = cursor;
1137                         goto_new_line();
1138                         showfiles();
1139                         draw_full(command_len - sav_cursor);
1140                 }
1141                 return;
1142         }
1143
1144         *lastWasTab = 1;
1145         chosen_match = NULL;
1146
1147         /* Make a local copy of the string up to the position of the cursor.
1148          * build_match_prefix will expand it into int16_t's, need to allocate
1149          * twice as much as the string_len+1.
1150          * (we then also (ab)use this extra space later - see (**))
1151          */
1152         match_buf = xmalloc(MAX_LINELEN * sizeof(int16_t));
1153 # if !ENABLE_UNICODE_SUPPORT
1154         save_string(match_buf, cursor + 1); /* +1 for NUL */
1155 # else
1156         {
1157                 CHAR_T wc = command_ps[cursor];
1158                 command_ps[cursor] = BB_NUL;
1159                 save_string(match_buf, MAX_LINELEN);
1160                 command_ps[cursor] = wc;
1161                 cursor_mb = strlen(match_buf);
1162         }
1163 # endif
1164         find_type = build_match_prefix(match_buf);
1165
1166         /* Free up any memory already allocated */
1167         free_tab_completion_data();
1168
1169 # if ENABLE_FEATURE_USERNAME_COMPLETION
1170         /* If the word starts with ~ and there is no slash in the word,
1171          * then try completing this word as a username. */
1172         if (state->flags & USERNAME_COMPLETION)
1173                 if (match_buf[0] == '~' && strchr(match_buf, '/') == NULL)
1174                         match_pfx_len = complete_username(match_buf);
1175 # endif
1176         /* If complete_username() did not match,
1177          * try to match a command in $PATH, or a directory, or a file */
1178         if (!matches)
1179                 match_pfx_len = complete_cmd_dir_file(match_buf, find_type);
1180
1181         /* Account for backslashes which will be inserted
1182          * by quote_special_chars() later */
1183         {
1184                 const char *e = match_buf + strlen(match_buf);
1185                 const char *s = e - match_pfx_len;
1186                 while (s < e)
1187                         if (is_special_char(*s++))
1188                                 match_pfx_len++;
1189         }
1190
1191         /* Remove duplicates */
1192         if (matches) {
1193                 unsigned i, n = 0;
1194                 qsort_string_vector(matches, num_matches);
1195                 for (i = 0; i < num_matches - 1; ++i) {
1196                         //if (matches[i] && matches[i+1]) { /* paranoia */
1197                                 if (strcmp(matches[i], matches[i+1]) == 0) {
1198                                         free(matches[i]);
1199                                         //matches[i] = NULL; /* paranoia */
1200                                 } else {
1201                                         matches[n++] = matches[i];
1202                                 }
1203                         //}
1204                 }
1205                 matches[n++] = matches[i];
1206                 num_matches = n;
1207         }
1208
1209         /* Did we find exactly one match? */
1210         if (num_matches != 1) { /* no */
1211                 char *cp;
1212                 beep();
1213                 if (!matches)
1214                         goto ret; /* no matches at all */
1215                 /* Find common prefix */
1216                 chosen_match = xstrdup(matches[0]);
1217                 for (cp = chosen_match; *cp; cp++) {
1218                         unsigned n;
1219                         for (n = 1; n < num_matches; n++) {
1220                                 if (matches[n][cp - chosen_match] != *cp) {
1221                                         goto stop;
1222                                 }
1223                         }
1224                 }
1225  stop:
1226                 if (cp == chosen_match) { /* have unique prefix? */
1227                         goto ret; /* no */
1228                 }
1229                 *cp = '\0';
1230                 cp = quote_special_chars(chosen_match);
1231                 free(chosen_match);
1232                 chosen_match = cp;
1233                 len_found = strlen(chosen_match);
1234         } else {                        /* exactly one match */
1235                 /* Next <tab> is not a double-tab */
1236                 *lastWasTab = 0;
1237
1238                 chosen_match = quote_special_chars(matches[0]);
1239                 len_found = strlen(chosen_match);
1240                 if (chosen_match[len_found-1] != '/') {
1241                         chosen_match[len_found] = ' ';
1242                         chosen_match[++len_found] = '\0';
1243                 }
1244         }
1245
1246 # if !ENABLE_UNICODE_SUPPORT
1247         /* Have space to place the match? */
1248         /* The result consists of three parts with these lengths: */
1249         /* cursor + (len_found - match_pfx_len) + (command_len - cursor) */
1250         /* it simplifies into: */
1251         if ((int)(len_found - match_pfx_len + command_len) < S.maxsize) {
1252                 int pos;
1253                 /* save tail */
1254                 strcpy(match_buf, &command_ps[cursor]);
1255                 /* add match and tail */
1256                 sprintf(&command_ps[cursor], "%s%s", chosen_match + match_pfx_len, match_buf);
1257                 command_len = strlen(command_ps);
1258                 /* new pos */
1259                 pos = cursor + len_found - match_pfx_len;
1260                 /* write out the matched command */
1261                 redraw(cmdedit_y, command_len - pos);
1262         }
1263 # else
1264         {
1265                 /* Use 2nd half of match_buf as scratch space - see (**) */
1266                 char *command = match_buf + MAX_LINELEN;
1267                 int len = save_string(command, MAX_LINELEN);
1268                 /* Have space to place the match? */
1269                 /* cursor_mb + (len_found - match_pfx_len) + (len - cursor_mb) */
1270                 if ((int)(len_found - match_pfx_len + len) < MAX_LINELEN) {
1271                         int pos;
1272                         /* save tail */
1273                         strcpy(match_buf, &command[cursor_mb]);
1274                         /* where do we want to have cursor after all? */
1275                         strcpy(&command[cursor_mb], chosen_match + match_pfx_len);
1276                         len = load_string(command);
1277                         /* add match and tail */
1278                         sprintf(&command[cursor_mb], "%s%s", chosen_match + match_pfx_len, match_buf);
1279                         command_len = load_string(command);
1280                         /* write out the matched command */
1281                         /* paranoia: load_string can return 0 on conv error,
1282                          * prevent passing pos = (0 - 12) to redraw */
1283                         pos = command_len - len;
1284                         redraw(cmdedit_y, pos >= 0 ? pos : 0);
1285                 }
1286         }
1287 # endif
1288  ret:
1289         free(chosen_match);
1290         free(match_buf);
1291 }
1292
1293 #endif  /* FEATURE_TAB_COMPLETION */
1294
1295
1296 line_input_t* FAST_FUNC new_line_input_t(int flags)
1297 {
1298         line_input_t *n = xzalloc(sizeof(*n));
1299         n->flags = flags;
1300         n->timeout = -1;
1301 #if MAX_HISTORY > 0
1302         n->max_history = MAX_HISTORY;
1303 #endif
1304         return n;
1305 }
1306
1307
1308 #if MAX_HISTORY > 0
1309
1310 unsigned FAST_FUNC size_from_HISTFILESIZE(const char *hp)
1311 {
1312         int size = MAX_HISTORY;
1313         if (hp) {
1314                 size = atoi(hp);
1315                 if (size <= 0)
1316                         return 1;
1317                 if (size > MAX_HISTORY)
1318                         return MAX_HISTORY;
1319         }
1320         return size;
1321 }
1322
1323 static void save_command_ps_at_cur_history(void)
1324 {
1325         if (command_ps[0] != BB_NUL) {
1326                 int cur = state->cur_history;
1327                 free(state->history[cur]);
1328
1329 # if ENABLE_UNICODE_SUPPORT
1330                 {
1331                         char tbuf[MAX_LINELEN];
1332                         save_string(tbuf, sizeof(tbuf));
1333                         state->history[cur] = xstrdup(tbuf);
1334                 }
1335 # else
1336                 state->history[cur] = xstrdup(command_ps);
1337 # endif
1338         }
1339 }
1340
1341 /* state->flags is already checked to be nonzero */
1342 static int get_previous_history(void)
1343 {
1344         if ((state->flags & DO_HISTORY) && state->cur_history) {
1345                 save_command_ps_at_cur_history();
1346                 state->cur_history--;
1347                 return 1;
1348         }
1349         beep();
1350         return 0;
1351 }
1352
1353 static int get_next_history(void)
1354 {
1355         if (state->flags & DO_HISTORY) {
1356                 if (state->cur_history < state->cnt_history) {
1357                         save_command_ps_at_cur_history(); /* save the current history line */
1358                         return ++state->cur_history;
1359                 }
1360         }
1361         beep();
1362         return 0;
1363 }
1364
1365 /* Lists command history. Used by shell 'history' builtins */
1366 void FAST_FUNC show_history(const line_input_t *st)
1367 {
1368         int i;
1369
1370         if (!st)
1371                 return;
1372         for (i = 0; i < st->cnt_history; i++)
1373                 printf("%4d %s\n", i, st->history[i]);
1374 }
1375
1376 # if ENABLE_FEATURE_EDITING_SAVEHISTORY
1377 /* We try to ensure that concurrent additions to the history
1378  * do not overwrite each other.
1379  * Otherwise shell users get unhappy.
1380  *
1381  * History file is trimmed lazily, when it grows several times longer
1382  * than configured MAX_HISTORY lines.
1383  */
1384
1385 static void free_line_input_t(line_input_t *n)
1386 {
1387         int i = n->cnt_history;
1388         while (i > 0)
1389                 free(n->history[--i]);
1390         free(n);
1391 }
1392
1393 /* state->flags is already checked to be nonzero */
1394 static void load_history(line_input_t *st_parm)
1395 {
1396         char *temp_h[MAX_HISTORY];
1397         char *line;
1398         FILE *fp;
1399         unsigned idx, i, line_len;
1400
1401         /* NB: do not trash old history if file can't be opened */
1402
1403         fp = fopen_for_read(st_parm->hist_file);
1404         if (fp) {
1405                 /* clean up old history */
1406                 for (idx = st_parm->cnt_history; idx > 0;) {
1407                         idx--;
1408                         free(st_parm->history[idx]);
1409                         st_parm->history[idx] = NULL;
1410                 }
1411
1412                 /* fill temp_h[], retaining only last MAX_HISTORY lines */
1413                 memset(temp_h, 0, sizeof(temp_h));
1414                 idx = 0;
1415                 st_parm->cnt_history_in_file = 0;
1416                 while ((line = xmalloc_fgetline(fp)) != NULL) {
1417                         if (line[0] == '\0') {
1418                                 free(line);
1419                                 continue;
1420                         }
1421                         free(temp_h[idx]);
1422                         temp_h[idx] = line;
1423                         st_parm->cnt_history_in_file++;
1424                         idx++;
1425                         if (idx == st_parm->max_history)
1426                                 idx = 0;
1427                 }
1428                 fclose(fp);
1429
1430                 /* find first non-NULL temp_h[], if any */
1431                 if (st_parm->cnt_history_in_file) {
1432                         while (temp_h[idx] == NULL) {
1433                                 idx++;
1434                                 if (idx == st_parm->max_history)
1435                                         idx = 0;
1436                         }
1437                 }
1438
1439                 /* copy temp_h[] to st_parm->history[] */
1440                 for (i = 0; i < st_parm->max_history;) {
1441                         line = temp_h[idx];
1442                         if (!line)
1443                                 break;
1444                         idx++;
1445                         if (idx == st_parm->max_history)
1446                                 idx = 0;
1447                         line_len = strlen(line);
1448                         if (line_len >= MAX_LINELEN)
1449                                 line[MAX_LINELEN-1] = '\0';
1450                         st_parm->history[i++] = line;
1451                 }
1452                 st_parm->cnt_history = i;
1453                 if (ENABLE_FEATURE_EDITING_SAVE_ON_EXIT)
1454                         st_parm->cnt_history_in_file = i;
1455         }
1456 }
1457
1458 #  if ENABLE_FEATURE_EDITING_SAVE_ON_EXIT
1459 void save_history(line_input_t *st)
1460 {
1461         FILE *fp;
1462
1463         if (!st->hist_file)
1464                 return;
1465         if (st->cnt_history <= st->cnt_history_in_file)
1466                 return;
1467
1468         fp = fopen(st->hist_file, "a");
1469         if (fp) {
1470                 int i, fd;
1471                 char *new_name;
1472                 line_input_t *st_temp;
1473
1474                 for (i = st->cnt_history_in_file; i < st->cnt_history; i++)
1475                         fprintf(fp, "%s\n", st->history[i]);
1476                 fclose(fp);
1477
1478                 /* we may have concurrently written entries from others.
1479                  * load them */
1480                 st_temp = new_line_input_t(st->flags);
1481                 st_temp->hist_file = st->hist_file;
1482                 st_temp->max_history = st->max_history;
1483                 load_history(st_temp);
1484
1485                 /* write out temp file and replace hist_file atomically */
1486                 new_name = xasprintf("%s.%u.new", st->hist_file, (int) getpid());
1487                 fd = open(new_name, O_WRONLY | O_CREAT | O_TRUNC, 0600);
1488                 if (fd >= 0) {
1489                         fp = xfdopen_for_write(fd);
1490                         for (i = 0; i < st_temp->cnt_history; i++)
1491                                 fprintf(fp, "%s\n", st_temp->history[i]);
1492                         fclose(fp);
1493                         if (rename(new_name, st->hist_file) == 0)
1494                                 st->cnt_history_in_file = st_temp->cnt_history;
1495                 }
1496                 free(new_name);
1497                 free_line_input_t(st_temp);
1498         }
1499 }
1500 #  else
1501 static void save_history(char *str)
1502 {
1503         int fd;
1504         int len, len2;
1505
1506         if (!state->hist_file)
1507                 return;
1508
1509         fd = open(state->hist_file, O_WRONLY | O_CREAT | O_APPEND, 0600);
1510         if (fd < 0)
1511                 return;
1512         xlseek(fd, 0, SEEK_END); /* paranoia */
1513         len = strlen(str);
1514         str[len] = '\n'; /* we (try to) do atomic write */
1515         len2 = full_write(fd, str, len + 1);
1516         str[len] = '\0';
1517         close(fd);
1518         if (len2 != len + 1)
1519                 return; /* "wtf?" */
1520
1521         /* did we write so much that history file needs trimming? */
1522         state->cnt_history_in_file++;
1523         if (state->cnt_history_in_file > state->max_history * 4) {
1524                 char *new_name;
1525                 line_input_t *st_temp;
1526
1527                 /* we may have concurrently written entries from others.
1528                  * load them */
1529                 st_temp = new_line_input_t(state->flags);
1530                 st_temp->hist_file = state->hist_file;
1531                 st_temp->max_history = state->max_history;
1532                 load_history(st_temp);
1533
1534                 /* write out temp file and replace hist_file atomically */
1535                 new_name = xasprintf("%s.%u.new", state->hist_file, (int) getpid());
1536                 fd = open(new_name, O_WRONLY | O_CREAT | O_TRUNC, 0600);
1537                 if (fd >= 0) {
1538                         FILE *fp;
1539                         int i;
1540
1541                         fp = xfdopen_for_write(fd);
1542                         for (i = 0; i < st_temp->cnt_history; i++)
1543                                 fprintf(fp, "%s\n", st_temp->history[i]);
1544                         fclose(fp);
1545                         if (rename(new_name, state->hist_file) == 0)
1546                                 state->cnt_history_in_file = st_temp->cnt_history;
1547                 }
1548                 free(new_name);
1549                 free_line_input_t(st_temp);
1550         }
1551 }
1552 #  endif
1553 # else
1554 #  define load_history(a) ((void)0)
1555 #  define save_history(a) ((void)0)
1556 # endif /* FEATURE_COMMAND_SAVEHISTORY */
1557
1558 static void remember_in_history(char *str)
1559 {
1560         int i;
1561
1562         if (!(state->flags & DO_HISTORY))
1563                 return;
1564         if (str[0] == '\0')
1565                 return;
1566         i = state->cnt_history;
1567         /* Don't save dupes */
1568         if (i && strcmp(state->history[i-1], str) == 0)
1569                 return;
1570
1571         free(state->history[state->max_history]); /* redundant, paranoia */
1572         state->history[state->max_history] = NULL; /* redundant, paranoia */
1573
1574         /* If history[] is full, remove the oldest command */
1575         /* we need to keep history[state->max_history] empty, hence >=, not > */
1576         if (i >= state->max_history) {
1577                 free(state->history[0]);
1578                 for (i = 0; i < state->max_history-1; i++)
1579                         state->history[i] = state->history[i+1];
1580                 /* i == state->max_history-1 */
1581 # if ENABLE_FEATURE_EDITING_SAVE_ON_EXIT
1582                 if (state->cnt_history_in_file)
1583                         state->cnt_history_in_file--;
1584 # endif
1585         }
1586         /* i <= state->max_history-1 */
1587         state->history[i++] = xstrdup(str);
1588         /* i <= state->max_history */
1589         state->cur_history = i;
1590         state->cnt_history = i;
1591 # if ENABLE_FEATURE_EDITING_SAVEHISTORY && !ENABLE_FEATURE_EDITING_SAVE_ON_EXIT
1592         save_history(str);
1593 # endif
1594 }
1595
1596 #else /* MAX_HISTORY == 0 */
1597 # define remember_in_history(a) ((void)0)
1598 #endif /* MAX_HISTORY */
1599
1600
1601 #if ENABLE_FEATURE_EDITING_VI
1602 /*
1603  * vi mode implemented 2005 by Paul Fox <pgf@foxharp.boston.ma.us>
1604  */
1605 static void
1606 vi_Word_motion(int eat)
1607 {
1608         CHAR_T *command = command_ps;
1609
1610         while (cursor < command_len && !BB_isspace(command[cursor]))
1611                 input_forward();
1612         if (eat) while (cursor < command_len && BB_isspace(command[cursor]))
1613                 input_forward();
1614 }
1615
1616 static void
1617 vi_word_motion(int eat)
1618 {
1619         CHAR_T *command = command_ps;
1620
1621         if (BB_isalnum_or_underscore(command[cursor])) {
1622                 while (cursor < command_len
1623                  && (BB_isalnum_or_underscore(command[cursor+1]))
1624                 ) {
1625                         input_forward();
1626                 }
1627         } else if (BB_ispunct(command[cursor])) {
1628                 while (cursor < command_len && BB_ispunct(command[cursor+1]))
1629                         input_forward();
1630         }
1631
1632         if (cursor < command_len)
1633                 input_forward();
1634
1635         if (eat) {
1636                 while (cursor < command_len && BB_isspace(command[cursor]))
1637                         input_forward();
1638         }
1639 }
1640
1641 static void
1642 vi_End_motion(void)
1643 {
1644         CHAR_T *command = command_ps;
1645
1646         input_forward();
1647         while (cursor < command_len && BB_isspace(command[cursor]))
1648                 input_forward();
1649         while (cursor < command_len-1 && !BB_isspace(command[cursor+1]))
1650                 input_forward();
1651 }
1652
1653 static void
1654 vi_end_motion(void)
1655 {
1656         CHAR_T *command = command_ps;
1657
1658         if (cursor >= command_len-1)
1659                 return;
1660         input_forward();
1661         while (cursor < command_len-1 && BB_isspace(command[cursor]))
1662                 input_forward();
1663         if (cursor >= command_len-1)
1664                 return;
1665         if (BB_isalnum_or_underscore(command[cursor])) {
1666                 while (cursor < command_len-1
1667                  && (BB_isalnum_or_underscore(command[cursor+1]))
1668                 ) {
1669                         input_forward();
1670                 }
1671         } else if (BB_ispunct(command[cursor])) {
1672                 while (cursor < command_len-1 && BB_ispunct(command[cursor+1]))
1673                         input_forward();
1674         }
1675 }
1676
1677 static void
1678 vi_Back_motion(void)
1679 {
1680         CHAR_T *command = command_ps;
1681
1682         while (cursor > 0 && BB_isspace(command[cursor-1]))
1683                 input_backward(1);
1684         while (cursor > 0 && !BB_isspace(command[cursor-1]))
1685                 input_backward(1);
1686 }
1687
1688 static void
1689 vi_back_motion(void)
1690 {
1691         CHAR_T *command = command_ps;
1692
1693         if (cursor <= 0)
1694                 return;
1695         input_backward(1);
1696         while (cursor > 0 && BB_isspace(command[cursor]))
1697                 input_backward(1);
1698         if (cursor <= 0)
1699                 return;
1700         if (BB_isalnum_or_underscore(command[cursor])) {
1701                 while (cursor > 0
1702                  && (BB_isalnum_or_underscore(command[cursor-1]))
1703                 ) {
1704                         input_backward(1);
1705                 }
1706         } else if (BB_ispunct(command[cursor])) {
1707                 while (cursor > 0 && BB_ispunct(command[cursor-1]))
1708                         input_backward(1);
1709         }
1710 }
1711 #endif
1712
1713 /* Modelled after bash 4.0 behavior of Ctrl-<arrow> */
1714 static void ctrl_left(void)
1715 {
1716         CHAR_T *command = command_ps;
1717
1718         while (1) {
1719                 CHAR_T c;
1720
1721                 input_backward(1);
1722                 if (cursor == 0)
1723                         break;
1724                 c = command[cursor];
1725                 if (c != ' ' && !BB_ispunct(c)) {
1726                         /* we reached a "word" delimited by spaces/punct.
1727                          * go to its beginning */
1728                         while (1) {
1729                                 c = command[cursor - 1];
1730                                 if (c == ' ' || BB_ispunct(c))
1731                                         break;
1732                                 input_backward(1);
1733                                 if (cursor == 0)
1734                                         break;
1735                         }
1736                         break;
1737                 }
1738         }
1739 }
1740 static void ctrl_right(void)
1741 {
1742         CHAR_T *command = command_ps;
1743
1744         while (1) {
1745                 CHAR_T c;
1746
1747                 c = command[cursor];
1748                 if (c == BB_NUL)
1749                         break;
1750                 if (c != ' ' && !BB_ispunct(c)) {
1751                         /* we reached a "word" delimited by spaces/punct.
1752                          * go to its end + 1 */
1753                         while (1) {
1754                                 input_forward();
1755                                 c = command[cursor];
1756                                 if (c == BB_NUL || c == ' ' || BB_ispunct(c))
1757                                         break;
1758                         }
1759                         break;
1760                 }
1761                 input_forward();
1762         }
1763 }
1764
1765
1766 /*
1767  * read_line_input and its helpers
1768  */
1769
1770 #if ENABLE_FEATURE_EDITING_ASK_TERMINAL
1771 static void ask_terminal(void)
1772 {
1773         /* Ask terminal where is the cursor now.
1774          * lineedit_read_key handles response and corrects
1775          * our idea of current cursor position.
1776          * Testcase: run "echo -n long_line_long_line_long_line",
1777          * then type in a long, wrapping command and try to
1778          * delete it using backspace key.
1779          * Note: we print it _after_ prompt, because
1780          * prompt may contain CR. Example: PS1='\[\r\n\]\w '
1781          */
1782         /* Problem: if there is buffered input on stdin,
1783          * the response will be delivered later,
1784          * possibly to an unsuspecting application.
1785          * Testcase: "sleep 1; busybox ash" + press and hold [Enter].
1786          * Result:
1787          * ~/srcdevel/bbox/fix/busybox.t4 #
1788          * ~/srcdevel/bbox/fix/busybox.t4 #
1789          * ^[[59;34~/srcdevel/bbox/fix/busybox.t4 #  <-- garbage
1790          * ~/srcdevel/bbox/fix/busybox.t4 #
1791          *
1792          * Checking for input with poll only makes the race narrower,
1793          * I still can trigger it. Strace:
1794          *
1795          * write(1, "~/srcdevel/bbox/fix/busybox.t4 # ", 33) = 33
1796          * poll([{fd=0, events=POLLIN}], 1, 0) = 0 (Timeout)  <-- no input exists
1797          * write(1, "\33[6n", 4) = 4  <-- send the ESC sequence, quick!
1798          * poll([{fd=0, events=POLLIN}], 1, -1) = 1 ([{fd=0, revents=POLLIN}])
1799          * read(0, "\n", 1)      = 1  <-- oh crap, user's input got in first
1800          */
1801         struct pollfd pfd;
1802
1803         pfd.fd = STDIN_FILENO;
1804         pfd.events = POLLIN;
1805         if (safe_poll(&pfd, 1, 0) == 0) {
1806                 S.sent_ESC_br6n = 1;
1807                 fputs(ESC"[6n", stdout);
1808                 fflush_all(); /* make terminal see it ASAP! */
1809         }
1810 }
1811 #else
1812 #define ask_terminal() ((void)0)
1813 #endif
1814
1815 /* Note about multi-line PS1 (e.g. "\n\w \u@\h\n> ") and prompt redrawing:
1816  *
1817  * If the prompt has any newlines, after we print it once we use only its last
1818  * line to redraw in-place, which makes it simpler to calculate how many lines
1819  * we should move the cursor up to align the redraw (cmdedit_y). The earlier
1820  * prompt lines just stay on screen and we redraw below them.
1821  *
1822  * Use cases for all prompt lines beyond the initial draw:
1823  * - After clear-screen (^L) or after displaying tab-completion choices, we
1824  *   print the full prompt, as it isn't redrawn in-place.
1825  * - During terminal resize we could try to redraw all lines, but we don't,
1826  *   because it requires delicate alignment, it's good enough with only the
1827  *   last line, and doing it wrong is arguably worse than not doing it at all.
1828  *
1829  * Terminology wise, if it doesn't mention "full", then it means the last/sole
1830  * prompt line. We use the prompt (last/sole line) while redrawing in-place,
1831  * and the full where we need a fresh one unrelated to an earlier position.
1832  *
1833  * If PS1 is not multiline, the last/sole line and the full are the same string.
1834  */
1835
1836 /* Called just once at read_line_input() init time */
1837 #if !ENABLE_FEATURE_EDITING_FANCY_PROMPT
1838 static void parse_and_put_prompt(const char *prmt_ptr)
1839 {
1840         const char *p;
1841         cmdedit_prompt = prompt_last_line = prmt_ptr;
1842         p = strrchr(prmt_ptr, '\n');
1843         if (p)
1844                 prompt_last_line = p + 1;
1845         cmdedit_prmt_len = unicode_strwidth(prompt_last_line);
1846         put_prompt();
1847 }
1848 #else
1849 static void parse_and_put_prompt(const char *prmt_ptr)
1850 {
1851         int prmt_size = 0;
1852         char *prmt_mem_ptr = xzalloc(1);
1853 # if ENABLE_USERNAME_OR_HOMEDIR
1854         char *cwd_buf = NULL;
1855 # endif
1856         char flg_not_length = '[';
1857         char cbuf[2];
1858
1859         /*cmdedit_prmt_len = 0; - already is */
1860
1861         cbuf[1] = '\0'; /* never changes */
1862
1863         while (*prmt_ptr) {
1864                 char timebuf[sizeof("HH:MM:SS")];
1865                 char *free_me = NULL;
1866                 char *pbuf;
1867                 char c;
1868
1869                 pbuf = cbuf;
1870                 c = *prmt_ptr++;
1871                 if (c == '\\') {
1872                         const char *cp;
1873                         int l;
1874 /*
1875  * Supported via bb_process_escape_sequence:
1876  * \a   ASCII bell character (07)
1877  * \e   ASCII escape character (033)
1878  * \n   newline
1879  * \r   carriage return
1880  * \\   backslash
1881  * \nnn char with octal code nnn
1882  * Supported:
1883  * \$   if the effective UID is 0, a #, otherwise a $
1884  * \w   current working directory, with $HOME abbreviated with a tilde
1885  *      Note: we do not support $PROMPT_DIRTRIM=n feature
1886  * \W   basename of the current working directory, with $HOME abbreviated with a tilde
1887  * \h   hostname up to the first '.'
1888  * \H   hostname
1889  * \u   username
1890  * \[   begin a sequence of non-printing characters
1891  * \]   end a sequence of non-printing characters
1892  * \T   current time in 12-hour HH:MM:SS format
1893  * \@   current time in 12-hour am/pm format
1894  * \A   current time in 24-hour HH:MM format
1895  * \t   current time in 24-hour HH:MM:SS format
1896  *      (all of the above work as \A)
1897  * Not supported:
1898  * \!   history number of this command
1899  * \#   command number of this command
1900  * \j   number of jobs currently managed by the shell
1901  * \l   basename of the shell's terminal device name
1902  * \s   name of the shell, the basename of $0 (the portion following the final slash)
1903  * \V   release of bash, version + patch level (e.g., 2.00.0)
1904  * \d   date in "Weekday Month Date" format (e.g., "Tue May 26")
1905  * \D{format}
1906  *      format is passed to strftime(3).
1907  *      An empty format results in a locale-specific time representation.
1908  *      The braces are required.
1909  * Mishandled by bb_process_escape_sequence:
1910  * \v   version of bash (e.g., 2.00)
1911  */
1912                         cp = prmt_ptr;
1913                         c = *cp;
1914                         if (c != 't') /* don't treat \t as tab */
1915                                 c = bb_process_escape_sequence(&prmt_ptr);
1916                         if (prmt_ptr == cp) {
1917                                 if (*cp == '\0')
1918                                         break;
1919                                 c = *prmt_ptr++;
1920
1921                                 switch (c) {
1922 # if ENABLE_USERNAME_OR_HOMEDIR
1923                                 case 'u':
1924                                         pbuf = user_buf ? user_buf : (char*)"";
1925                                         break;
1926 # endif
1927                                 case 'H':
1928                                 case 'h':
1929                                         pbuf = free_me = safe_gethostname();
1930                                         if (c == 'h')
1931                                                 strchrnul(pbuf, '.')[0] = '\0';
1932                                         break;
1933                                 case '$':
1934                                         c = (geteuid() == 0 ? '#' : '$');
1935                                         break;
1936                                 case 'T': /* 12-hour HH:MM:SS format */
1937                                 case '@': /* 12-hour am/pm format */
1938                                 case 'A': /* 24-hour HH:MM format */
1939                                 case 't': /* 24-hour HH:MM:SS format */
1940                                         /* We show all of them as 24-hour HH:MM */
1941                                         strftime_HHMMSS(timebuf, sizeof(timebuf), NULL)[-3] = '\0';
1942                                         pbuf = timebuf;
1943                                         break;
1944 # if ENABLE_USERNAME_OR_HOMEDIR
1945                                 case 'w': /* current dir */
1946                                 case 'W': /* basename of cur dir */
1947                                         if (!cwd_buf) {
1948                                                 cwd_buf = xrealloc_getcwd_or_warn(NULL);
1949                                                 if (!cwd_buf)
1950                                                         cwd_buf = (char *)bb_msg_unknown;
1951                                                 else if (home_pwd_buf[0]) {
1952                                                         char *after_home_user;
1953
1954                                                         /* /home/user[/something] -> ~[/something] */
1955                                                         after_home_user = is_prefixed_with(cwd_buf, home_pwd_buf);
1956                                                         if (after_home_user
1957                                                          && (*after_home_user == '/' || *after_home_user == '\0')
1958                                                         ) {
1959                                                                 cwd_buf[0] = '~';
1960                                                                 overlapping_strcpy(cwd_buf + 1, after_home_user);
1961                                                         }
1962                                                 }
1963                                         }
1964                                         pbuf = cwd_buf;
1965                                         if (c == 'w')
1966                                                 break;
1967                                         cp = strrchr(pbuf, '/');
1968                                         if (cp)
1969                                                 pbuf = (char*)cp + 1;
1970                                         break;
1971 # endif
1972 // bb_process_escape_sequence does this now:
1973 //                              case 'e': case 'E':     /* \e \E = \033 */
1974 //                                      c = '\033';
1975 //                                      break;
1976                                 case 'x': case 'X': {
1977                                         char buf2[4];
1978                                         for (l = 0; l < 3;) {
1979                                                 unsigned h;
1980                                                 buf2[l++] = *prmt_ptr;
1981                                                 buf2[l] = '\0';
1982                                                 h = strtoul(buf2, &pbuf, 16);
1983                                                 if (h > UCHAR_MAX || (pbuf - buf2) < l) {
1984                                                         buf2[--l] = '\0';
1985                                                         break;
1986                                                 }
1987                                                 prmt_ptr++;
1988                                         }
1989                                         c = (char)strtoul(buf2, NULL, 16);
1990                                         if (c == 0)
1991                                                 c = '?';
1992                                         pbuf = cbuf;
1993                                         break;
1994                                 }
1995                                 case '[': case ']':
1996                                         if (c == flg_not_length) {
1997                                                 /* Toggle '['/']' hex 5b/5d */
1998                                                 flg_not_length ^= 6;
1999                                                 continue;
2000                                         }
2001                                         break;
2002                                 } /* switch */
2003                         } /* if */
2004                 } /* if */
2005                 cbuf[0] = c;
2006                 {
2007                         int n = strlen(pbuf);
2008                         prmt_size += n;
2009                         if (c == '\n')
2010                                 cmdedit_prmt_len = 0;
2011                         else if (flg_not_length != ']') {
2012 #if 0 /*ENABLE_UNICODE_SUPPORT*/
2013 /* Won't work, pbuf is one BYTE string here instead of an one Unicode char string. */
2014 /* FIXME */
2015                                 cmdedit_prmt_len += unicode_strwidth(pbuf);
2016 #else
2017                                 cmdedit_prmt_len += n;
2018 #endif
2019                         }
2020                 }
2021                 prmt_mem_ptr = strcat(xrealloc(prmt_mem_ptr, prmt_size+1), pbuf);
2022                 free(free_me);
2023         } /* while */
2024
2025 # if ENABLE_USERNAME_OR_HOMEDIR
2026         if (cwd_buf != (char *)bb_msg_unknown)
2027                 free(cwd_buf);
2028 # endif
2029         /* see comment (above this function) about multiline prompt redrawing */
2030         cmdedit_prompt = prompt_last_line = prmt_mem_ptr;
2031         prmt_ptr = strrchr(cmdedit_prompt, '\n');
2032         if (prmt_ptr)
2033                 prompt_last_line = prmt_ptr + 1;
2034         put_prompt();
2035 }
2036 #endif
2037
2038 #if ENABLE_FEATURE_EDITING_WINCH
2039 static void cmdedit_setwidth(void)
2040 {
2041         int new_y;
2042
2043         cmdedit_termw = get_terminal_width(STDIN_FILENO);
2044         /* new y for current cursor */
2045         new_y = (cursor + cmdedit_prmt_len) / cmdedit_termw;
2046         /* redraw */
2047         redraw((new_y >= cmdedit_y ? new_y : cmdedit_y), command_len - cursor);
2048 }
2049
2050 static void win_changed(int nsig UNUSED_PARAM)
2051 {
2052         if (S.ok_to_redraw) {
2053                 /* We are in read_key(), safe to redraw immediately */
2054                 int sv_errno = errno;
2055                 cmdedit_setwidth();
2056                 fflush_all();
2057                 errno = sv_errno;
2058         } else {
2059                 /* Signal main loop that redraw is necessary */
2060                 S.SIGWINCH_count++;
2061         }
2062 }
2063 #endif
2064
2065 static int lineedit_read_key(char *read_key_buffer, int timeout)
2066 {
2067         int64_t ic;
2068 #if ENABLE_UNICODE_SUPPORT
2069         char unicode_buf[MB_CUR_MAX + 1];
2070         int unicode_idx = 0;
2071 #endif
2072
2073         fflush_all();
2074         while (1) {
2075                 /* Wait for input. TIMEOUT = -1 makes read_key wait even
2076                  * on nonblocking stdin, TIMEOUT = 50 makes sure we won't
2077                  * insist on full MB_CUR_MAX buffer to declare input like
2078                  * "\xff\n",pause,"ls\n" invalid and thus won't lose "ls".
2079                  *
2080                  * Note: read_key sets errno to 0 on success.
2081                  */
2082                 IF_FEATURE_EDITING_WINCH(S.ok_to_redraw = 1;)
2083                 ic = read_key(STDIN_FILENO, read_key_buffer, timeout);
2084                 IF_FEATURE_EDITING_WINCH(S.ok_to_redraw = 0;)
2085                 if (errno) {
2086 #if ENABLE_UNICODE_SUPPORT
2087                         if (errno == EAGAIN && unicode_idx != 0)
2088                                 goto pushback;
2089 #endif
2090                         break;
2091                 }
2092
2093 #if ENABLE_FEATURE_EDITING_ASK_TERMINAL
2094                 if ((int32_t)ic == KEYCODE_CURSOR_POS
2095                  && S.sent_ESC_br6n
2096                 ) {
2097                         S.sent_ESC_br6n = 0;
2098                         if (cursor == 0) { /* otherwise it may be bogus */
2099                                 int col = ((ic >> 32) & 0x7fff) - 1;
2100                                 /*
2101                                  * Is col > cmdedit_prmt_len?
2102                                  * If yes (terminal says cursor is farther to the right
2103                                  * of where we think it should be),
2104                                  * the prompt wasn't printed starting at col 1,
2105                                  * there was additional text before it.
2106                                  */
2107                                 if ((int)(col - cmdedit_prmt_len) > 0) {
2108                                         /* Fix our understanding of current x position */
2109                                         cmdedit_x += (col - cmdedit_prmt_len);
2110                                         while (cmdedit_x >= cmdedit_termw) {
2111                                                 cmdedit_x -= cmdedit_termw;
2112                                                 cmdedit_y++;
2113                                         }
2114                                 }
2115                         }
2116                         continue;
2117                 }
2118 #endif
2119
2120 #if ENABLE_UNICODE_SUPPORT
2121                 if (unicode_status == UNICODE_ON) {
2122                         wchar_t wc;
2123
2124                         if ((int32_t)ic < 0) /* KEYCODE_xxx */
2125                                 break;
2126                         // TODO: imagine sequence like: 0xff,<left-arrow>: we are currently losing 0xff...
2127
2128                         unicode_buf[unicode_idx++] = ic;
2129                         unicode_buf[unicode_idx] = '\0';
2130                         if (mbstowcs(&wc, unicode_buf, 1) != 1) {
2131                                 /* Not (yet?) a valid unicode char */
2132                                 if (unicode_idx < MB_CUR_MAX) {
2133                                         timeout = 50;
2134                                         continue;
2135                                 }
2136  pushback:
2137                                 /* Invalid sequence. Save all "bad bytes" except first */
2138                                 read_key_ungets(read_key_buffer, unicode_buf + 1, unicode_idx - 1);
2139 # if !ENABLE_UNICODE_PRESERVE_BROKEN
2140                                 ic = CONFIG_SUBST_WCHAR;
2141 # else
2142                                 ic = unicode_mark_raw_byte(unicode_buf[0]);
2143 # endif
2144                         } else {
2145                                 /* Valid unicode char, return its code */
2146                                 ic = wc;
2147                         }
2148                 }
2149 #endif
2150                 break;
2151         }
2152
2153         return ic;
2154 }
2155
2156 #if ENABLE_UNICODE_BIDI_SUPPORT
2157 static int isrtl_str(void)
2158 {
2159         int idx = cursor;
2160
2161         while (idx < command_len && unicode_bidi_is_neutral_wchar(command_ps[idx]))
2162                 idx++;
2163         return unicode_bidi_isrtl(command_ps[idx]);
2164 }
2165 #else
2166 # define isrtl_str() 0
2167 #endif
2168
2169 /* leave out the "vi-mode"-only case labels if vi editing isn't
2170  * configured. */
2171 #define vi_case(caselabel) IF_FEATURE_EDITING_VI(case caselabel)
2172
2173 /* convert uppercase ascii to equivalent control char, for readability */
2174 #undef CTRL
2175 #define CTRL(a) ((a) & ~0x40)
2176
2177 enum {
2178         VI_CMDMODE_BIT = 0x40000000,
2179         /* 0x80000000 bit flags KEYCODE_xxx */
2180 };
2181
2182 #if ENABLE_FEATURE_REVERSE_SEARCH
2183 /* Mimic readline Ctrl-R reverse history search.
2184  * When invoked, it shows the following prompt:
2185  * (reverse-i-search)'': user_input [cursor pos unchanged by Ctrl-R]
2186  * and typing results in search being performed:
2187  * (reverse-i-search)'tmp': cd /tmp [cursor under t in /tmp]
2188  * Search is performed by looking at progressively older lines in history.
2189  * Ctrl-R again searches for the next match in history.
2190  * Backspace deletes last matched char.
2191  * Control keys exit search and return to normal editing (at current history line).
2192  */
2193 static int32_t reverse_i_search(int timeout)
2194 {
2195         char match_buf[128]; /* for user input */
2196         char read_key_buffer[KEYCODE_BUFFER_SIZE];
2197         const char *matched_history_line;
2198         const char *saved_prompt;
2199         unsigned saved_prmt_len;
2200         int32_t ic;
2201
2202         matched_history_line = NULL;
2203         read_key_buffer[0] = 0;
2204         match_buf[0] = '\0';
2205
2206         /* Save and replace the prompt */
2207         saved_prompt = prompt_last_line;
2208         saved_prmt_len = cmdedit_prmt_len;
2209         goto set_prompt;
2210
2211         while (1) {
2212                 int h;
2213                 unsigned match_buf_len = strlen(match_buf);
2214
2215 //FIXME: correct timeout? (i.e. count it down?)
2216                 ic = lineedit_read_key(read_key_buffer, timeout);
2217
2218                 switch (ic) {
2219                 case CTRL('R'): /* searching for the next match */
2220                         break;
2221
2222                 case '\b':
2223                 case '\x7f':
2224                         /* Backspace */
2225                         if (unicode_status == UNICODE_ON) {
2226                                 while (match_buf_len != 0) {
2227                                         uint8_t c = match_buf[--match_buf_len];
2228                                         if ((c & 0xc0) != 0x80) /* start of UTF-8 char? */
2229                                                 break; /* yes */
2230                                 }
2231                         } else {
2232                                 if (match_buf_len != 0)
2233                                         match_buf_len--;
2234                         }
2235                         match_buf[match_buf_len] = '\0';
2236                         break;
2237
2238                 default:
2239                         if (ic < ' '
2240                          || (!ENABLE_UNICODE_SUPPORT && ic >= 256)
2241                          || (ENABLE_UNICODE_SUPPORT && ic >= VI_CMDMODE_BIT)
2242                         ) {
2243                                 goto ret;
2244                         }
2245
2246                         /* Append this char */
2247 #if ENABLE_UNICODE_SUPPORT
2248                         if (unicode_status == UNICODE_ON) {
2249                                 mbstate_t mbstate = { 0 };
2250                                 char buf[MB_CUR_MAX + 1];
2251                                 int len = wcrtomb(buf, ic, &mbstate);
2252                                 if (len > 0) {
2253                                         buf[len] = '\0';
2254                                         if (match_buf_len + len < sizeof(match_buf))
2255                                                 strcpy(match_buf + match_buf_len, buf);
2256                                 }
2257                         } else
2258 #endif
2259                         if (match_buf_len < sizeof(match_buf) - 1) {
2260                                 match_buf[match_buf_len] = ic;
2261                                 match_buf[match_buf_len + 1] = '\0';
2262                         }
2263                         break;
2264                 } /* switch (ic) */
2265
2266                 /* Search in history for match_buf */
2267                 h = state->cur_history;
2268                 if (ic == CTRL('R'))
2269                         h--;
2270                 while (h >= 0) {
2271                         if (state->history[h]) {
2272                                 char *match = strstr(state->history[h], match_buf);
2273                                 if (match) {
2274                                         state->cur_history = h;
2275                                         matched_history_line = state->history[h];
2276                                         command_len = load_string(matched_history_line);
2277                                         cursor = match - matched_history_line;
2278 //FIXME: cursor position for Unicode case
2279
2280                                         free((char*)prompt_last_line);
2281  set_prompt:
2282                                         prompt_last_line = xasprintf("(reverse-i-search)'%s': ", match_buf);
2283                                         cmdedit_prmt_len = unicode_strwidth(prompt_last_line);
2284                                         goto do_redraw;
2285                                 }
2286                         }
2287                         h--;
2288                 }
2289
2290                 /* Not found */
2291                 match_buf[match_buf_len] = '\0';
2292                 beep();
2293                 continue;
2294
2295  do_redraw:
2296                 redraw(cmdedit_y, command_len - cursor);
2297         } /* while (1) */
2298
2299  ret:
2300         if (matched_history_line)
2301                 command_len = load_string(matched_history_line);
2302
2303         free((char*)prompt_last_line);
2304         prompt_last_line = saved_prompt;
2305         cmdedit_prmt_len = saved_prmt_len;
2306         redraw(cmdedit_y, command_len - cursor);
2307
2308         return ic;
2309 }
2310 #endif
2311
2312 /* maxsize must be >= 2.
2313  * Returns:
2314  * -1 on read errors or EOF, or on bare Ctrl-D,
2315  * 0  on ctrl-C (the line entered is still returned in 'command'),
2316  * (in both cases the cursor remains on the input line, '\n' is not printed)
2317  * >0 length of input string, including terminating '\n'
2318  */
2319 int FAST_FUNC read_line_input(line_input_t *st, const char *prompt, char *command, int maxsize)
2320 {
2321         int len, n;
2322         int timeout;
2323 #if ENABLE_FEATURE_TAB_COMPLETION
2324         smallint lastWasTab = 0;
2325 #endif
2326         smallint break_out = 0;
2327 #if ENABLE_FEATURE_EDITING_VI
2328         smallint vi_cmdmode = 0;
2329 #endif
2330         struct termios initial_settings;
2331         struct termios new_settings;
2332         char read_key_buffer[KEYCODE_BUFFER_SIZE];
2333
2334         INIT_S();
2335
2336         n = get_termios_and_make_raw(STDIN_FILENO, &new_settings, &initial_settings, 0
2337                 | TERMIOS_CLEAR_ISIG /* turn off INTR (ctrl-C), QUIT, SUSP */
2338         );
2339         if (n != 0 || (initial_settings.c_lflag & (ECHO|ICANON)) == ICANON) {
2340                 /* Happens when e.g. stty -echo was run before.
2341                  * But if ICANON is not set, we don't come here.
2342                  * (example: interactive python ^Z-backgrounded,
2343                  * tty is still in "raw mode").
2344                  */
2345                 parse_and_put_prompt(prompt);
2346                 fflush_all();
2347                 if (fgets(command, maxsize, stdin) == NULL)
2348                         len = -1; /* EOF or error */
2349                 else
2350                         len = strlen(command);
2351                 DEINIT_S();
2352                 return len;
2353         }
2354
2355         init_unicode();
2356
2357 // FIXME: audit & improve this
2358         if (maxsize > MAX_LINELEN)
2359                 maxsize = MAX_LINELEN;
2360         S.maxsize = maxsize;
2361
2362         timeout = -1;
2363         /* Make state->flags == 0 if st is NULL.
2364          * With zeroed flags, no other fields are ever referenced.
2365          */
2366         state = (line_input_t*) &const_int_0;
2367         if (st) {
2368                 state = st;
2369                 timeout = st->timeout;
2370         }
2371 #if MAX_HISTORY > 0
2372 # if ENABLE_FEATURE_EDITING_SAVEHISTORY
2373         if (state->hist_file)
2374                 if (state->cnt_history == 0)
2375                         load_history(state);
2376 # endif
2377         if (state->flags & DO_HISTORY)
2378                 state->cur_history = state->cnt_history;
2379 #endif
2380
2381         /* prepare before init handlers */
2382         cmdedit_y = 0;  /* quasireal y, not true if line > xt*yt */
2383         command_len = 0;
2384 #if ENABLE_UNICODE_SUPPORT
2385         command_ps = xzalloc(maxsize * sizeof(command_ps[0]));
2386 #else
2387         command_ps = command;
2388         command[0] = '\0';
2389 #endif
2390 #define command command_must_not_be_used
2391
2392         tcsetattr_stdin_TCSANOW(&new_settings);
2393
2394 #if ENABLE_USERNAME_OR_HOMEDIR
2395         {
2396                 struct passwd *entry;
2397
2398                 entry = getpwuid(geteuid());
2399                 if (entry) {
2400                         user_buf = xstrdup(entry->pw_name);
2401                         home_pwd_buf = xstrdup(entry->pw_dir);
2402                 }
2403         }
2404 #endif
2405
2406 #if 0
2407         for (i = 0; i <= state->max_history; i++)
2408                 bb_error_msg("history[%d]:'%s'", i, state->history[i]);
2409         bb_error_msg("cur_history:%d cnt_history:%d", state->cur_history, state->cnt_history);
2410 #endif
2411
2412         /* Get width (before printing prompt) */
2413         cmdedit_termw = get_terminal_width(STDIN_FILENO);
2414         /* Print out the command prompt, optionally ask where cursor is */
2415         parse_and_put_prompt(prompt);
2416         ask_terminal();
2417
2418 #if ENABLE_FEATURE_EDITING_WINCH
2419         /* Install window resize handler (NB: after *all* init is complete) */
2420         S.SIGWINCH_handler.sa_handler = win_changed;
2421         S.SIGWINCH_handler.sa_flags = SA_RESTART;
2422         sigaction(SIGWINCH, &S.SIGWINCH_handler, &S.SIGWINCH_handler);
2423 #endif
2424         read_key_buffer[0] = 0;
2425         while (1) {
2426                 /*
2427                  * The emacs and vi modes share much of the code in the big
2428                  * command loop.  Commands entered when in vi's command mode
2429                  * (aka "escape mode") get an extra bit added to distinguish
2430                  * them - this keeps them from being self-inserted. This
2431                  * clutters the big switch a bit, but keeps all the code
2432                  * in one place.
2433                  */
2434                 int32_t ic, ic_raw;
2435 #if ENABLE_FEATURE_EDITING_WINCH
2436                 unsigned count;
2437
2438                 count = S.SIGWINCH_count;
2439                 if (S.SIGWINCH_saved != count) {
2440                         S.SIGWINCH_saved = count;
2441                         cmdedit_setwidth();
2442                 }
2443 #endif
2444                 ic = ic_raw = lineedit_read_key(read_key_buffer, timeout);
2445
2446 #if ENABLE_FEATURE_REVERSE_SEARCH
2447  again:
2448 #endif
2449 #if ENABLE_FEATURE_EDITING_VI
2450                 newdelflag = 1;
2451                 if (vi_cmdmode) {
2452                         /* btw, since KEYCODE_xxx are all < 0, this doesn't
2453                          * change ic if it contains one of them: */
2454                         ic |= VI_CMDMODE_BIT;
2455                 }
2456 #endif
2457
2458                 switch (ic) {
2459                 case '\n':
2460                 case '\r':
2461                 vi_case('\n'|VI_CMDMODE_BIT:)
2462                 vi_case('\r'|VI_CMDMODE_BIT:)
2463                         /* Enter */
2464                         goto_new_line();
2465                         break_out = 1;
2466                         break;
2467                 case CTRL('A'):
2468                 vi_case('0'|VI_CMDMODE_BIT:)
2469                         /* Control-a -- Beginning of line */
2470                         input_backward(cursor);
2471                         break;
2472                 case CTRL('B'):
2473                 vi_case('h'|VI_CMDMODE_BIT:)
2474                 vi_case('\b'|VI_CMDMODE_BIT:) /* ^H */
2475                 vi_case('\x7f'|VI_CMDMODE_BIT:) /* DEL */
2476                         input_backward(1); /* Move back one character */
2477                         break;
2478                 case CTRL('E'):
2479                 vi_case('$'|VI_CMDMODE_BIT:)
2480                         /* Control-e -- End of line */
2481                         put_till_end_and_adv_cursor();
2482                         break;
2483                 case CTRL('F'):
2484                 vi_case('l'|VI_CMDMODE_BIT:)
2485                 vi_case(' '|VI_CMDMODE_BIT:)
2486                         input_forward(); /* Move forward one character */
2487                         break;
2488                 case '\b':   /* ^H */
2489                 case '\x7f': /* DEL */
2490                         if (!isrtl_str())
2491                                 input_backspace();
2492                         else
2493                                 input_delete(0);
2494                         break;
2495                 case KEYCODE_DELETE:
2496                         if (!isrtl_str())
2497                                 input_delete(0);
2498                         else
2499                                 input_backspace();
2500                         break;
2501 #if ENABLE_FEATURE_TAB_COMPLETION
2502                 case '\t':
2503                         input_tab(&lastWasTab);
2504                         break;
2505 #endif
2506                 case CTRL('K'):
2507                         /* Control-k -- clear to end of line */
2508                         command_ps[cursor] = BB_NUL;
2509                         command_len = cursor;
2510                         printf(SEQ_CLEAR_TILL_END_OF_SCREEN);
2511                         break;
2512                 case CTRL('L'):
2513                 vi_case(CTRL('L')|VI_CMDMODE_BIT:)
2514                         /* Control-l -- clear screen */
2515                         /* cursor to top,left; clear to the end of screen */
2516                         printf(ESC"[H" ESC"[J");
2517                         draw_full(command_len - cursor);
2518                         break;
2519 #if MAX_HISTORY > 0
2520                 case CTRL('N'):
2521                 vi_case(CTRL('N')|VI_CMDMODE_BIT:)
2522                 vi_case('j'|VI_CMDMODE_BIT:)
2523                         /* Control-n -- Get next command in history */
2524                         if (get_next_history())
2525                                 goto rewrite_line;
2526                         break;
2527                 case CTRL('P'):
2528                 vi_case(CTRL('P')|VI_CMDMODE_BIT:)
2529                 vi_case('k'|VI_CMDMODE_BIT:)
2530                         /* Control-p -- Get previous command from history */
2531                         if (get_previous_history())
2532                                 goto rewrite_line;
2533                         break;
2534 #endif
2535                 case CTRL('U'):
2536                 vi_case(CTRL('U')|VI_CMDMODE_BIT:)
2537                         /* Control-U -- Clear line before cursor */
2538                         if (cursor) {
2539                                 command_len -= cursor;
2540                                 memmove(command_ps, command_ps + cursor,
2541                                         (command_len + 1) * sizeof(command_ps[0]));
2542                                 redraw(cmdedit_y, command_len);
2543                         }
2544                         break;
2545                 case CTRL('W'):
2546                 vi_case(CTRL('W')|VI_CMDMODE_BIT:)
2547                         /* Control-W -- Remove the last word */
2548                         while (cursor > 0 && BB_isspace(command_ps[cursor-1]))
2549                                 input_backspace();
2550                         while (cursor > 0 && !BB_isspace(command_ps[cursor-1]))
2551                                 input_backspace();
2552                         break;
2553                 case KEYCODE_ALT_D: {
2554                         /* Delete word forward */
2555                         int nc, sc = cursor;
2556                         ctrl_right();
2557                         nc = cursor - sc;
2558                         input_backward(nc);
2559                         while (--nc >= 0)
2560                                 input_delete(1);
2561                         break;
2562                 }
2563                 case KEYCODE_ALT_BACKSPACE: {
2564                         /* Delete word backward */
2565                         int sc = cursor;
2566                         ctrl_left();
2567                         while (sc-- > cursor)
2568                                 input_delete(1);
2569                         break;
2570                 }
2571 #if ENABLE_FEATURE_REVERSE_SEARCH
2572                 case CTRL('R'):
2573                         ic = ic_raw = reverse_i_search(timeout);
2574                         goto again;
2575 #endif
2576
2577 #if ENABLE_FEATURE_EDITING_VI
2578                 case 'i'|VI_CMDMODE_BIT:
2579                         vi_cmdmode = 0;
2580                         break;
2581                 case 'I'|VI_CMDMODE_BIT:
2582                         input_backward(cursor);
2583                         vi_cmdmode = 0;
2584                         break;
2585                 case 'a'|VI_CMDMODE_BIT:
2586                         input_forward();
2587                         vi_cmdmode = 0;
2588                         break;
2589                 case 'A'|VI_CMDMODE_BIT:
2590                         put_till_end_and_adv_cursor();
2591                         vi_cmdmode = 0;
2592                         break;
2593                 case 'x'|VI_CMDMODE_BIT:
2594                         input_delete(1);
2595                         break;
2596                 case 'X'|VI_CMDMODE_BIT:
2597                         if (cursor > 0) {
2598                                 input_backward(1);
2599                                 input_delete(1);
2600                         }
2601                         break;
2602                 case 'W'|VI_CMDMODE_BIT:
2603                         vi_Word_motion(1);
2604                         break;
2605                 case 'w'|VI_CMDMODE_BIT:
2606                         vi_word_motion(1);
2607                         break;
2608                 case 'E'|VI_CMDMODE_BIT:
2609                         vi_End_motion();
2610                         break;
2611                 case 'e'|VI_CMDMODE_BIT:
2612                         vi_end_motion();
2613                         break;
2614                 case 'B'|VI_CMDMODE_BIT:
2615                         vi_Back_motion();
2616                         break;
2617                 case 'b'|VI_CMDMODE_BIT:
2618                         vi_back_motion();
2619                         break;
2620                 case 'C'|VI_CMDMODE_BIT:
2621                         vi_cmdmode = 0;
2622                         /* fall through */
2623                 case 'D'|VI_CMDMODE_BIT:
2624                         goto clear_to_eol;
2625
2626                 case 'c'|VI_CMDMODE_BIT:
2627                         vi_cmdmode = 0;
2628                         /* fall through */
2629                 case 'd'|VI_CMDMODE_BIT: {
2630                         int nc, sc;
2631
2632                         ic = lineedit_read_key(read_key_buffer, timeout);
2633                         if (errno) /* error */
2634                                 goto return_error_indicator;
2635                         if (ic == ic_raw) { /* "cc", "dd" */
2636                                 input_backward(cursor);
2637                                 goto clear_to_eol;
2638                                 break;
2639                         }
2640
2641                         sc = cursor;
2642                         switch (ic) {
2643                         case 'w':
2644                         case 'W':
2645                         case 'e':
2646                         case 'E':
2647                                 switch (ic) {
2648                                 case 'w':   /* "dw", "cw" */
2649                                         vi_word_motion(vi_cmdmode);
2650                                         break;
2651                                 case 'W':   /* 'dW', 'cW' */
2652                                         vi_Word_motion(vi_cmdmode);
2653                                         break;
2654                                 case 'e':   /* 'de', 'ce' */
2655                                         vi_end_motion();
2656                                         input_forward();
2657                                         break;
2658                                 case 'E':   /* 'dE', 'cE' */
2659                                         vi_End_motion();
2660                                         input_forward();
2661                                         break;
2662                                 }
2663                                 nc = cursor;
2664                                 input_backward(cursor - sc);
2665                                 while (nc-- > cursor)
2666                                         input_delete(1);
2667                                 break;
2668                         case 'b':  /* "db", "cb" */
2669                         case 'B':  /* implemented as B */
2670                                 if (ic == 'b')
2671                                         vi_back_motion();
2672                                 else
2673                                         vi_Back_motion();
2674                                 while (sc-- > cursor)
2675                                         input_delete(1);
2676                                 break;
2677                         case ' ':  /* "d ", "c " */
2678                                 input_delete(1);
2679                                 break;
2680                         case '$':  /* "d$", "c$" */
2681  clear_to_eol:
2682                                 while (cursor < command_len)
2683                                         input_delete(1);
2684                                 break;
2685                         }
2686                         break;
2687                 }
2688                 case 'p'|VI_CMDMODE_BIT:
2689                         input_forward();
2690                         /* fallthrough */
2691                 case 'P'|VI_CMDMODE_BIT:
2692                         put();
2693                         break;
2694                 case 'r'|VI_CMDMODE_BIT:
2695 //FIXME: unicode case?
2696                         ic = lineedit_read_key(read_key_buffer, timeout);
2697                         if (errno) /* error */
2698                                 goto return_error_indicator;
2699                         if (ic < ' ' || ic > 255) {
2700                                 beep();
2701                         } else {
2702                                 command_ps[cursor] = ic;
2703                                 bb_putchar(ic);
2704                                 bb_putchar('\b');
2705                         }
2706                         break;
2707                 case '\x1b': /* ESC */
2708                         if (state->flags & VI_MODE) {
2709                                 /* insert mode --> command mode */
2710                                 vi_cmdmode = 1;
2711                                 input_backward(1);
2712                         }
2713                         break;
2714 #endif /* FEATURE_COMMAND_EDITING_VI */
2715
2716 #if MAX_HISTORY > 0
2717                 case KEYCODE_UP:
2718                         if (get_previous_history())
2719                                 goto rewrite_line;
2720                         beep();
2721                         break;
2722                 case KEYCODE_DOWN:
2723                         if (!get_next_history())
2724                                 break;
2725  rewrite_line:
2726                         /* Rewrite the line with the selected history item */
2727                         /* change command */
2728                         command_len = load_string(state->history[state->cur_history] ?
2729                                         state->history[state->cur_history] : "");
2730                         /* redraw and go to eol (bol, in vi) */
2731                         redraw(cmdedit_y, (state->flags & VI_MODE) ? 9999 : 0);
2732                         break;
2733 #endif
2734                 case KEYCODE_RIGHT:
2735                         input_forward();
2736                         break;
2737                 case KEYCODE_LEFT:
2738                         input_backward(1);
2739                         break;
2740                 case KEYCODE_CTRL_LEFT:
2741                 case KEYCODE_ALT_LEFT: /* bash doesn't do it */
2742                         ctrl_left();
2743                         break;
2744                 case KEYCODE_CTRL_RIGHT:
2745                 case KEYCODE_ALT_RIGHT: /* bash doesn't do it */
2746                         ctrl_right();
2747                         break;
2748                 case KEYCODE_HOME:
2749                         input_backward(cursor);
2750                         break;
2751                 case KEYCODE_END:
2752                         put_till_end_and_adv_cursor();
2753                         break;
2754
2755                 default:
2756                         if (initial_settings.c_cc[VINTR] != 0
2757                          && ic_raw == initial_settings.c_cc[VINTR]
2758                         ) {
2759                                 /* Ctrl-C (usually) - stop gathering input */
2760                                 command_len = 0;
2761                                 break_out = -1; /* "do not append '\n'" */
2762                                 break;
2763                         }
2764                         if (initial_settings.c_cc[VEOF] != 0
2765                          && ic_raw == initial_settings.c_cc[VEOF]
2766                         ) {
2767                                 /* Ctrl-D (usually) - delete one character,
2768                                  * or exit if len=0 and no chars to delete */
2769                                 if (command_len == 0) {
2770                                         errno = 0;
2771
2772                 case -1: /* error (e.g. EIO when tty is destroyed) */
2773  IF_FEATURE_EDITING_VI(return_error_indicator:)
2774                                         break_out = command_len = -1;
2775                                         break;
2776                                 }
2777                                 input_delete(0);
2778                                 break;
2779                         }
2780 //                      /* Control-V -- force insert of next char */
2781 //                      if (c == CTRL('V')) {
2782 //                              if (safe_read(STDIN_FILENO, &c, 1) < 1)
2783 //                                      goto return_error_indicator;
2784 //                              if (c == 0) {
2785 //                                      beep();
2786 //                                      break;
2787 //                              }
2788 //                      }
2789                         if (ic < ' '
2790                          || (!ENABLE_UNICODE_SUPPORT && ic >= 256)
2791                          || (ENABLE_UNICODE_SUPPORT && ic >= VI_CMDMODE_BIT)
2792                         ) {
2793                                 /* If VI_CMDMODE_BIT is set, ic is >= 256
2794                                  * and vi mode ignores unexpected chars.
2795                                  * Otherwise, we are here if ic is a
2796                                  * control char or an unhandled ESC sequence,
2797                                  * which is also ignored.
2798                                  */
2799                                 break;
2800                         }
2801                         if ((int)command_len >= (maxsize - 2)) {
2802                                 /* Not enough space for the char and EOL */
2803                                 break;
2804                         }
2805
2806                         command_len++;
2807                         if (cursor == (command_len - 1)) {
2808                                 /* We are at the end, append */
2809                                 command_ps[cursor] = ic;
2810                                 command_ps[cursor + 1] = BB_NUL;
2811                                 put_cur_glyph_and_inc_cursor();
2812                                 if (unicode_bidi_isrtl(ic))
2813                                         input_backward(1);
2814                         } else {
2815                                 /* In the middle, insert */
2816                                 int sc = cursor;
2817
2818                                 memmove(command_ps + sc + 1, command_ps + sc,
2819                                         (command_len - sc) * sizeof(command_ps[0]));
2820                                 command_ps[sc] = ic;
2821                                 /* is right-to-left char, or neutral one (e.g. comma) was just added to rtl text? */
2822                                 if (!isrtl_str())
2823                                         sc++; /* no */
2824                                 put_till_end_and_adv_cursor();
2825                                 /* to prev x pos + 1 */
2826                                 input_backward(cursor - sc);
2827                         }
2828                         break;
2829                 } /* switch (ic) */
2830
2831                 if (break_out)
2832                         break;
2833
2834 #if ENABLE_FEATURE_TAB_COMPLETION
2835                 if (ic_raw != '\t')
2836                         lastWasTab = 0;
2837 #endif
2838         } /* while (1) */
2839
2840 #if ENABLE_FEATURE_EDITING_ASK_TERMINAL
2841         if (S.sent_ESC_br6n) {
2842                 /* "sleep 1; busybox ash" + hold [Enter] to trigger.
2843                  * We sent "ESC [ 6 n", but got '\n' first, and
2844                  * KEYCODE_CURSOR_POS response is now buffered from terminal.
2845                  * It's bad already and not much can be done with it
2846                  * (it _will_ be visible for the next process to read stdin),
2847                  * but without this delay it even shows up on the screen
2848                  * as garbage because we restore echo settings with tcsetattr
2849                  * before it comes in. UGLY!
2850                  */
2851                 usleep(20*1000);
2852         }
2853 #endif
2854
2855 /* End of bug-catching "command_must_not_be_used" trick */
2856 #undef command
2857
2858 #if ENABLE_UNICODE_SUPPORT
2859         command[0] = '\0';
2860         if (command_len > 0)
2861                 command_len = save_string(command, maxsize - 1);
2862         free(command_ps);
2863 #endif
2864
2865         if (command_len > 0) {
2866                 remember_in_history(command);
2867         }
2868
2869         if (break_out > 0) {
2870                 command[command_len++] = '\n';
2871                 command[command_len] = '\0';
2872         }
2873
2874 #if ENABLE_FEATURE_TAB_COMPLETION
2875         free_tab_completion_data();
2876 #endif
2877
2878         /* restore initial_settings */
2879         tcsetattr_stdin_TCSANOW(&initial_settings);
2880 #if ENABLE_FEATURE_EDITING_WINCH
2881         /* restore SIGWINCH handler */
2882         sigaction_set(SIGWINCH, &S.SIGWINCH_handler);
2883 #endif
2884         fflush_all();
2885
2886         len = command_len;
2887         DEINIT_S();
2888
2889         return len; /* can't return command_len, DEINIT_S() destroys it */
2890 }
2891
2892 #else  /* !FEATURE_EDITING */
2893
2894 #undef read_line_input
2895 int FAST_FUNC read_line_input(const char* prompt, char* command, int maxsize)
2896 {
2897         fputs(prompt, stdout);
2898         fflush_all();
2899         if (!fgets(command, maxsize, stdin))
2900                 return -1;
2901         return strlen(command);
2902 }
2903
2904 #endif  /* !FEATURE_EDITING */
2905
2906
2907 /*
2908  * Testing
2909  */
2910
2911 #ifdef TEST
2912
2913 #include <locale.h>
2914
2915 const char *applet_name = "debug stuff usage";
2916
2917 int main(int argc, char **argv)
2918 {
2919         char buff[MAX_LINELEN];
2920         char *prompt =
2921 #if ENABLE_FEATURE_EDITING_FANCY_PROMPT
2922                 "\\[\\033[32;1m\\]\\u@\\[\\x1b[33;1m\\]\\h:"
2923                 "\\[\\033[34;1m\\]\\w\\[\\033[35;1m\\] "
2924                 "\\!\\[\\e[36;1m\\]\\$ \\[\\E[m\\]";
2925 #else
2926                 "% ";
2927 #endif
2928
2929         while (1) {
2930                 int l;
2931                 l = read_line_input(prompt, buff);
2932                 if (l <= 0 || buff[l-1] != '\n')
2933                         break;
2934                 buff[l-1] = '\0';
2935                 printf("*** read_line_input() returned line =%s=\n", buff);
2936         }
2937         printf("*** read_line_input() detect ^D\n");
2938         return 0;
2939 }
2940
2941 #endif  /* TEST */