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