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