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