lineedit: implement Unicode-aware line editing (optional)
[platform/upstream/busybox.git] / libbb / lineedit.c
1 /* vi: set sw=4 ts=4: */
2 /*
3  * Termios command line History and Editing.
4  *
5  * Copyright (c) 1986-2003 may safely be consumed by a BSD or GPL license.
6  * Written by:   Vladimir Oleynik <dzo@simtreas.ru>
7  *
8  * Used ideas:
9  *      Adam Rogoyski    <rogoyski@cs.utexas.edu>
10  *      Dave Cinege      <dcinege@psychosis.com>
11  *      Jakub Jelinek (c) 1995
12  *      Erik Andersen    <andersen@codepoet.org> (Majorly adjusted for busybox)
13  *
14  * This code is 'as is' with no warranty.
15  */
16
17 /*
18  * Usage and known bugs:
19  * Terminal key codes are not extensive, 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 #if ENABLE_FEATURE_ASSUME_UNICODE
38 # include <wchar.h>
39 # include <wctype.h>
40 #endif
41
42 /* FIXME: obsolete CONFIG item? */
43 #define ENABLE_FEATURE_NONPRINTABLE_INVERSE_PUT 0
44
45 #ifdef TEST
46 # define ENABLE_FEATURE_EDITING 0
47 # define ENABLE_FEATURE_TAB_COMPLETION 0
48 # define ENABLE_FEATURE_USERNAME_COMPLETION 0
49 # define ENABLE_FEATURE_NONPRINTABLE_INVERSE_PUT 0
50 #endif
51
52
53 /* Entire file (except TESTing part) sits inside this #if */
54 #if ENABLE_FEATURE_EDITING
55
56
57 #define ENABLE_FEATURE_GETUSERNAME_AND_HOMEDIR \
58         (ENABLE_FEATURE_USERNAME_COMPLETION || ENABLE_FEATURE_EDITING_FANCY_PROMPT)
59 #define IF_FEATURE_GETUSERNAME_AND_HOMEDIR(...)
60 #if ENABLE_FEATURE_GETUSERNAME_AND_HOMEDIR
61 #undef IF_FEATURE_GETUSERNAME_AND_HOMEDIR
62 #define IF_FEATURE_GETUSERNAME_AND_HOMEDIR(...) __VA_ARGS__
63 #endif
64
65
66 #undef CHAR_T
67 #if ENABLE_FEATURE_ASSUME_UNICODE
68 # define BB_NUL L'\0'
69 # define CHAR_T wchar_t
70 # define BB_isspace(c) iswspace(c)
71 # define BB_isalnum(c) iswalnum(c)
72 # define BB_ispunct(c) iswpunct(c)
73 # define BB_isprint(c) iswprint(c)
74 /* this catches bugs */
75 # undef isspace
76 # undef isalnum
77 # undef ispunct
78 # undef isprint
79 # define isspace isspace_must_not_be_used
80 # define isalnum isalnum_must_not_be_used
81 # define ispunct ispunct_must_not_be_used
82 # define isprint isprint_must_not_be_used
83 #else
84 # define BB_NUL '\0'
85 # define CHAR_T char
86 # define BB_isspace(c) isspace(c)
87 # define BB_isalnum(c) isalnum(c)
88 # define BB_ispunct(c) ispunct(c)
89 # if ENABLE_LOCALE_SUPPORT
90 #  define BB_isprint(c) isprint(c)
91 # else
92 #  define BB_isprint(c) ((c) >= ' ' && (c) != ((unsigned char)'\233'))
93 # endif
94 #endif
95
96
97 enum {
98         /* We use int16_t for positions, need to limit line len */
99         MAX_LINELEN = CONFIG_FEATURE_EDITING_MAX_LEN < 0x7ff0
100                       ? CONFIG_FEATURE_EDITING_MAX_LEN
101                       : 0x7ff0
102 };
103
104 #if ENABLE_FEATURE_GETUSERNAME_AND_HOMEDIR
105 static const char null_str[] ALIGN1 = "";
106 #endif
107
108 /* We try to minimize both static and stack usage. */
109 struct lineedit_statics {
110         line_input_t *state;
111
112         volatile unsigned cmdedit_termw; /* = 80; */ /* actual terminal width */
113         sighandler_t previous_SIGWINCH_handler;
114
115         unsigned cmdedit_x;        /* real x (col) terminal position */
116         unsigned cmdedit_y;        /* pseudoreal y (row) terminal position */
117         unsigned cmdedit_prmt_len; /* length of prompt (without colors etc) */
118
119         unsigned cursor;
120         unsigned command_len;
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[%dA", 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 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
929                 *lastWasTab = TRUE;             /* flop trigger */
930
931                 /* Make a local copy of the string --
932                  * up to the position of the cursor */
933                 save_string(matchBuf, cursor + 1);
934                 tmp = matchBuf;
935
936                 find_type = find_match(matchBuf, &recalc_pos);
937
938                 /* Free up any memory already allocated */
939                 free_tab_completion_data();
940
941 #if ENABLE_FEATURE_USERNAME_COMPLETION
942                 /* If the word starts with `~' and there is no slash in the word,
943                  * then try completing this word as a username. */
944                 if (state->flags & USERNAME_COMPLETION)
945                         if (matchBuf[0] == '~' && strchr(matchBuf, '/') == 0)
946                                 username_tab_completion(matchBuf, NULL);
947 #endif
948                 /* Try to match any executable in our path and everything
949                  * in the current working directory */
950                 if (!matches)
951                         exe_n_cwd_tab_completion(matchBuf, find_type);
952                 /* Sort, then remove any duplicates found */
953                 if (matches) {
954                         unsigned i;
955                         int n = 0;
956                         qsort_string_vector(matches, num_matches);
957                         for (i = 0; i < num_matches - 1; ++i) {
958                                 if (matches[i] && matches[i+1]) { /* paranoia */
959                                         if (strcmp(matches[i], matches[i+1]) == 0) {
960                                                 free(matches[i]);
961                                                 matches[i] = NULL; /* paranoia */
962                                         } else {
963                                                 matches[n++] = matches[i];
964                                         }
965                                 }
966                         }
967                         matches[n] = matches[i];
968                         num_matches = n + 1;
969                 }
970                 /* Did we find exactly one match? */
971                 if (!matches || num_matches > 1) {
972                         beep();
973                         if (!matches)
974                                 return;         /* not found */
975                         /* find minimal match */
976                         tmp1 = xstrdup(matches[0]);
977                         for (tmp = tmp1; *tmp; tmp++)
978                                 for (len_found = 1; len_found < num_matches; len_found++)
979                                         if (matches[len_found][(tmp - tmp1)] != *tmp) {
980                                                 *tmp = '\0';
981                                                 break;
982                                         }
983                         if (*tmp1 == '\0') {        /* have unique */
984                                 free(tmp1);
985                                 return;
986                         }
987                         tmp = add_quote_for_spec_chars(tmp1);
988                         free(tmp1);
989                 } else {                        /* one match */
990                         tmp = add_quote_for_spec_chars(matches[0]);
991                         /* for next completion current found */
992                         *lastWasTab = FALSE;
993
994                         len_found = strlen(tmp);
995                         if (tmp[len_found-1] != '/') {
996                                 tmp[len_found] = ' ';
997                                 tmp[len_found+1] = '\0';
998                         }
999                 }
1000                 len_found = strlen(tmp);
1001                 /* have space to placed match? */
1002                 if ((len_found - strlen(matchBuf) + command_len) < MAX_LINELEN) {
1003                         /* before word for match   */
1004 //TODO:
1005 #if !ENABLE_FEATURE_ASSUME_UNICODE
1006                         command_ps[cursor - recalc_pos] = '\0';
1007                         /* save   tail line        */
1008                         strcpy(matchBuf, command_ps + cursor);
1009                         /* add    match            */
1010                         strcat(command_ps, tmp);
1011                         /* add    tail             */
1012                         strcat(command_ps, matchBuf);
1013                         /* back to begin word for match    */
1014                         input_backward(recalc_pos);
1015                         /* new pos                         */
1016                         recalc_pos = cursor + len_found;
1017                         /* new len                         */
1018                         command_len = strlen(command_ps);
1019                         /* write out the matched command   */
1020 #endif
1021                         redraw(cmdedit_y, command_len - recalc_pos);
1022                 }
1023                 free(tmp);
1024 #undef matchBuf
1025         } else {
1026                 /* Ok -- the last char was a TAB.  Since they
1027                  * just hit TAB again, print a list of all the
1028                  * available choices... */
1029                 if (matches && num_matches > 0) {
1030                         int sav_cursor = cursor;        /* change goto_new_line() */
1031
1032                         /* Go to the next line */
1033                         goto_new_line();
1034                         showfiles();
1035                         redraw(0, command_len - sav_cursor);
1036                 }
1037         }
1038 }
1039
1040 #endif  /* FEATURE_COMMAND_TAB_COMPLETION */
1041
1042
1043 line_input_t* FAST_FUNC new_line_input_t(int flags)
1044 {
1045         line_input_t *n = xzalloc(sizeof(*n));
1046         n->flags = flags;
1047         return n;
1048 }
1049
1050
1051 #if MAX_HISTORY > 0
1052
1053 static void save_command_ps_at_cur_history(void)
1054 {
1055         if (command_ps[0] != BB_NUL) {
1056                 int cur = state->cur_history;
1057                 free(state->history[cur]);
1058
1059 #if ENABLE_FEATURE_ASSUME_UNICODE
1060                 {
1061                         char tbuf[MAX_LINELEN];
1062                         save_string(tbuf, sizeof(tbuf));
1063                         state->history[cur] = xstrdup(tbuf);
1064                 }
1065 #else
1066                 state->history[cur] = xstrdup(command_ps);
1067 #endif
1068         }
1069 }
1070
1071 /* state->flags is already checked to be nonzero */
1072 static int get_previous_history(void)
1073 {
1074         if ((state->flags & DO_HISTORY) && state->cur_history) {
1075                 save_command_ps_at_cur_history();
1076                 state->cur_history--;
1077                 return 1;
1078         }
1079         beep();
1080         return 0;
1081 }
1082
1083 static int get_next_history(void)
1084 {
1085         if (state->flags & DO_HISTORY) {
1086                 if (state->cur_history < state->cnt_history) {
1087                         save_command_ps_at_cur_history(); /* save the current history line */
1088                         return ++state->cur_history;
1089                 }
1090         }
1091         beep();
1092         return 0;
1093 }
1094
1095 #if ENABLE_FEATURE_EDITING_SAVEHISTORY
1096 /* We try to ensure that concurrent additions to the history
1097  * do not overwrite each other.
1098  * Otherwise shell users get unhappy.
1099  *
1100  * History file is trimmed lazily, when it grows several times longer
1101  * than configured MAX_HISTORY lines.
1102  */
1103
1104 static void free_line_input_t(line_input_t *n)
1105 {
1106         int i = n->cnt_history;
1107         while (i > 0)
1108                 free(n->history[--i]);
1109         free(n);
1110 }
1111
1112 /* state->flags is already checked to be nonzero */
1113 static void load_history(line_input_t *st_parm)
1114 {
1115         char *temp_h[MAX_HISTORY];
1116         char *line;
1117         FILE *fp;
1118         unsigned idx, i, line_len;
1119
1120         /* NB: do not trash old history if file can't be opened */
1121
1122         fp = fopen_for_read(st_parm->hist_file);
1123         if (fp) {
1124                 /* clean up old history */
1125                 for (idx = st_parm->cnt_history; idx > 0;) {
1126                         idx--;
1127                         free(st_parm->history[idx]);
1128                         st_parm->history[idx] = NULL;
1129                 }
1130
1131                 /* fill temp_h[], retaining only last MAX_HISTORY lines */
1132                 memset(temp_h, 0, sizeof(temp_h));
1133                 st_parm->cnt_history_in_file = idx = 0;
1134                 while ((line = xmalloc_fgetline(fp)) != NULL) {
1135                         if (line[0] == '\0') {
1136                                 free(line);
1137                                 continue;
1138                         }
1139                         free(temp_h[idx]);
1140                         temp_h[idx] = line;
1141                         st_parm->cnt_history_in_file++;
1142                         idx++;
1143                         if (idx == MAX_HISTORY)
1144                                 idx = 0;
1145                 }
1146                 fclose(fp);
1147
1148                 /* find first non-NULL temp_h[], if any */
1149                 if (st_parm->cnt_history_in_file) {
1150                         while (temp_h[idx] == NULL) {
1151                                 idx++;
1152                                 if (idx == MAX_HISTORY)
1153                                         idx = 0;
1154                         }
1155                 }
1156
1157                 /* copy temp_h[] to st_parm->history[] */
1158                 for (i = 0; i < MAX_HISTORY;) {
1159                         line = temp_h[idx];
1160                         if (!line)
1161                                 break;
1162                         idx++;
1163                         if (idx == MAX_HISTORY)
1164                                 idx = 0;
1165                         line_len = strlen(line);
1166                         if (line_len >= MAX_LINELEN)
1167                                 line[MAX_LINELEN-1] = '\0';
1168                         st_parm->history[i++] = line;
1169                 }
1170                 st_parm->cnt_history = i;
1171         }
1172 }
1173
1174 /* state->flags is already checked to be nonzero */
1175 static void save_history(char *str)
1176 {
1177         int fd;
1178         int len, len2;
1179
1180         fd = open(state->hist_file, O_WRONLY | O_CREAT | O_APPEND, 0666);
1181         if (fd < 0)
1182                 return;
1183         xlseek(fd, 0, SEEK_END); /* paranoia */
1184         len = strlen(str);
1185         str[len] = '\n'; /* we (try to) do atomic write */
1186         len2 = full_write(fd, str, len + 1);
1187         str[len] = '\0';
1188         close(fd);
1189         if (len2 != len + 1)
1190                 return; /* "wtf?" */
1191
1192         /* did we write so much that history file needs trimming? */
1193         state->cnt_history_in_file++;
1194         if (state->cnt_history_in_file > MAX_HISTORY * 4) {
1195                 FILE *fp;
1196                 char *new_name;
1197                 line_input_t *st_temp;
1198                 int i;
1199
1200                 /* we may have concurrently written entries from others.
1201                  * load them */
1202                 st_temp = new_line_input_t(state->flags);
1203                 st_temp->hist_file = state->hist_file;
1204                 load_history(st_temp);
1205
1206                 /* write out temp file and replace hist_file atomically */
1207                 new_name = xasprintf("%s.%u.new", state->hist_file, (int) getpid());
1208                 fp = fopen_for_write(new_name);
1209                 if (fp) {
1210                         for (i = 0; i < st_temp->cnt_history; i++)
1211                                 fprintf(fp, "%s\n", st_temp->history[i]);
1212                         fclose(fp);
1213                         if (rename(new_name, state->hist_file) == 0)
1214                                 state->cnt_history_in_file = st_temp->cnt_history;
1215                 }
1216                 free(new_name);
1217                 free_line_input_t(st_temp);
1218         }
1219 }
1220 #else
1221 #define load_history(a) ((void)0)
1222 #define save_history(a) ((void)0)
1223 #endif /* FEATURE_COMMAND_SAVEHISTORY */
1224
1225 static void remember_in_history(char *str)
1226 {
1227         int i;
1228
1229         if (!(state->flags & DO_HISTORY))
1230                 return;
1231         if (str[0] == '\0')
1232                 return;
1233         i = state->cnt_history;
1234         /* Don't save dupes */
1235         if (i && strcmp(state->history[i-1], str) == 0)
1236                 return;
1237
1238         free(state->history[MAX_HISTORY]); /* redundant, paranoia */
1239         state->history[MAX_HISTORY] = NULL; /* redundant, paranoia */
1240
1241         /* If history[] is full, remove the oldest command */
1242         /* we need to keep history[MAX_HISTORY] empty, hence >=, not > */
1243         if (i >= MAX_HISTORY) {
1244                 free(state->history[0]);
1245                 for (i = 0; i < MAX_HISTORY-1; i++)
1246                         state->history[i] = state->history[i+1];
1247                 /* i == MAX_HISTORY-1 */
1248         }
1249         /* i <= MAX_HISTORY-1 */
1250         state->history[i++] = xstrdup(str);
1251         /* i <= MAX_HISTORY */
1252         state->cur_history = i;
1253         state->cnt_history = i;
1254 #if ENABLE_FEATURE_EDITING_SAVEHISTORY
1255         if ((state->flags & SAVE_HISTORY) && state->hist_file)
1256                 save_history(str);
1257 #endif
1258         IF_FEATURE_EDITING_FANCY_PROMPT(num_ok_lines++;)
1259 }
1260
1261 #else /* MAX_HISTORY == 0 */
1262 #define remember_in_history(a) ((void)0)
1263 #endif /* MAX_HISTORY */
1264
1265
1266 /*
1267  * This function is used to grab a character buffer
1268  * from the input file descriptor and allows you to
1269  * a string with full command editing (sort of like
1270  * a mini readline).
1271  *
1272  * The following standard commands are not implemented:
1273  * ESC-b -- Move back one word
1274  * ESC-f -- Move forward one word
1275  * ESC-d -- Delete back one word
1276  * ESC-h -- Delete forward one word
1277  * CTL-t -- Transpose two characters
1278  *
1279  * Minimalist vi-style command line editing available if configured.
1280  * vi mode implemented 2005 by Paul Fox <pgf@foxharp.boston.ma.us>
1281  */
1282
1283 #if ENABLE_FEATURE_EDITING_VI
1284 static void
1285 vi_Word_motion(int eat)
1286 {
1287         CHAR_T *command = command_ps;
1288
1289         while (cursor < command_len && !BB_isspace(command[cursor]))
1290                 input_forward();
1291         if (eat) while (cursor < command_len && BB_isspace(command[cursor]))
1292                 input_forward();
1293 }
1294
1295 static void
1296 vi_word_motion(int eat)
1297 {
1298         CHAR_T *command = command_ps;
1299
1300         if (BB_isalnum(command[cursor]) || command[cursor] == '_') {
1301                 while (cursor < command_len
1302                  && (BB_isalnum(command[cursor+1]) || command[cursor+1] == '_'))
1303                         input_forward();
1304         } else if (BB_ispunct(command[cursor])) {
1305                 while (cursor < command_len && BB_ispunct(command[cursor+1]))
1306                         input_forward();
1307         }
1308
1309         if (cursor < command_len)
1310                 input_forward();
1311
1312         if (eat && cursor < command_len && BB_isspace(command[cursor]))
1313                 while (cursor < command_len && BB_isspace(command[cursor]))
1314                         input_forward();
1315 }
1316
1317 static void
1318 vi_End_motion(void)
1319 {
1320         CHAR_T *command = command_ps;
1321
1322         input_forward();
1323         while (cursor < command_len && BB_isspace(command[cursor]))
1324                 input_forward();
1325         while (cursor < command_len-1 && !BB_isspace(command[cursor+1]))
1326                 input_forward();
1327 }
1328
1329 static void
1330 vi_end_motion(void)
1331 {
1332         CHAR_T *command = command_ps;
1333
1334         if (cursor >= command_len-1)
1335                 return;
1336         input_forward();
1337         while (cursor < command_len-1 && BB_isspace(command[cursor]))
1338                 input_forward();
1339         if (cursor >= command_len-1)
1340                 return;
1341         if (BB_isalnum(command[cursor]) || command[cursor] == '_') {
1342                 while (cursor < command_len-1
1343                  && (BB_isalnum(command[cursor+1]) || command[cursor+1] == '_')
1344                 ) {
1345                         input_forward();
1346                 }
1347         } else if (BB_ispunct(command[cursor])) {
1348                 while (cursor < command_len-1 && BB_ispunct(command[cursor+1]))
1349                         input_forward();
1350         }
1351 }
1352
1353 static void
1354 vi_Back_motion(void)
1355 {
1356         CHAR_T *command = command_ps;
1357
1358         while (cursor > 0 && BB_isspace(command[cursor-1]))
1359                 input_backward(1);
1360         while (cursor > 0 && !BB_isspace(command[cursor-1]))
1361                 input_backward(1);
1362 }
1363
1364 static void
1365 vi_back_motion(void)
1366 {
1367         CHAR_T *command = command_ps;
1368
1369         if (cursor <= 0)
1370                 return;
1371         input_backward(1);
1372         while (cursor > 0 && BB_isspace(command[cursor]))
1373                 input_backward(1);
1374         if (cursor <= 0)
1375                 return;
1376         if (BB_isalnum(command[cursor]) || command[cursor] == '_') {
1377                 while (cursor > 0
1378                  && (BB_isalnum(command[cursor-1]) || command[cursor-1] == '_')
1379                 ) {
1380                         input_backward(1);
1381                 }
1382         } else if (BB_ispunct(command[cursor])) {
1383                 while (cursor > 0 && BB_ispunct(command[cursor-1]))
1384                         input_backward(1);
1385         }
1386 }
1387 #endif
1388
1389
1390 /*
1391  * read_line_input and its helpers
1392  */
1393
1394 #if !ENABLE_FEATURE_EDITING_FANCY_PROMPT
1395 static void parse_and_put_prompt(const char *prmt_ptr)
1396 {
1397         cmdedit_prompt = prmt_ptr;
1398         cmdedit_prmt_len = strlen(prmt_ptr);
1399         put_prompt();
1400 }
1401 #else
1402 static void parse_and_put_prompt(const char *prmt_ptr)
1403 {
1404         int prmt_len = 0;
1405         size_t cur_prmt_len = 0;
1406         char flg_not_length = '[';
1407         char *prmt_mem_ptr = xzalloc(1);
1408         char *cwd_buf = xrealloc_getcwd_or_warn(NULL);
1409         char cbuf[2];
1410         char c;
1411         char *pbuf;
1412
1413         cmdedit_prmt_len = 0;
1414
1415         if (!cwd_buf) {
1416                 cwd_buf = (char *)bb_msg_unknown;
1417         }
1418
1419         cbuf[1] = '\0'; /* never changes */
1420
1421         while (*prmt_ptr) {
1422                 char *free_me = NULL;
1423
1424                 pbuf = cbuf;
1425                 c = *prmt_ptr++;
1426                 if (c == '\\') {
1427                         const char *cp = prmt_ptr;
1428                         int l;
1429
1430                         c = bb_process_escape_sequence(&prmt_ptr);
1431                         if (prmt_ptr == cp) {
1432                                 if (*cp == '\0')
1433                                         break;
1434                                 c = *prmt_ptr++;
1435
1436                                 switch (c) {
1437 #if ENABLE_FEATURE_GETUSERNAME_AND_HOMEDIR
1438                                 case 'u':
1439                                         pbuf = user_buf ? user_buf : (char*)"";
1440                                         break;
1441 #endif
1442                                 case 'h':
1443                                         pbuf = free_me = safe_gethostname();
1444                                         *strchrnul(pbuf, '.') = '\0';
1445                                         break;
1446                                 case '$':
1447                                         c = (geteuid() == 0 ? '#' : '$');
1448                                         break;
1449 #if ENABLE_FEATURE_GETUSERNAME_AND_HOMEDIR
1450                                 case 'w':
1451                                         /* /home/user[/something] -> ~[/something] */
1452                                         pbuf = cwd_buf;
1453                                         l = strlen(home_pwd_buf);
1454                                         if (l != 0
1455                                          && strncmp(home_pwd_buf, cwd_buf, l) == 0
1456                                          && (cwd_buf[l]=='/' || cwd_buf[l]=='\0')
1457                                          && strlen(cwd_buf + l) < PATH_MAX
1458                                         ) {
1459                                                 pbuf = free_me = xasprintf("~%s", cwd_buf + l);
1460                                         }
1461                                         break;
1462 #endif
1463                                 case 'W':
1464                                         pbuf = cwd_buf;
1465                                         cp = strrchr(pbuf, '/');
1466                                         if (cp != NULL && cp != pbuf)
1467                                                 pbuf += (cp-pbuf) + 1;
1468                                         break;
1469                                 case '!':
1470                                         pbuf = free_me = xasprintf("%d", num_ok_lines);
1471                                         break;
1472                                 case 'e': case 'E':     /* \e \E = \033 */
1473                                         c = '\033';
1474                                         break;
1475                                 case 'x': case 'X': {
1476                                         char buf2[4];
1477                                         for (l = 0; l < 3;) {
1478                                                 unsigned h;
1479                                                 buf2[l++] = *prmt_ptr;
1480                                                 buf2[l] = '\0';
1481                                                 h = strtoul(buf2, &pbuf, 16);
1482                                                 if (h > UCHAR_MAX || (pbuf - buf2) < l) {
1483                                                         buf2[--l] = '\0';
1484                                                         break;
1485                                                 }
1486                                                 prmt_ptr++;
1487                                         }
1488                                         c = (char)strtoul(buf2, NULL, 16);
1489                                         if (c == 0)
1490                                                 c = '?';
1491                                         pbuf = cbuf;
1492                                         break;
1493                                 }
1494                                 case '[': case ']':
1495                                         if (c == flg_not_length) {
1496                                                 flg_not_length = (flg_not_length == '[' ? ']' : '[');
1497                                                 continue;
1498                                         }
1499                                         break;
1500                                 } /* switch */
1501                         } /* if */
1502                 } /* if */
1503                 cbuf[0] = c;
1504                 cur_prmt_len = strlen(pbuf);
1505                 prmt_len += cur_prmt_len;
1506                 if (flg_not_length != ']')
1507                         cmdedit_prmt_len += cur_prmt_len;
1508                 prmt_mem_ptr = strcat(xrealloc(prmt_mem_ptr, prmt_len+1), pbuf);
1509                 free(free_me);
1510         } /* while */
1511
1512         if (cwd_buf != (char *)bb_msg_unknown)
1513                 free(cwd_buf);
1514         cmdedit_prompt = prmt_mem_ptr;
1515         put_prompt();
1516 }
1517 #endif
1518
1519 static void cmdedit_setwidth(unsigned w, int redraw_flg)
1520 {
1521         cmdedit_termw = w;
1522         if (redraw_flg) {
1523                 /* new y for current cursor */
1524                 int new_y = (cursor + cmdedit_prmt_len) / w;
1525                 /* redraw */
1526                 redraw((new_y >= cmdedit_y ? new_y : cmdedit_y), command_len - cursor);
1527                 fflush(stdout);
1528         }
1529 }
1530
1531 static void win_changed(int nsig)
1532 {
1533         unsigned width;
1534         get_terminal_width_height(0, &width, NULL);
1535         cmdedit_setwidth(width, nsig /* - just a yes/no flag */);
1536         if (nsig == SIGWINCH)
1537                 signal(SIGWINCH, win_changed); /* rearm ourself */
1538 }
1539
1540 static int lineedit_read_key(char *read_key_buffer)
1541 {
1542         int64_t ic;
1543         struct pollfd pfd;
1544         int delay = -1;
1545 #if ENABLE_FEATURE_ASSUME_UNICODE
1546         char unicode_buf[MB_CUR_MAX + 1];
1547         int unicode_idx = 0;
1548 #endif
1549
1550         pfd.fd = STDIN_FILENO;
1551         pfd.events = POLLIN;
1552         do {
1553  poll_again:
1554                 if (read_key_buffer[0] == 0) {
1555                         /* Wait for input. Can't just call read_key,
1556                          * it returns at once if stdin
1557                          * is in non-blocking mode. */
1558                         safe_poll(&pfd, 1, delay);
1559                 }
1560                 /* Note: read_key sets errno to 0 on success: */
1561                 ic = read_key(STDIN_FILENO, read_key_buffer);
1562                 if (ENABLE_FEATURE_EDITING_ASK_TERMINAL
1563                  && (int32_t)ic == KEYCODE_CURSOR_POS
1564                 ) {
1565                         int col = ((ic >> 32) & 0x7fff) - 1;
1566                         if (col > cmdedit_prmt_len) {
1567                                 cmdedit_x += (col - cmdedit_prmt_len);
1568                                 while (cmdedit_x >= cmdedit_termw) {
1569                                         cmdedit_x -= cmdedit_termw;
1570                                         cmdedit_y++;
1571                                 }
1572                         }
1573                         goto poll_again;
1574                 }
1575
1576 #if ENABLE_FEATURE_ASSUME_UNICODE
1577                 {
1578                         wchar_t wc;
1579
1580                         if ((int32_t)ic < 0) /* KEYCODE_xxx */
1581                                 return ic;
1582                         unicode_buf[unicode_idx++] = ic;
1583                         unicode_buf[unicode_idx] = '\0';
1584                         if (mbstowcs(&wc, unicode_buf, 1) < 1 && unicode_idx < MB_CUR_MAX) {
1585                                 delay = 50;
1586                                 goto poll_again;
1587                         }
1588                         ic = wc;
1589                 }
1590 #endif
1591         } while (errno == EAGAIN);
1592
1593         return ic;
1594 }
1595
1596 /* leave out the "vi-mode"-only case labels if vi editing isn't
1597  * configured. */
1598 #define vi_case(caselabel) IF_FEATURE_EDITING(case caselabel)
1599
1600 /* convert uppercase ascii to equivalent control char, for readability */
1601 #undef CTRL
1602 #define CTRL(a) ((a) & ~0x40)
1603
1604 /* Returns:
1605  * -1 on read errors or EOF, or on bare Ctrl-D,
1606  * 0  on ctrl-C (the line entered is still returned in 'command'),
1607  * >0 length of input string, including terminating '\n'
1608  */
1609 int FAST_FUNC read_line_input(const char *prompt, char *command, int maxsize, line_input_t *st)
1610 {
1611         int len;
1612 #if ENABLE_FEATURE_TAB_COMPLETION
1613         smallint lastWasTab = FALSE;
1614 #endif
1615         smallint break_out = 0;
1616 #if ENABLE_FEATURE_EDITING_VI
1617         smallint vi_cmdmode = 0;
1618 #endif
1619         struct termios initial_settings;
1620         struct termios new_settings;
1621         char read_key_buffer[KEYCODE_BUFFER_SIZE];
1622
1623         INIT_S();
1624
1625         if (tcgetattr(STDIN_FILENO, &initial_settings) < 0
1626          || !(initial_settings.c_lflag & ECHO)
1627         ) {
1628                 /* Happens when e.g. stty -echo was run before */
1629                 parse_and_put_prompt(prompt);
1630                 fflush(stdout);
1631                 if (fgets(command, maxsize, stdin) == NULL)
1632                         len = -1; /* EOF or error */
1633                 else
1634                         len = strlen(command);
1635                 DEINIT_S();
1636                 return len;
1637         }
1638
1639 // FIXME: audit & improve this
1640         if (maxsize > MAX_LINELEN)
1641                 maxsize = MAX_LINELEN;
1642
1643         /* With null flags, no other fields are ever used */
1644         state = st ? st : (line_input_t*) &const_int_0;
1645 #if ENABLE_FEATURE_EDITING_SAVEHISTORY
1646         if ((state->flags & SAVE_HISTORY) && state->hist_file)
1647                 if (state->cnt_history == 0)
1648                         load_history(state);
1649 #endif
1650         if (state->flags & DO_HISTORY)
1651                 state->cur_history = state->cnt_history;
1652
1653         /* prepare before init handlers */
1654         cmdedit_y = 0;  /* quasireal y, not true if line > xt*yt */
1655         command_len = 0;
1656 #if ENABLE_FEATURE_ASSUME_UNICODE
1657         command_ps = xzalloc(maxsize * sizeof(command_ps[0]));
1658 #else
1659         command_ps = command;
1660         command[0] = '\0';
1661 #endif
1662 #define command command_must_not_be_used
1663
1664         new_settings = initial_settings;
1665         new_settings.c_lflag &= ~ICANON;        /* unbuffered input */
1666         /* Turn off echoing and CTRL-C, so we can trap it */
1667         new_settings.c_lflag &= ~(ECHO | ECHONL | ISIG);
1668         /* Hmm, in linux c_cc[] is not parsed if ICANON is off */
1669         new_settings.c_cc[VMIN] = 1;
1670         new_settings.c_cc[VTIME] = 0;
1671         /* Turn off CTRL-C, so we can trap it */
1672 #ifndef _POSIX_VDISABLE
1673 #define _POSIX_VDISABLE '\0'
1674 #endif
1675         new_settings.c_cc[VINTR] = _POSIX_VDISABLE;
1676         tcsetattr_stdin_TCSANOW(&new_settings);
1677
1678         /* Now initialize things */
1679         previous_SIGWINCH_handler = signal(SIGWINCH, win_changed);
1680         win_changed(0); /* do initial resizing */
1681 #if ENABLE_FEATURE_GETUSERNAME_AND_HOMEDIR
1682         {
1683                 struct passwd *entry;
1684
1685                 entry = getpwuid(geteuid());
1686                 if (entry) {
1687                         user_buf = xstrdup(entry->pw_name);
1688                         home_pwd_buf = xstrdup(entry->pw_dir);
1689                 }
1690         }
1691 #endif
1692
1693 #if 0
1694         for (i = 0; i <= MAX_HISTORY; i++)
1695                 bb_error_msg("history[%d]:'%s'", i, state->history[i]);
1696         bb_error_msg("cur_history:%d cnt_history:%d", state->cur_history, state->cnt_history);
1697 #endif
1698
1699         /* Print out the command prompt */
1700         parse_and_put_prompt(prompt);
1701
1702         read_key_buffer[0] = 0;
1703         while (1) {
1704                 /*
1705                  * The emacs and vi modes share much of the code in the big
1706                  * command loop.  Commands entered when in vi's command mode
1707                  * (aka "escape mode") get an extra bit added to distinguish
1708                  * them - this keeps them from being self-inserted. This
1709                  * clutters the big switch a bit, but keeps all the code
1710                  * in one place.
1711                  */
1712                 enum {
1713                         VI_CMDMODE_BIT = 0x40000000,
1714                         /* 0x80000000 bit flags KEYCODE_xxx */
1715                 };
1716                 int32_t ic;
1717
1718                 fflush(NULL);
1719                 ic = lineedit_read_key(read_key_buffer);
1720
1721 #if ENABLE_FEATURE_EDITING_VI
1722                 newdelflag = 1;
1723                 if (vi_cmdmode) {
1724                         /* btw, since KEYCODE_xxx are all < 0, this doesn't
1725                          * change ic if it contains one of them: */
1726                         ic |= VI_CMDMODE_BIT;
1727                 }
1728 #endif
1729
1730                 switch (ic) {
1731                 case '\n':
1732                 case '\r':
1733                 vi_case('\n'|VI_CMDMODE_BIT:)
1734                 vi_case('\r'|VI_CMDMODE_BIT:)
1735                         /* Enter */
1736                         goto_new_line();
1737                         break_out = 1;
1738                         break;
1739                 case CTRL('A'):
1740                 vi_case('0'|VI_CMDMODE_BIT:)
1741                         /* Control-a -- Beginning of line */
1742                         input_backward(cursor);
1743                         break;
1744                 case CTRL('B'):
1745                 vi_case('h'|VI_CMDMODE_BIT:)
1746                 vi_case('\b'|VI_CMDMODE_BIT:)
1747                 vi_case('\x7f'|VI_CMDMODE_BIT:) /* DEL */
1748                         /* Control-b -- Move back one character */
1749                         input_backward(1);
1750                         break;
1751                 case CTRL('C'):
1752                 vi_case(CTRL('C')|VI_CMDMODE_BIT:)
1753                         /* Control-c -- stop gathering input */
1754                         goto_new_line();
1755                         command_len = 0;
1756                         break_out = -1; /* "do not append '\n'" */
1757                         break;
1758                 case CTRL('D'):
1759                         /* Control-d -- Delete one character, or exit
1760                          * if the len=0 and no chars to delete */
1761                         if (command_len == 0) {
1762                                 errno = 0;
1763 #if ENABLE_FEATURE_EDITING_VI
1764  prepare_to_die:
1765 #endif
1766                                 /* to control stopped jobs */
1767                                 break_out = command_len = -1;
1768                                 break;
1769                         }
1770                         input_delete(0);
1771                         break;
1772                 case CTRL('E'):
1773                 vi_case('$'|VI_CMDMODE_BIT:)
1774                         /* Control-e -- End of line */
1775                         input_end();
1776                         break;
1777                 case CTRL('F'):
1778                 vi_case('l'|VI_CMDMODE_BIT:)
1779                 vi_case(' '|VI_CMDMODE_BIT:)
1780                         /* Control-f -- Move forward one character */
1781                         input_forward();
1782                         break;
1783                 case '\b':
1784                 case '\x7f': /* DEL */
1785                         /* Control-h and DEL */
1786                         input_backspace();
1787                         break;
1788 #if ENABLE_FEATURE_TAB_COMPLETION
1789                 case '\t':
1790                         input_tab(&lastWasTab);
1791                         break;
1792 #endif
1793                 case CTRL('K'):
1794                         /* Control-k -- clear to end of line */
1795                         command_ps[cursor] = BB_NUL;
1796                         command_len = cursor;
1797                         printf("\033[J");
1798                         break;
1799                 case CTRL('L'):
1800                 vi_case(CTRL('L')|VI_CMDMODE_BIT:)
1801                         /* Control-l -- clear screen */
1802                         printf("\033[H");
1803                         redraw(0, command_len - cursor);
1804                         break;
1805 #if MAX_HISTORY > 0
1806                 case CTRL('N'):
1807                 vi_case(CTRL('N')|VI_CMDMODE_BIT:)
1808                 vi_case('j'|VI_CMDMODE_BIT:)
1809                         /* Control-n -- Get next command in history */
1810                         if (get_next_history())
1811                                 goto rewrite_line;
1812                         break;
1813                 case CTRL('P'):
1814                 vi_case(CTRL('P')|VI_CMDMODE_BIT:)
1815                 vi_case('k'|VI_CMDMODE_BIT:)
1816                         /* Control-p -- Get previous command from history */
1817                         if (get_previous_history())
1818                                 goto rewrite_line;
1819                         break;
1820 #endif
1821                 case CTRL('U'):
1822                 vi_case(CTRL('U')|VI_CMDMODE_BIT:)
1823                         /* Control-U -- Clear line before cursor */
1824                         if (cursor) {
1825                                 command_len -= cursor;
1826                                 memmove(command_ps, command_ps + cursor,
1827                                         (command_len + 1) * sizeof(command_ps[0]));
1828                                 redraw(cmdedit_y, command_len);
1829                         }
1830                         break;
1831                 case CTRL('W'):
1832                 vi_case(CTRL('W')|VI_CMDMODE_BIT:)
1833                         /* Control-W -- Remove the last word */
1834                         while (cursor > 0 && BB_isspace(command_ps[cursor-1]))
1835                                 input_backspace();
1836                         while (cursor > 0 && !BB_isspace(command_ps[cursor-1]))
1837                                 input_backspace();
1838                         break;
1839
1840 #if ENABLE_FEATURE_EDITING_VI
1841                 case 'i'|VI_CMDMODE_BIT:
1842                         vi_cmdmode = 0;
1843                         break;
1844                 case 'I'|VI_CMDMODE_BIT:
1845                         input_backward(cursor);
1846                         vi_cmdmode = 0;
1847                         break;
1848                 case 'a'|VI_CMDMODE_BIT:
1849                         input_forward();
1850                         vi_cmdmode = 0;
1851                         break;
1852                 case 'A'|VI_CMDMODE_BIT:
1853                         input_end();
1854                         vi_cmdmode = 0;
1855                         break;
1856                 case 'x'|VI_CMDMODE_BIT:
1857                         input_delete(1);
1858                         break;
1859                 case 'X'|VI_CMDMODE_BIT:
1860                         if (cursor > 0) {
1861                                 input_backward(1);
1862                                 input_delete(1);
1863                         }
1864                         break;
1865                 case 'W'|VI_CMDMODE_BIT:
1866                         vi_Word_motion(1);
1867                         break;
1868                 case 'w'|VI_CMDMODE_BIT:
1869                         vi_word_motion(1);
1870                         break;
1871                 case 'E'|VI_CMDMODE_BIT:
1872                         vi_End_motion();
1873                         break;
1874                 case 'e'|VI_CMDMODE_BIT:
1875                         vi_end_motion();
1876                         break;
1877                 case 'B'|VI_CMDMODE_BIT:
1878                         vi_Back_motion();
1879                         break;
1880                 case 'b'|VI_CMDMODE_BIT:
1881                         vi_back_motion();
1882                         break;
1883                 case 'C'|VI_CMDMODE_BIT:
1884                         vi_cmdmode = 0;
1885                         /* fall through */
1886                 case 'D'|VI_CMDMODE_BIT:
1887                         goto clear_to_eol;
1888
1889                 case 'c'|VI_CMDMODE_BIT:
1890                         vi_cmdmode = 0;
1891                         /* fall through */
1892                 case 'd'|VI_CMDMODE_BIT: {
1893                         int nc, sc;
1894                         int prev_ic;
1895
1896                         sc = cursor;
1897                         prev_ic = ic;
1898
1899                         ic = lineedit_read_key(read_key_buffer);
1900                         if (errno) /* error */
1901                                 goto prepare_to_die;
1902
1903                         if ((ic | VI_CMDMODE_BIT) == prev_ic) {
1904                                 /* "cc", "dd" */
1905                                 input_backward(cursor);
1906                                 goto clear_to_eol;
1907                                 break;
1908                         }
1909                         switch (ic) {
1910                         case 'w':
1911                         case 'W':
1912                         case 'e':
1913                         case 'E':
1914                                 switch (ic) {
1915                                 case 'w':   /* "dw", "cw" */
1916                                         vi_word_motion(vi_cmdmode);
1917                                         break;
1918                                 case 'W':   /* 'dW', 'cW' */
1919                                         vi_Word_motion(vi_cmdmode);
1920                                         break;
1921                                 case 'e':   /* 'de', 'ce' */
1922                                         vi_end_motion();
1923                                         input_forward();
1924                                         break;
1925                                 case 'E':   /* 'dE', 'cE' */
1926                                         vi_End_motion();
1927                                         input_forward();
1928                                         break;
1929                                 }
1930                                 nc = cursor;
1931                                 input_backward(cursor - sc);
1932                                 while (nc-- > cursor)
1933                                         input_delete(1);
1934                                 break;
1935                         case 'b':  /* "db", "cb" */
1936                         case 'B':  /* implemented as B */
1937                                 if (ic == 'b')
1938                                         vi_back_motion();
1939                                 else
1940                                         vi_Back_motion();
1941                                 while (sc-- > cursor)
1942                                         input_delete(1);
1943                                 break;
1944                         case ' ':  /* "d ", "c " */
1945                                 input_delete(1);
1946                                 break;
1947                         case '$':  /* "d$", "c$" */
1948  clear_to_eol:
1949                                 while (cursor < command_len)
1950                                         input_delete(1);
1951                                 break;
1952                         }
1953                         break;
1954                 }
1955                 case 'p'|VI_CMDMODE_BIT:
1956                         input_forward();
1957                         /* fallthrough */
1958                 case 'P'|VI_CMDMODE_BIT:
1959                         put();
1960                         break;
1961                 case 'r'|VI_CMDMODE_BIT:
1962                         ic = lineedit_read_key(read_key_buffer);
1963                         if (errno) /* error */
1964                                 goto prepare_to_die;
1965                         if (ic < ' ' || ic > 255) {
1966                                 beep();
1967                         } else {
1968                                 command_ps[cursor] = ic;
1969                                 bb_putchar(ic);
1970                                 bb_putchar('\b');
1971                         }
1972                         break;
1973                 case '\x1b': /* ESC */
1974                         if (state->flags & VI_MODE) {
1975                                 /* insert mode --> command mode */
1976                                 vi_cmdmode = 1;
1977                                 input_backward(1);
1978                         }
1979                         break;
1980 #endif /* FEATURE_COMMAND_EDITING_VI */
1981
1982 #if MAX_HISTORY > 0
1983                 case KEYCODE_UP:
1984                         if (get_previous_history())
1985                                 goto rewrite_line;
1986                         beep();
1987                         break;
1988                 case KEYCODE_DOWN:
1989                         if (!get_next_history())
1990                                 break;
1991  rewrite_line:
1992                         /* Rewrite the line with the selected history item */
1993                         /* change command */
1994                         command_len = load_string(state->history[state->cur_history] ? : "", maxsize);
1995                         /* redraw and go to eol (bol, in vi) */
1996                         redraw(cmdedit_y, (state->flags & VI_MODE) ? 9999 : 0);
1997                         break;
1998 #endif
1999                 case KEYCODE_RIGHT:
2000                         input_forward();
2001                         break;
2002                 case KEYCODE_LEFT:
2003                         input_backward(1);
2004                         break;
2005                 case KEYCODE_DELETE:
2006                         input_delete(0);
2007                         break;
2008                 case KEYCODE_HOME:
2009                         input_backward(cursor);
2010                         break;
2011                 case KEYCODE_END:
2012                         input_end();
2013                         break;
2014
2015                 default:
2016 //                      /* Control-V -- force insert of next char */
2017 //                      if (c == CTRL('V')) {
2018 //                              if (safe_read(STDIN_FILENO, &c, 1) < 1)
2019 //                                      goto prepare_to_die;
2020 //                              if (c == 0) {
2021 //                                      beep();
2022 //                                      break;
2023 //                              }
2024 //                      }
2025                         if (ic < ' '
2026                          || (!ENABLE_FEATURE_ASSUME_UNICODE && ic >= 256)
2027                          || (ENABLE_FEATURE_ASSUME_UNICODE && ic >= VI_CMDMODE_BIT)
2028                         ) {
2029                                 /* If VI_CMDMODE_BIT is set, ic is >= 256
2030                                  * and command mode ignores unexpected chars.
2031                                  * Otherwise, we are here if ic is a
2032                                  * control char or an unhandled ESC sequence,
2033                                  * which is also ignored.
2034                                  */
2035                                 break;
2036                         }
2037                         if ((int)command_len >= (maxsize - 2)) {
2038                                 /* Not enough space for the char and EOL */
2039                                 break;
2040                         }
2041
2042                         command_len++;
2043                         if (cursor == (command_len - 1)) {
2044                                 /* We are at the end, append */
2045                                 command_ps[cursor] = ic;
2046                                 command_ps[cursor + 1] = BB_NUL;
2047                                 cmdedit_set_out_char(' ');
2048                         } else {
2049                                 /* In the middle, insert */
2050                                 int sc = cursor;
2051
2052                                 memmove(command_ps + sc + 1, command_ps + sc,
2053                                         (command_len - sc) * sizeof(command_ps[0]));
2054                                 command_ps[sc] = ic;
2055                                 sc++;
2056                                 /* rewrite from cursor */
2057                                 input_end();
2058                                 /* to prev x pos + 1 */
2059                                 input_backward(cursor - sc);
2060                         }
2061                         break;
2062                 } /* switch (input_key) */
2063
2064                 if (break_out)
2065                         break;
2066
2067 #if ENABLE_FEATURE_TAB_COMPLETION
2068                 ic &= ~VI_CMDMODE_BIT;
2069                 if (ic != '\t')
2070                         lastWasTab = FALSE;
2071 #endif
2072         } /* while (1) */
2073
2074 /* Stop bug catching using "command_must_not_be_used" trick */
2075 #undef command
2076
2077 #if ENABLE_FEATURE_ASSUME_UNICODE
2078         command_len = save_string(command, maxsize - 1);
2079         free(command_ps);
2080 #endif
2081
2082         if (command_len > 0)
2083                 remember_in_history(command);
2084
2085         if (break_out > 0) {
2086                 command[command_len++] = '\n';
2087                 command[command_len] = '\0';
2088         }
2089
2090 #if ENABLE_FEATURE_TAB_COMPLETION
2091         free_tab_completion_data();
2092 #endif
2093
2094         /* restore initial_settings */
2095         tcsetattr_stdin_TCSANOW(&initial_settings);
2096         /* restore SIGWINCH handler */
2097         signal(SIGWINCH, previous_SIGWINCH_handler);
2098         fflush(stdout);
2099
2100         len = command_len;
2101         DEINIT_S();
2102
2103         return len; /* can't return command_len, DEINIT_S() destroys it */
2104 }
2105
2106 #else
2107
2108 #undef read_line_input
2109 int FAST_FUNC read_line_input(const char* prompt, char* command, int maxsize)
2110 {
2111         fputs(prompt, stdout);
2112         fflush(stdout);
2113         fgets(command, maxsize, stdin);
2114         return strlen(command);
2115 }
2116
2117 #endif  /* FEATURE_EDITING */
2118
2119
2120 /*
2121  * Testing
2122  */
2123
2124 #ifdef TEST
2125
2126 #include <locale.h>
2127
2128 const char *applet_name = "debug stuff usage";
2129
2130 int main(int argc, char **argv)
2131 {
2132         char buff[MAX_LINELEN];
2133         char *prompt =
2134 #if ENABLE_FEATURE_EDITING_FANCY_PROMPT
2135                 "\\[\\033[32;1m\\]\\u@\\[\\x1b[33;1m\\]\\h:"
2136                 "\\[\\033[34;1m\\]\\w\\[\\033[35;1m\\] "
2137                 "\\!\\[\\e[36;1m\\]\\$ \\[\\E[0m\\]";
2138 #else
2139                 "% ";
2140 #endif
2141
2142 #if ENABLE_FEATURE_NONPRINTABLE_INVERSE_PUT
2143         setlocale(LC_ALL, "");
2144 #endif
2145         while (1) {
2146                 int l;
2147                 l = read_line_input(prompt, buff);
2148                 if (l <= 0 || buff[l-1] != '\n')
2149                         break;
2150                 buff[l-1] = 0;
2151                 printf("*** read_line_input() returned line =%s=\n", buff);
2152         }
2153         printf("*** read_line_input() detect ^D\n");
2154         return 0;
2155 }
2156
2157 #endif  /* TEST */