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