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