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