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