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