libbb: filename completion should match dangling symlinks too
[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    Small bugs (simple effect):
26    - not true viewing if terminal size (x*y symbols) less
27      size (prompt + editor's line + 2 symbols)
28    - not true viewing if length prompt less terminal width
29  */
30
31 #include "libbb.h"
32
33
34 /* FIXME: obsolete CONFIG item? */
35 #define ENABLE_FEATURE_NONPRINTABLE_INVERSE_PUT 0
36
37
38 #ifdef TEST
39
40 #define ENABLE_FEATURE_EDITING 0
41 #define ENABLE_FEATURE_TAB_COMPLETION 0
42 #define ENABLE_FEATURE_USERNAME_COMPLETION 0
43 #define ENABLE_FEATURE_NONPRINTABLE_INVERSE_PUT 0
44
45 #endif  /* TEST */
46
47
48 /* Entire file (except TESTing part) sits inside this #if */
49 #if ENABLE_FEATURE_EDITING
50
51 #if ENABLE_LOCALE_SUPPORT
52 #define Isprint(c) isprint(c)
53 #else
54 #define Isprint(c) ((c) >= ' ' && (c) != ((unsigned char)'\233'))
55 #endif
56
57 #define ENABLE_FEATURE_GETUSERNAME_AND_HOMEDIR \
58         (ENABLE_FEATURE_USERNAME_COMPLETION || ENABLE_FEATURE_EDITING_FANCY_PROMPT)
59 #define USE_FEATURE_GETUSERNAME_AND_HOMEDIR(...)
60 #if ENABLE_FEATURE_GETUSERNAME_AND_HOMEDIR
61 #undef USE_FEATURE_GETUSERNAME_AND_HOMEDIR
62 #define USE_FEATURE_GETUSERNAME_AND_HOMEDIR(...) __VA_ARGS__
63 #endif
64
65 enum {
66         /* We use int16_t for positions, need to limit line len */
67         MAX_LINELEN = CONFIG_FEATURE_EDITING_MAX_LEN < 0x7ff0
68                       ? CONFIG_FEATURE_EDITING_MAX_LEN
69                       : 0x7ff0
70 };
71
72 #if ENABLE_FEATURE_GETUSERNAME_AND_HOMEDIR
73 static const char null_str[] ALIGN1 = "";
74 #endif
75
76 /* We try to minimize both static and stack usage. */
77 struct statics {
78         line_input_t *state;
79
80         volatile unsigned cmdedit_termw; /* = 80; */ /* actual terminal width */
81         sighandler_t previous_SIGWINCH_handler;
82
83
84         int cmdedit_x;           /* real x terminal position */
85         int cmdedit_y;           /* pseudoreal y terminal position */
86         int cmdedit_prmt_len;    /* length of prompt (without colors etc) */
87
88         unsigned cursor;
89         unsigned command_len;
90         char *command_ps;
91
92         const char *cmdedit_prompt;
93 #if ENABLE_FEATURE_EDITING_FANCY_PROMPT
94         int num_ok_lines; /* = 1; */
95 #endif
96
97 #if ENABLE_FEATURE_GETUSERNAME_AND_HOMEDIR
98         char *user_buf;
99         char *home_pwd_buf; /* = (char*)null_str; */
100 #endif
101
102 #if ENABLE_FEATURE_TAB_COMPLETION
103         char **matches;
104         unsigned num_matches;
105 #endif
106
107 #if ENABLE_FEATURE_EDITING_VI
108 #define DELBUFSIZ 128
109         char *delptr;
110         smallint newdelflag;     /* whether delbuf should be reused yet */
111         char delbuf[DELBUFSIZ];  /* a place to store deleted characters */
112 #endif
113
114         /* Formerly these were big buffers on stack: */
115 #if ENABLE_FEATURE_TAB_COMPLETION
116         char exe_n_cwd_tab_completion__dirbuf[MAX_LINELEN];
117         char input_tab__matchBuf[MAX_LINELEN];
118         int16_t find_match__int_buf[MAX_LINELEN + 1]; /* need to have 9 bits at least */
119         int16_t find_match__pos_buf[MAX_LINELEN + 1];
120 #endif
121 };
122
123 /* Make it reside in writable memory, yet make compiler understand
124  * that it is not going to change. */
125 static struct statics *const ptr_to_statics __attribute__ ((section (".data")));
126
127 #define S (*ptr_to_statics)
128 #define state            (S.state           )
129 #define cmdedit_termw    (S.cmdedit_termw   )
130 #define previous_SIGWINCH_handler (S.previous_SIGWINCH_handler)
131 #define cmdedit_x        (S.cmdedit_x       )
132 #define cmdedit_y        (S.cmdedit_y       )
133 #define cmdedit_prmt_len (S.cmdedit_prmt_len)
134 #define cursor           (S.cursor          )
135 #define command_len      (S.command_len     )
136 #define command_ps       (S.command_ps      )
137 #define cmdedit_prompt   (S.cmdedit_prompt  )
138 #define num_ok_lines     (S.num_ok_lines    )
139 #define user_buf         (S.user_buf        )
140 #define home_pwd_buf     (S.home_pwd_buf    )
141 #define matches          (S.matches         )
142 #define num_matches      (S.num_matches     )
143 #define delptr           (S.delptr          )
144 #define newdelflag       (S.newdelflag      )
145 #define delbuf           (S.delbuf          )
146
147 #define INIT_S() do { \
148         (*(struct statics**)&ptr_to_statics) = xzalloc(sizeof(S)); \
149         cmdedit_termw = 80; \
150         USE_FEATURE_EDITING_FANCY_PROMPT(num_ok_lines = 1;) \
151         USE_FEATURE_GETUSERNAME_AND_HOMEDIR(home_pwd_buf = (char*)null_str;) \
152 } while (0)
153 static void deinit_S(void)
154 {
155 #if ENABLE_FEATURE_EDITING_FANCY_PROMPT
156         /* This one is allocated only if FANCY_PROMPT is on
157          * (otherwise it points to verbatim prompt (NOT malloced) */
158         free((char*)cmdedit_prompt);
159 #endif
160 #if ENABLE_FEATURE_GETUSERNAME_AND_HOMEDIR
161         free(user_buf);
162         if (home_pwd_buf != null_str)
163                 free(home_pwd_buf);
164 #endif
165         free(ptr_to_statics);
166 }
167 #define DEINIT_S() deinit_S()
168
169 /* Put 'command_ps[cursor]', cursor++.
170  * Advance cursor on screen. If we reached right margin, scroll text up
171  * and remove terminal margin effect by printing 'next_char' */
172 static void cmdedit_set_out_char(int next_char)
173 {
174         int c = (unsigned char)command_ps[cursor];
175
176         if (c == '\0') {
177                 /* erase character after end of input string */
178                 c = ' ';
179         }
180 #if ENABLE_FEATURE_NONPRINTABLE_INVERSE_PUT
181         /* Display non-printable characters in reverse */
182         if (!Isprint(c)) {
183                 if (c >= 128)
184                         c -= 128;
185                 if (c < ' ')
186                         c += '@';
187                 if (c == 127)
188                         c = '?';
189                 printf("\033[7m%c\033[0m", c);
190         } else
191 #endif
192         {
193                 bb_putchar(c);
194         }
195         if (++cmdedit_x >= cmdedit_termw) {
196                 /* terminal is scrolled down */
197                 cmdedit_y++;
198                 cmdedit_x = 0;
199                 /* destroy "(auto)margin" */
200                 bb_putchar(next_char);
201                 bb_putchar('\b');
202         }
203 // Huh? What if command_ps[cursor] == '\0' (we are at the end already?)
204         cursor++;
205 }
206
207 /* Move to end of line (by printing all chars till the end) */
208 static void input_end(void)
209 {
210         while (cursor < command_len)
211                 cmdedit_set_out_char(' ');
212 }
213
214 /* Go to the next line */
215 static void goto_new_line(void)
216 {
217         input_end();
218         if (cmdedit_x)
219                 bb_putchar('\n');
220 }
221
222
223 static void out1str(const char *s)
224 {
225         if (s)
226                 fputs(s, stdout);
227 }
228
229 static void beep(void)
230 {
231         bb_putchar('\007');
232 }
233
234 /* Move back one character */
235 /* (optimized for slow terminals) */
236 static void input_backward(unsigned num)
237 {
238         int count_y;
239
240         if (num > cursor)
241                 num = cursor;
242         if (!num)
243                 return;
244         cursor -= num;
245
246         if (cmdedit_x >= num) {
247                 cmdedit_x -= num;
248                 if (num <= 4) {
249                         printf("\b\b\b\b" + (4-num));
250                         return;
251                 }
252                 printf("\033[%uD", num);
253                 return;
254         }
255
256         /* Need to go one or more lines up */
257         num -= cmdedit_x;
258         count_y = 1 + (num / cmdedit_termw);
259         cmdedit_y -= count_y;
260         cmdedit_x = cmdedit_termw * count_y - num;
261         /* go to 1st column; go up; go to correct column */
262         printf("\r" "\033[%dA" "\033[%dC", count_y, cmdedit_x);
263 }
264
265 static void put_prompt(void)
266 {
267         out1str(cmdedit_prompt);
268         cmdedit_x = cmdedit_prmt_len;
269         cursor = 0;
270 // Huh? what if cmdedit_prmt_len >= width?
271         cmdedit_y = 0;                  /* new quasireal y */
272 }
273
274 /* draw prompt, editor line, and clear tail */
275 static void redraw(int y, int back_cursor)
276 {
277         if (y > 0)                              /* up to start y */
278                 printf("\033[%dA", y);
279         bb_putchar('\r');
280         put_prompt();
281         input_end();                            /* rewrite */
282         printf("\033[J");                       /* erase after cursor */
283         input_backward(back_cursor);
284 }
285
286 /* Delete the char in front of the cursor, optionally saving it
287  * for later putback */
288 static void input_delete(int save)
289 {
290         int j = cursor;
291
292         if (j == command_len)
293                 return;
294
295 #if ENABLE_FEATURE_EDITING_VI
296         if (save) {
297                 if (newdelflag) {
298                         delptr = delbuf;
299                         newdelflag = 0;
300                 }
301                 if ((delptr - delbuf) < DELBUFSIZ)
302                         *delptr++ = command_ps[j];
303         }
304 #endif
305
306         strcpy(command_ps + j, command_ps + j + 1);
307         command_len--;
308         input_end();                    /* rewrite new line */
309         cmdedit_set_out_char(' ');      /* erase char */
310         input_backward(cursor - j);     /* back to old pos cursor */
311 }
312
313 #if ENABLE_FEATURE_EDITING_VI
314 static void put(void)
315 {
316         int ocursor;
317         int j = delptr - delbuf;
318
319         if (j == 0)
320                 return;
321         ocursor = cursor;
322         /* open hole and then fill it */
323         memmove(command_ps + cursor + j, command_ps + cursor, command_len - cursor + 1);
324         strncpy(command_ps + cursor, delbuf, j);
325         command_len += j;
326         input_end();                    /* rewrite new line */
327         input_backward(cursor - ocursor - j + 1); /* at end of new text */
328 }
329 #endif
330
331 /* Delete the char in back of the cursor */
332 static void input_backspace(void)
333 {
334         if (cursor > 0) {
335                 input_backward(1);
336                 input_delete(0);
337         }
338 }
339
340 /* Move forward one character */
341 static void input_forward(void)
342 {
343         if (cursor < command_len)
344                 cmdedit_set_out_char(command_ps[cursor + 1]);
345 }
346
347 #if ENABLE_FEATURE_TAB_COMPLETION
348
349 static void free_tab_completion_data(void)
350 {
351         if (matches) {
352                 while (num_matches)
353                         free(matches[--num_matches]);
354                 free(matches);
355                 matches = NULL;
356         }
357 }
358
359 static void add_match(char *matched)
360 {
361         int nm = num_matches;
362         int nm1 = nm + 1;
363
364         matches = xrealloc(matches, nm1 * sizeof(char *));
365         matches[nm] = matched;
366         num_matches++;
367 }
368
369 #if ENABLE_FEATURE_USERNAME_COMPLETION
370 static void username_tab_completion(char *ud, char *with_shash_flg)
371 {
372         struct passwd *entry;
373         int userlen;
374
375         ud++;                           /* ~user/... to user/... */
376         userlen = strlen(ud);
377
378         if (with_shash_flg) {           /* "~/..." or "~user/..." */
379                 char *sav_ud = ud - 1;
380                 char *home = NULL;
381
382                 if (*ud == '/') {       /* "~/..."     */
383                         home = home_pwd_buf;
384                 } else {
385                         /* "~user/..." */
386                         char *temp;
387                         temp = strchr(ud, '/');
388                         *temp = '\0';           /* ~user\0 */
389                         entry = getpwnam(ud);
390                         *temp = '/';            /* restore ~user/... */
391                         ud = temp;
392                         if (entry)
393                                 home = entry->pw_dir;
394                 }
395                 if (home) {
396                         if ((userlen + strlen(home) + 1) < MAX_LINELEN) {
397                                 /* /home/user/... */
398                                 sprintf(sav_ud, "%s%s", home, ud);
399                         }
400                 }
401         } else {
402                 /* "~[^/]*" */
403                 /* Using _r function to avoid pulling in static buffers */
404                 char line_buff[256];
405                 struct passwd pwd;
406                 struct passwd *result;
407
408                 setpwent();
409                 while (!getpwent_r(&pwd, line_buff, sizeof(line_buff), &result)) {
410                         /* Null usernames should result in all users as possible completions. */
411                         if (/*!userlen || */ strncmp(ud, pwd.pw_name, userlen) == 0) {
412                                 add_match(xasprintf("~%s/", pwd.pw_name));
413                         }
414                 }
415                 endpwent();
416         }
417 }
418 #endif  /* FEATURE_COMMAND_USERNAME_COMPLETION */
419
420 enum {
421         FIND_EXE_ONLY = 0,
422         FIND_DIR_ONLY = 1,
423         FIND_FILE_ONLY = 2,
424 };
425
426 static int path_parse(char ***p, int flags)
427 {
428         int npth;
429         const char *pth;
430         char *tmp;
431         char **res;
432
433         /* if not setenv PATH variable, to search cur dir "." */
434         if (flags != FIND_EXE_ONLY)
435                 return 1;
436
437         if (state->flags & WITH_PATH_LOOKUP)
438                 pth = state->path_lookup;
439         else
440                 pth = getenv("PATH");
441         /* PATH=<empty> or PATH=:<empty> */
442         if (!pth || !pth[0] || LONE_CHAR(pth, ':'))
443                 return 1;
444
445         tmp = (char*)pth;
446         npth = 1; /* path component count */
447         while (1) {
448                 tmp = strchr(tmp, ':');
449                 if (!tmp)
450                         break;
451                 if (*++tmp == '\0')
452                         break;  /* :<empty> */
453                 npth++;
454         }
455
456         res = xmalloc(npth * sizeof(char*));
457         res[0] = tmp = xstrdup(pth);
458         npth = 1;
459         while (1) {
460                 tmp = strchr(tmp, ':');
461                 if (!tmp)
462                         break;
463                 *tmp++ = '\0'; /* ':' -> '\0' */
464                 if (*tmp == '\0')
465                         break; /* :<empty> */
466                 res[npth++] = tmp;
467         }
468         *p = res;
469         return npth;
470 }
471
472 static void exe_n_cwd_tab_completion(char *command, int type)
473 {
474         DIR *dir;
475         struct dirent *next;
476         struct stat st;
477         char *path1[1];
478         char **paths = path1;
479         int npaths;
480         int i;
481         char *found;
482         char *pfind = strrchr(command, '/');
483 /*      char dirbuf[MAX_LINELEN]; */
484 #define dirbuf (S.exe_n_cwd_tab_completion__dirbuf)
485
486         npaths = 1;
487         path1[0] = (char*)".";
488
489         if (pfind == NULL) {
490                 /* no dir, if flags==EXE_ONLY - get paths, else "." */
491                 npaths = path_parse(&paths, type);
492                 pfind = command;
493         } else {
494                 /* dirbuf = ".../.../.../" */
495                 safe_strncpy(dirbuf, command, (pfind - command) + 2);
496 #if ENABLE_FEATURE_USERNAME_COMPLETION
497                 if (dirbuf[0] == '~')   /* ~/... or ~user/... */
498                         username_tab_completion(dirbuf, dirbuf);
499 #endif
500                 paths[0] = dirbuf;
501                 /* point to 'l' in "..../last_component" */
502                 pfind++;
503         }
504
505         for (i = 0; i < npaths; i++) {
506                 dir = opendir(paths[i]);
507                 if (!dir)                       /* Don't print an error */
508                         continue;
509
510                 while ((next = readdir(dir)) != NULL) {
511                         int len1;
512                         const char *str_found = next->d_name;
513
514                         /* matched? */
515                         if (strncmp(str_found, pfind, strlen(pfind)))
516                                 continue;
517                         /* not see .name without .match */
518                         if (*str_found == '.' && *pfind == 0) {
519                                 if (NOT_LONE_CHAR(paths[i], '/') || str_found[1])
520                                         continue;
521                                 str_found = ""; /* only "/" */
522                         }
523                         found = concat_path_file(paths[i], str_found);
524                         /* hmm, remover in progress? */
525                         if (lstat(found, &st) < 0)
526                                 goto cont;
527                         /* find with dirs? */
528                         if (paths[i] != dirbuf)
529                                 strcpy(found, next->d_name);    /* only name */
530
531                         len1 = strlen(found);
532                         found = xrealloc(found, len1 + 2);
533                         found[len1] = '\0';
534                         found[len1+1] = '\0';
535
536                         if (S_ISDIR(st.st_mode)) {
537                                 /* name is directory      */
538                                 if (found[len1-1] != '/') {
539                                         found[len1] = '/';
540                                 }
541                         } else {
542                                 /* not put found file if search only dirs for cd */
543                                 if (type == FIND_DIR_ONLY)
544                                         goto cont;
545                         }
546                         /* Add it to the list */
547                         add_match(found);
548                         continue;
549  cont:
550                         free(found);
551                 }
552                 closedir(dir);
553         }
554         if (paths != path1) {
555                 free(paths[0]);                 /* allocated memory only in first member */
556                 free(paths);
557         }
558 #undef dirbuf
559 }
560
561 #define QUOT (UCHAR_MAX+1)
562
563 #define collapse_pos(is, in) do { \
564         memmove(int_buf+(is), int_buf+(in), (MAX_LINELEN+1-(is)-(in)) * sizeof(pos_buf[0])); \
565         memmove(pos_buf+(is), pos_buf+(in), (MAX_LINELEN+1-(is)-(in)) * sizeof(pos_buf[0])); \
566 } while (0)
567
568 static int find_match(char *matchBuf, int *len_with_quotes)
569 {
570         int i, j;
571         int command_mode;
572         int c, c2;
573 /*      int16_t int_buf[MAX_LINELEN + 1]; */
574 /*      int16_t pos_buf[MAX_LINELEN + 1]; */
575 #define int_buf (S.find_match__int_buf)
576 #define pos_buf (S.find_match__pos_buf)
577
578         /* set to integer dimension characters and own positions */
579         for (i = 0;; i++) {
580                 int_buf[i] = (unsigned char)matchBuf[i];
581                 if (int_buf[i] == 0) {
582                         pos_buf[i] = -1;        /* indicator end line */
583                         break;
584                 }
585                 pos_buf[i] = i;
586         }
587
588         /* mask \+symbol and convert '\t' to ' ' */
589         for (i = j = 0; matchBuf[i]; i++, j++)
590                 if (matchBuf[i] == '\\') {
591                         collapse_pos(j, j + 1);
592                         int_buf[j] |= QUOT;
593                         i++;
594 #if ENABLE_FEATURE_NONPRINTABLE_INVERSE_PUT
595                         if (matchBuf[i] == '\t')        /* algorithm equivalent */
596                                 int_buf[j] = ' ' | QUOT;
597 #endif
598                 }
599 #if ENABLE_FEATURE_NONPRINTABLE_INVERSE_PUT
600                 else if (matchBuf[i] == '\t')
601                         int_buf[j] = ' ';
602 #endif
603
604         /* mask "symbols" or 'symbols' */
605         c2 = 0;
606         for (i = 0; int_buf[i]; i++) {
607                 c = int_buf[i];
608                 if (c == '\'' || c == '"') {
609                         if (c2 == 0)
610                                 c2 = c;
611                         else {
612                                 if (c == c2)
613                                         c2 = 0;
614                                 else
615                                         int_buf[i] |= QUOT;
616                         }
617                 } else if (c2 != 0 && c != '$')
618                         int_buf[i] |= QUOT;
619         }
620
621         /* skip commands with arguments if line has commands delimiters */
622         /* ';' ';;' '&' '|' '&&' '||' but `>&' `<&' `>|' */
623         for (i = 0; int_buf[i]; i++) {
624                 c = int_buf[i];
625                 c2 = int_buf[i + 1];
626                 j = i ? int_buf[i - 1] : -1;
627                 command_mode = 0;
628                 if (c == ';' || c == '&' || c == '|') {
629                         command_mode = 1 + (c == c2);
630                         if (c == '&') {
631                                 if (j == '>' || j == '<')
632                                         command_mode = 0;
633                         } else if (c == '|' && j == '>')
634                                 command_mode = 0;
635                 }
636                 if (command_mode) {
637                         collapse_pos(0, i + command_mode);
638                         i = -1;                         /* hack incremet */
639                 }
640         }
641         /* collapse `command...` */
642         for (i = 0; int_buf[i]; i++)
643                 if (int_buf[i] == '`') {
644                         for (j = i + 1; int_buf[j]; j++)
645                                 if (int_buf[j] == '`') {
646                                         collapse_pos(i, j + 1);
647                                         j = 0;
648                                         break;
649                                 }
650                         if (j) {
651                                 /* not found close ` - command mode, collapse all previous */
652                                 collapse_pos(0, i + 1);
653                                 break;
654                         } else
655                                 i--;                    /* hack incremet */
656                 }
657
658         /* collapse (command...(command...)...) or {command...{command...}...} */
659         c = 0;                                          /* "recursive" level */
660         c2 = 0;
661         for (i = 0; int_buf[i]; i++)
662                 if (int_buf[i] == '(' || int_buf[i] == '{') {
663                         if (int_buf[i] == '(')
664                                 c++;
665                         else
666                                 c2++;
667                         collapse_pos(0, i + 1);
668                         i = -1;                         /* hack incremet */
669                 }
670         for (i = 0; pos_buf[i] >= 0 && (c > 0 || c2 > 0); i++)
671                 if ((int_buf[i] == ')' && c > 0) || (int_buf[i] == '}' && c2 > 0)) {
672                         if (int_buf[i] == ')')
673                                 c--;
674                         else
675                                 c2--;
676                         collapse_pos(0, i + 1);
677                         i = -1;                         /* hack incremet */
678                 }
679
680         /* skip first not quote space */
681         for (i = 0; int_buf[i]; i++)
682                 if (int_buf[i] != ' ')
683                         break;
684         if (i)
685                 collapse_pos(0, i);
686
687         /* set find mode for completion */
688         command_mode = FIND_EXE_ONLY;
689         for (i = 0; int_buf[i]; i++)
690                 if (int_buf[i] == ' ' || int_buf[i] == '<' || int_buf[i] == '>') {
691                         if (int_buf[i] == ' ' && command_mode == FIND_EXE_ONLY
692                          && matchBuf[pos_buf[0]] == 'c'
693                          && matchBuf[pos_buf[1]] == 'd'
694                         ) {
695                                 command_mode = FIND_DIR_ONLY;
696                         } else {
697                                 command_mode = FIND_FILE_ONLY;
698                                 break;
699                         }
700                 }
701         for (i = 0; int_buf[i]; i++)
702                 /* "strlen" */;
703         /* find last word */
704         for (--i; i >= 0; i--) {
705                 c = int_buf[i];
706                 if (c == ' ' || c == '<' || c == '>' || c == '|' || c == '&') {
707                         collapse_pos(0, i + 1);
708                         break;
709                 }
710         }
711         /* skip first not quoted '\'' or '"' */
712         for (i = 0; int_buf[i] == '\'' || int_buf[i] == '"'; i++)
713                 /*skip*/;
714         /* collapse quote or unquote // or /~ */
715         while ((int_buf[i] & ~QUOT) == '/'
716          && ((int_buf[i+1] & ~QUOT) == '/' || (int_buf[i+1] & ~QUOT) == '~')
717         ) {
718                 i++;
719         }
720
721         /* set only match and destroy quotes */
722         j = 0;
723         for (c = 0; pos_buf[i] >= 0; i++) {
724                 matchBuf[c++] = matchBuf[pos_buf[i]];
725                 j = pos_buf[i] + 1;
726         }
727         matchBuf[c] = '\0';
728         /* old length matchBuf with quotes symbols */
729         *len_with_quotes = j ? j - pos_buf[0] : 0;
730
731         return command_mode;
732 #undef int_buf
733 #undef pos_buf
734 }
735
736 /*
737  * display by column (original idea from ls applet,
738  * very optimized by me :)
739  */
740 static void showfiles(void)
741 {
742         int ncols, row;
743         int column_width = 0;
744         int nfiles = num_matches;
745         int nrows = nfiles;
746         int l;
747
748         /* find the longest file name-  use that as the column width */
749         for (row = 0; row < nrows; row++) {
750                 l = strlen(matches[row]);
751                 if (column_width < l)
752                         column_width = l;
753         }
754         column_width += 2;              /* min space for columns */
755         ncols = cmdedit_termw / column_width;
756
757         if (ncols > 1) {
758                 nrows /= ncols;
759                 if (nfiles % ncols)
760                         nrows++;        /* round up fractionals */
761         } else {
762                 ncols = 1;
763         }
764         for (row = 0; row < nrows; row++) {
765                 int n = row;
766                 int nc;
767
768                 for (nc = 1; nc < ncols && n+nrows < nfiles; n += nrows, nc++) {
769                         printf("%s%-*s", matches[n],
770                                 (int)(column_width - strlen(matches[n])), "");
771                 }
772                 puts(matches[n]);
773         }
774 }
775
776 static char *add_quote_for_spec_chars(char *found)
777 {
778         int l = 0;
779         char *s = xmalloc((strlen(found) + 1) * 2);
780
781         while (*found) {
782                 if (strchr(" `\"#$%^&*()=+{}[]:;\'|\\<>", *found))
783                         s[l++] = '\\';
784                 s[l++] = *found++;
785         }
786         s[l] = 0;
787         return s;
788 }
789
790 static int match_compare(const void *a, const void *b)
791 {
792         return strcmp(*(char**)a, *(char**)b);
793 }
794
795 /* Do TAB completion */
796 static void input_tab(smallint *lastWasTab)
797 {
798         if (!(state->flags & TAB_COMPLETION))
799                 return;
800
801         if (!*lastWasTab) {
802                 char *tmp, *tmp1;
803                 int len_found;
804 /*              char matchBuf[MAX_LINELEN]; */
805 #define matchBuf (S.input_tab__matchBuf)
806                 int find_type;
807                 int recalc_pos;
808
809                 *lastWasTab = TRUE;             /* flop trigger */
810
811                 /* Make a local copy of the string -- up
812                  * to the position of the cursor */
813                 tmp = strncpy(matchBuf, command_ps, cursor);
814                 tmp[cursor] = '\0';
815
816                 find_type = find_match(matchBuf, &recalc_pos);
817
818                 /* Free up any memory already allocated */
819                 free_tab_completion_data();
820
821 #if ENABLE_FEATURE_USERNAME_COMPLETION
822                 /* If the word starts with `~' and there is no slash in the word,
823                  * then try completing this word as a username. */
824                 if (state->flags & USERNAME_COMPLETION)
825                         if (matchBuf[0] == '~' && strchr(matchBuf, '/') == 0)
826                                 username_tab_completion(matchBuf, NULL);
827 #endif
828                 /* Try to match any executable in our path and everything
829                  * in the current working directory */
830                 if (!matches)
831                         exe_n_cwd_tab_completion(matchBuf, find_type);
832                 /* Sort, then remove any duplicates found */
833                 if (matches) {
834                         int i, n = 0;
835                         qsort(matches, num_matches, sizeof(char*), match_compare);
836                         for (i = 0; i < num_matches - 1; ++i) {
837                                 if (matches[i] && matches[i+1]) { /* paranoia */
838                                         if (strcmp(matches[i], matches[i+1]) == 0) {
839                                                 free(matches[i]);
840                                                 matches[i] = NULL; /* paranoia */
841                                         } else {
842                                                 matches[n++] = matches[i];
843                                         }
844                                 }
845                         }
846                         matches[n] = matches[i];
847                         num_matches = n + 1;
848                 }
849                 /* Did we find exactly one match? */
850                 if (!matches || num_matches > 1) {
851                         beep();
852                         if (!matches)
853                                 return;         /* not found */
854                         /* find minimal match */
855                         tmp1 = xstrdup(matches[0]);
856                         for (tmp = tmp1; *tmp; tmp++)
857                                 for (len_found = 1; len_found < num_matches; len_found++)
858                                         if (matches[len_found][(tmp - tmp1)] != *tmp) {
859                                                 *tmp = '\0';
860                                                 break;
861                                         }
862                         if (*tmp1 == '\0') {        /* have unique */
863                                 free(tmp1);
864                                 return;
865                         }
866                         tmp = add_quote_for_spec_chars(tmp1);
867                         free(tmp1);
868                 } else {                        /* one match */
869                         tmp = add_quote_for_spec_chars(matches[0]);
870                         /* for next completion current found */
871                         *lastWasTab = FALSE;
872
873                         len_found = strlen(tmp);
874                         if (tmp[len_found-1] != '/') {
875                                 tmp[len_found] = ' ';
876                                 tmp[len_found+1] = '\0';
877                         }
878                 }
879                 len_found = strlen(tmp);
880                 /* have space to placed match? */
881                 if ((len_found - strlen(matchBuf) + command_len) < MAX_LINELEN) {
882                         /* before word for match   */
883                         command_ps[cursor - recalc_pos] = '\0';
884                         /* save   tail line        */
885                         strcpy(matchBuf, command_ps + cursor);
886                         /* add    match            */
887                         strcat(command_ps, tmp);
888                         /* add    tail             */
889                         strcat(command_ps, matchBuf);
890                         /* back to begin word for match    */
891                         input_backward(recalc_pos);
892                         /* new pos                         */
893                         recalc_pos = cursor + len_found;
894                         /* new len                         */
895                         command_len = strlen(command_ps);
896                         /* write out the matched command   */
897                         redraw(cmdedit_y, command_len - recalc_pos);
898                 }
899                 free(tmp);
900 #undef matchBuf
901         } else {
902                 /* Ok -- the last char was a TAB.  Since they
903                  * just hit TAB again, print a list of all the
904                  * available choices... */
905                 if (matches && num_matches > 0) {
906                         int sav_cursor = cursor;        /* change goto_new_line() */
907
908                         /* Go to the next line */
909                         goto_new_line();
910                         showfiles();
911                         redraw(0, command_len - sav_cursor);
912                 }
913         }
914 }
915
916 #endif  /* FEATURE_COMMAND_TAB_COMPLETION */
917
918
919 #if MAX_HISTORY > 0
920
921 /* state->flags is already checked to be nonzero */
922 static void get_previous_history(void)
923 {
924         if (command_ps[0] != '\0' || state->history[state->cur_history] == NULL) {
925                 free(state->history[state->cur_history]);
926                 state->history[state->cur_history] = xstrdup(command_ps);
927         }
928         state->cur_history--;
929 }
930
931 static int get_next_history(void)
932 {
933         if (state->flags & DO_HISTORY) {
934                 int ch = state->cur_history;
935                 if (ch < state->cnt_history) {
936                         get_previous_history(); /* save the current history line */
937                         state->cur_history = ch + 1;
938                         return state->cur_history;
939                 }
940         }
941         beep();
942         return 0;
943 }
944
945 #if ENABLE_FEATURE_EDITING_SAVEHISTORY
946 /* state->flags is already checked to be nonzero */
947 static void load_history(const char *fromfile)
948 {
949         FILE *fp;
950         int hi;
951
952         /* cleanup old */
953         for (hi = state->cnt_history; hi > 0;) {
954                 hi--;
955                 free(state->history[hi]);
956         }
957
958         fp = fopen(fromfile, "r");
959         if (fp) {
960                 for (hi = 0; hi < MAX_HISTORY;) {
961                         char *hl = xmalloc_getline(fp);
962                         int l;
963
964                         if (!hl)
965                                 break;
966                         l = strlen(hl);
967                         if (l >= MAX_LINELEN)
968                                 hl[MAX_LINELEN-1] = '\0';
969                         if (l == 0 || hl[0] == ' ') {
970                                 free(hl);
971                                 continue;
972                         }
973                         state->history[hi++] = hl;
974                 }
975                 fclose(fp);
976         }
977         state->cur_history = state->cnt_history = hi;
978 }
979
980 /* state->flags is already checked to be nonzero */
981 static void save_history(const char *tofile)
982 {
983         FILE *fp;
984
985         fp = fopen(tofile, "w");
986         if (fp) {
987                 int i;
988
989                 for (i = 0; i < state->cnt_history; i++) {
990                         fprintf(fp, "%s\n", state->history[i]);
991                 }
992                 fclose(fp);
993         }
994 }
995 #else
996 #define load_history(a) ((void)0)
997 #define save_history(a) ((void)0)
998 #endif /* FEATURE_COMMAND_SAVEHISTORY */
999
1000 static void remember_in_history(const char *str)
1001 {
1002         int i;
1003
1004         if (!(state->flags & DO_HISTORY))
1005                 return;
1006
1007         i = state->cnt_history;
1008         free(state->history[MAX_HISTORY]);
1009         state->history[MAX_HISTORY] = NULL;
1010         /* After max history, remove the oldest command */
1011         if (i >= MAX_HISTORY) {
1012                 free(state->history[0]);
1013                 for (i = 0; i < MAX_HISTORY-1; i++)
1014                         state->history[i] = state->history[i+1];
1015         }
1016 // Maybe "if (!i || strcmp(history[i-1], command) != 0) ..."
1017 // (i.e. do not save dups?)
1018         state->history[i++] = xstrdup(str);
1019         state->cur_history = i;
1020         state->cnt_history = i;
1021 #if ENABLE_FEATURE_EDITING_SAVEHISTORY
1022         if ((state->flags & SAVE_HISTORY) && state->hist_file)
1023                 save_history(state->hist_file);
1024 #endif
1025         USE_FEATURE_EDITING_FANCY_PROMPT(num_ok_lines++;)
1026 }
1027
1028 #else /* MAX_HISTORY == 0 */
1029 #define remember_in_history(a) ((void)0)
1030 #endif /* MAX_HISTORY */
1031
1032
1033 /*
1034  * This function is used to grab a character buffer
1035  * from the input file descriptor and allows you to
1036  * a string with full command editing (sort of like
1037  * a mini readline).
1038  *
1039  * The following standard commands are not implemented:
1040  * ESC-b -- Move back one word
1041  * ESC-f -- Move forward one word
1042  * ESC-d -- Delete back one word
1043  * ESC-h -- Delete forward one word
1044  * CTL-t -- Transpose two characters
1045  *
1046  * Minimalist vi-style command line editing available if configured.
1047  * vi mode implemented 2005 by Paul Fox <pgf@foxharp.boston.ma.us>
1048  */
1049
1050 #if ENABLE_FEATURE_EDITING_VI
1051 static void
1052 vi_Word_motion(char *command, int eat)
1053 {
1054         while (cursor < command_len && !isspace(command[cursor]))
1055                 input_forward();
1056         if (eat) while (cursor < command_len && isspace(command[cursor]))
1057                 input_forward();
1058 }
1059
1060 static void
1061 vi_word_motion(char *command, int eat)
1062 {
1063         if (isalnum(command[cursor]) || command[cursor] == '_') {
1064                 while (cursor < command_len
1065                  && (isalnum(command[cursor+1]) || command[cursor+1] == '_'))
1066                         input_forward();
1067         } else if (ispunct(command[cursor])) {
1068                 while (cursor < command_len && ispunct(command[cursor+1]))
1069                         input_forward();
1070         }
1071
1072         if (cursor < command_len)
1073                 input_forward();
1074
1075         if (eat && cursor < command_len && isspace(command[cursor]))
1076                 while (cursor < command_len && isspace(command[cursor]))
1077                         input_forward();
1078 }
1079
1080 static void
1081 vi_End_motion(char *command)
1082 {
1083         input_forward();
1084         while (cursor < command_len && isspace(command[cursor]))
1085                 input_forward();
1086         while (cursor < command_len-1 && !isspace(command[cursor+1]))
1087                 input_forward();
1088 }
1089
1090 static void
1091 vi_end_motion(char *command)
1092 {
1093         if (cursor >= command_len-1)
1094                 return;
1095         input_forward();
1096         while (cursor < command_len-1 && isspace(command[cursor]))
1097                 input_forward();
1098         if (cursor >= command_len-1)
1099                 return;
1100         if (isalnum(command[cursor]) || command[cursor] == '_') {
1101                 while (cursor < command_len-1
1102                  && (isalnum(command[cursor+1]) || command[cursor+1] == '_')
1103                 ) {
1104                         input_forward();
1105                 }
1106         } else if (ispunct(command[cursor])) {
1107                 while (cursor < command_len-1 && ispunct(command[cursor+1]))
1108                         input_forward();
1109         }
1110 }
1111
1112 static void
1113 vi_Back_motion(char *command)
1114 {
1115         while (cursor > 0 && isspace(command[cursor-1]))
1116                 input_backward(1);
1117         while (cursor > 0 && !isspace(command[cursor-1]))
1118                 input_backward(1);
1119 }
1120
1121 static void
1122 vi_back_motion(char *command)
1123 {
1124         if (cursor <= 0)
1125                 return;
1126         input_backward(1);
1127         while (cursor > 0 && isspace(command[cursor]))
1128                 input_backward(1);
1129         if (cursor <= 0)
1130                 return;
1131         if (isalnum(command[cursor]) || command[cursor] == '_') {
1132                 while (cursor > 0
1133                  && (isalnum(command[cursor-1]) || command[cursor-1] == '_')
1134                 ) {
1135                         input_backward(1);
1136                 }
1137         } else if (ispunct(command[cursor])) {
1138                 while (cursor > 0 && ispunct(command[cursor-1]))
1139                         input_backward(1);
1140         }
1141 }
1142 #endif
1143
1144
1145 /*
1146  * read_line_input and its helpers
1147  */
1148
1149 #if !ENABLE_FEATURE_EDITING_FANCY_PROMPT
1150 static void parse_and_put_prompt(const char *prmt_ptr)
1151 {
1152         cmdedit_prompt = prmt_ptr;
1153         cmdedit_prmt_len = strlen(prmt_ptr);
1154         put_prompt();
1155 }
1156 #else
1157 static void parse_and_put_prompt(const char *prmt_ptr)
1158 {
1159         int prmt_len = 0;
1160         size_t cur_prmt_len = 0;
1161         char flg_not_length = '[';
1162         char *prmt_mem_ptr = xzalloc(1);
1163         char *cwd_buf = xrealloc_getcwd_or_warn(NULL);
1164         char cbuf[2];
1165         char c;
1166         char *pbuf;
1167
1168         cmdedit_prmt_len = 0;
1169
1170         if (!cwd_buf) {
1171                 cwd_buf = (char *)bb_msg_unknown;
1172         }
1173
1174         cbuf[1] = '\0'; /* never changes */
1175
1176         while (*prmt_ptr) {
1177                 char *free_me = NULL;
1178
1179                 pbuf = cbuf;
1180                 c = *prmt_ptr++;
1181                 if (c == '\\') {
1182                         const char *cp = prmt_ptr;
1183                         int l;
1184
1185                         c = bb_process_escape_sequence(&prmt_ptr);
1186                         if (prmt_ptr == cp) {
1187                                 if (*cp == '\0')
1188                                         break;
1189                                 c = *prmt_ptr++;
1190
1191                                 switch (c) {
1192 #if ENABLE_FEATURE_GETUSERNAME_AND_HOMEDIR
1193                                 case 'u':
1194                                         pbuf = user_buf ? user_buf : (char*)"";
1195                                         break;
1196 #endif
1197                                 case 'h':
1198                                         pbuf = free_me = xzalloc(256);
1199                                         if (gethostname(pbuf, 255) < 0) {
1200                                                 pbuf[0] = '?';
1201                                                 pbuf[1] = '\0';
1202                                         }
1203                                         *strchrnul(pbuf, '.') = '\0';
1204                                         break;
1205                                 case '$':
1206                                         c = (geteuid() == 0 ? '#' : '$');
1207                                         break;
1208 #if ENABLE_FEATURE_GETUSERNAME_AND_HOMEDIR
1209                                 case 'w':
1210                                         /* /home/user[/something] -> ~[/something] */
1211                                         pbuf = cwd_buf;
1212                                         l = strlen(home_pwd_buf);
1213                                         if (l != 0
1214                                          && strncmp(home_pwd_buf, cwd_buf, l) == 0
1215                                          && (cwd_buf[l]=='/' || cwd_buf[l]=='\0')
1216                                          && strlen(cwd_buf + l) < PATH_MAX
1217                                         ) {
1218                                                 pbuf = free_me = xasprintf("~%s", cwd_buf + l);
1219                                         }
1220                                         break;
1221 #endif
1222                                 case 'W':
1223                                         pbuf = cwd_buf;
1224                                         cp = strrchr(pbuf, '/');
1225                                         if (cp != NULL && cp != pbuf)
1226                                                 pbuf += (cp-pbuf) + 1;
1227                                         break;
1228                                 case '!':
1229                                         pbuf = free_me = xasprintf("%d", num_ok_lines);
1230                                         break;
1231                                 case 'e': case 'E':     /* \e \E = \033 */
1232                                         c = '\033';
1233                                         break;
1234                                 case 'x': case 'X': {
1235                                         char buf2[4];
1236                                         for (l = 0; l < 3;) {
1237                                                 unsigned h;
1238                                                 buf2[l++] = *prmt_ptr;
1239                                                 buf2[l] = '\0';
1240                                                 h = strtoul(buf2, &pbuf, 16);
1241                                                 if (h > UCHAR_MAX || (pbuf - buf2) < l) {
1242                                                         buf2[--l] = '\0';
1243                                                         break;
1244                                                 }
1245                                                 prmt_ptr++;
1246                                         }
1247                                         c = (char)strtoul(buf2, NULL, 16);
1248                                         if (c == 0)
1249                                                 c = '?';
1250                                         pbuf = cbuf;
1251                                         break;
1252                                 }
1253                                 case '[': case ']':
1254                                         if (c == flg_not_length) {
1255                                                 flg_not_length = (flg_not_length == '[' ? ']' : '[');
1256                                                 continue;
1257                                         }
1258                                         break;
1259                                 } /* switch */
1260                         } /* if */
1261                 } /* if */
1262                 cbuf[0] = c;
1263                 cur_prmt_len = strlen(pbuf);
1264                 prmt_len += cur_prmt_len;
1265                 if (flg_not_length != ']')
1266                         cmdedit_prmt_len += cur_prmt_len;
1267                 prmt_mem_ptr = strcat(xrealloc(prmt_mem_ptr, prmt_len+1), pbuf);
1268                 free(free_me);
1269         } /* while */
1270
1271         if (cwd_buf != (char *)bb_msg_unknown)
1272                 free(cwd_buf);
1273         cmdedit_prompt = prmt_mem_ptr;
1274         put_prompt();
1275 }
1276 #endif
1277
1278 static void cmdedit_setwidth(unsigned w, int redraw_flg)
1279 {
1280         cmdedit_termw = w;
1281         if (redraw_flg) {
1282                 /* new y for current cursor */
1283                 int new_y = (cursor + cmdedit_prmt_len) / w;
1284                 /* redraw */
1285                 redraw((new_y >= cmdedit_y ? new_y : cmdedit_y), command_len - cursor);
1286                 fflush(stdout);
1287         }
1288 }
1289
1290 static void win_changed(int nsig)
1291 {
1292         int width;
1293         get_terminal_width_height(0, &width, NULL);
1294         cmdedit_setwidth(width, nsig /* - just a yes/no flag */);
1295         if (nsig == SIGWINCH)
1296                 signal(SIGWINCH, win_changed); /* rearm ourself */
1297 }
1298
1299 /*
1300  * The emacs and vi modes share much of the code in the big
1301  * command loop.  Commands entered when in vi's command mode (aka
1302  * "escape mode") get an extra bit added to distinguish them --
1303  * this keeps them from being self-inserted.  This clutters the
1304  * big switch a bit, but keeps all the code in one place.
1305  */
1306
1307 #define vbit 0x100
1308
1309 /* leave out the "vi-mode"-only case labels if vi editing isn't
1310  * configured. */
1311 #define vi_case(caselabel) USE_FEATURE_EDITING(case caselabel)
1312
1313 /* convert uppercase ascii to equivalent control char, for readability */
1314 #undef CTRL
1315 #define CTRL(a) ((a) & ~0x40)
1316
1317 /* Returns:
1318  * -1 on read errors or EOF, or on bare Ctrl-D,
1319  * 0  on ctrl-C (the line entered is still returned in 'command'),
1320  * >0 length of input string, including terminating '\n'
1321  */
1322 int read_line_input(const char *prompt, char *command, int maxsize, line_input_t *st)
1323 {
1324 #if ENABLE_FEATURE_TAB_COMPLETION
1325         smallint lastWasTab = FALSE;
1326 #endif
1327         unsigned int ic;
1328         unsigned char c;
1329         smallint break_out = 0;
1330 #if ENABLE_FEATURE_EDITING_VI
1331         smallint vi_cmdmode = 0;
1332         smalluint prevc;
1333 #endif
1334         struct termios initial_settings;
1335         struct termios new_settings;
1336
1337         INIT_S();
1338
1339         if (tcgetattr(STDIN_FILENO, &initial_settings) < 0
1340          || !(initial_settings.c_lflag & ECHO)
1341         ) {
1342                 /* Happens when e.g. stty -echo was run before */
1343                 int len;
1344                 parse_and_put_prompt(prompt);
1345                 fflush(stdout);
1346                 if (fgets(command, maxsize, stdin) == NULL)
1347                         len = -1; /* EOF or error */
1348                 else
1349                         len = strlen(command);
1350                 DEINIT_S();
1351                 return len;
1352         }
1353
1354 // FIXME: audit & improve this
1355         if (maxsize > MAX_LINELEN)
1356                 maxsize = MAX_LINELEN;
1357
1358         /* With null flags, no other fields are ever used */
1359         state = st ? st : (line_input_t*) &const_int_0;
1360 #if ENABLE_FEATURE_EDITING_SAVEHISTORY
1361         if ((state->flags & SAVE_HISTORY) && state->hist_file)
1362                 load_history(state->hist_file);
1363 #endif
1364
1365         /* prepare before init handlers */
1366         cmdedit_y = 0;  /* quasireal y, not true if line > xt*yt */
1367         command_len = 0;
1368         command_ps = command;
1369         command[0] = '\0';
1370
1371         new_settings = initial_settings;
1372         new_settings.c_lflag &= ~ICANON;        /* unbuffered input */
1373         /* Turn off echoing and CTRL-C, so we can trap it */
1374         new_settings.c_lflag &= ~(ECHO | ECHONL | ISIG);
1375         /* Hmm, in linux c_cc[] is not parsed if ICANON is off */
1376         new_settings.c_cc[VMIN] = 1;
1377         new_settings.c_cc[VTIME] = 0;
1378         /* Turn off CTRL-C, so we can trap it */
1379 #ifndef _POSIX_VDISABLE
1380 #define _POSIX_VDISABLE '\0'
1381 #endif
1382         new_settings.c_cc[VINTR] = _POSIX_VDISABLE;
1383         tcsetattr(STDIN_FILENO, TCSANOW, &new_settings);
1384
1385         /* Now initialize things */
1386         previous_SIGWINCH_handler = signal(SIGWINCH, win_changed);
1387         win_changed(0); /* do initial resizing */
1388 #if ENABLE_FEATURE_GETUSERNAME_AND_HOMEDIR
1389         {
1390                 struct passwd *entry;
1391
1392                 entry = getpwuid(geteuid());
1393                 if (entry) {
1394                         user_buf = xstrdup(entry->pw_name);
1395                         home_pwd_buf = xstrdup(entry->pw_dir);
1396                 }
1397         }
1398 #endif
1399         /* Print out the command prompt */
1400         parse_and_put_prompt(prompt);
1401
1402         while (1) {
1403                 fflush(stdout);
1404
1405                 if (safe_read(STDIN_FILENO, &c, 1) < 1) {
1406                         /* if we can't read input then exit */
1407                         goto prepare_to_die;
1408                 }
1409
1410                 ic = c;
1411
1412 #if ENABLE_FEATURE_EDITING_VI
1413                 newdelflag = 1;
1414                 if (vi_cmdmode)
1415                         ic |= vbit;
1416 #endif
1417                 switch (ic) {
1418                 case '\n':
1419                 case '\r':
1420                 vi_case('\n'|vbit:)
1421                 vi_case('\r'|vbit:)
1422                         /* Enter */
1423                         goto_new_line();
1424                         break_out = 1;
1425                         break;
1426                 case CTRL('A'):
1427                 vi_case('0'|vbit:)
1428                         /* Control-a -- Beginning of line */
1429                         input_backward(cursor);
1430                         break;
1431                 case CTRL('B'):
1432                 vi_case('h'|vbit:)
1433                 vi_case('\b'|vbit:)
1434                 vi_case('\x7f'|vbit:) /* DEL */
1435                         /* Control-b -- Move back one character */
1436                         input_backward(1);
1437                         break;
1438                 case CTRL('C'):
1439                 vi_case(CTRL('C')|vbit:)
1440                         /* Control-c -- stop gathering input */
1441                         goto_new_line();
1442                         command_len = 0;
1443                         break_out = -1; /* "do not append '\n'" */
1444                         break;
1445                 case CTRL('D'):
1446                         /* Control-d -- Delete one character, or exit
1447                          * if the len=0 and no chars to delete */
1448                         if (command_len == 0) {
1449                                 errno = 0;
1450  prepare_to_die:
1451                                 /* to control stopped jobs */
1452                                 break_out = command_len = -1;
1453                                 break;
1454                         }
1455                         input_delete(0);
1456                         break;
1457
1458                 case CTRL('E'):
1459                 vi_case('$'|vbit:)
1460                         /* Control-e -- End of line */
1461                         input_end();
1462                         break;
1463                 case CTRL('F'):
1464                 vi_case('l'|vbit:)
1465                 vi_case(' '|vbit:)
1466                         /* Control-f -- Move forward one character */
1467                         input_forward();
1468                         break;
1469
1470                 case '\b':
1471                 case '\x7f': /* DEL */
1472                         /* Control-h and DEL */
1473                         input_backspace();
1474                         break;
1475
1476 #if ENABLE_FEATURE_TAB_COMPLETION
1477                 case '\t':
1478                         input_tab(&lastWasTab);
1479                         break;
1480 #endif
1481
1482                 case CTRL('K'):
1483                         /* Control-k -- clear to end of line */
1484                         command[cursor] = 0;
1485                         command_len = cursor;
1486                         printf("\033[J");
1487                         break;
1488                 case CTRL('L'):
1489                 vi_case(CTRL('L')|vbit:)
1490                         /* Control-l -- clear screen */
1491                         printf("\033[H");
1492                         redraw(0, command_len - cursor);
1493                         break;
1494
1495 #if MAX_HISTORY > 0
1496                 case CTRL('N'):
1497                 vi_case(CTRL('N')|vbit:)
1498                 vi_case('j'|vbit:)
1499                         /* Control-n -- Get next command in history */
1500                         if (get_next_history())
1501                                 goto rewrite_line;
1502                         break;
1503                 case CTRL('P'):
1504                 vi_case(CTRL('P')|vbit:)
1505                 vi_case('k'|vbit:)
1506                         /* Control-p -- Get previous command from history */
1507                         if ((state->flags & DO_HISTORY) && state->cur_history > 0) {
1508                                 get_previous_history();
1509                                 goto rewrite_line;
1510                         }
1511                         beep();
1512                         break;
1513 #endif
1514
1515                 case CTRL('U'):
1516                 vi_case(CTRL('U')|vbit:)
1517                         /* Control-U -- Clear line before cursor */
1518                         if (cursor) {
1519                                 strcpy(command, command + cursor);
1520                                 command_len -= cursor;
1521                                 redraw(cmdedit_y, command_len);
1522                         }
1523                         break;
1524                 case CTRL('W'):
1525                 vi_case(CTRL('W')|vbit:)
1526                         /* Control-W -- Remove the last word */
1527                         while (cursor > 0 && isspace(command[cursor-1]))
1528                                 input_backspace();
1529                         while (cursor > 0 && !isspace(command[cursor-1]))
1530                                 input_backspace();
1531                         break;
1532
1533 #if ENABLE_FEATURE_EDITING_VI
1534                 case 'i'|vbit:
1535                         vi_cmdmode = 0;
1536                         break;
1537                 case 'I'|vbit:
1538                         input_backward(cursor);
1539                         vi_cmdmode = 0;
1540                         break;
1541                 case 'a'|vbit:
1542                         input_forward();
1543                         vi_cmdmode = 0;
1544                         break;
1545                 case 'A'|vbit:
1546                         input_end();
1547                         vi_cmdmode = 0;
1548                         break;
1549                 case 'x'|vbit:
1550                         input_delete(1);
1551                         break;
1552                 case 'X'|vbit:
1553                         if (cursor > 0) {
1554                                 input_backward(1);
1555                                 input_delete(1);
1556                         }
1557                         break;
1558                 case 'W'|vbit:
1559                         vi_Word_motion(command, 1);
1560                         break;
1561                 case 'w'|vbit:
1562                         vi_word_motion(command, 1);
1563                         break;
1564                 case 'E'|vbit:
1565                         vi_End_motion(command);
1566                         break;
1567                 case 'e'|vbit:
1568                         vi_end_motion(command);
1569                         break;
1570                 case 'B'|vbit:
1571                         vi_Back_motion(command);
1572                         break;
1573                 case 'b'|vbit:
1574                         vi_back_motion(command);
1575                         break;
1576                 case 'C'|vbit:
1577                         vi_cmdmode = 0;
1578                         /* fall through */
1579                 case 'D'|vbit:
1580                         goto clear_to_eol;
1581
1582                 case 'c'|vbit:
1583                         vi_cmdmode = 0;
1584                         /* fall through */
1585                 case 'd'|vbit: {
1586                         int nc, sc;
1587                         sc = cursor;
1588                         prevc = ic;
1589                         if (safe_read(STDIN_FILENO, &c, 1) < 1)
1590                                 goto prepare_to_die;
1591                         if (c == (prevc & 0xff)) {
1592                                 /* "cc", "dd" */
1593                                 input_backward(cursor);
1594                                 goto clear_to_eol;
1595                                 break;
1596                         }
1597                         switch (c) {
1598                         case 'w':
1599                         case 'W':
1600                         case 'e':
1601                         case 'E':
1602                                 switch (c) {
1603                                 case 'w':   /* "dw", "cw" */
1604                                         vi_word_motion(command, vi_cmdmode);
1605                                         break;
1606                                 case 'W':   /* 'dW', 'cW' */
1607                                         vi_Word_motion(command, vi_cmdmode);
1608                                         break;
1609                                 case 'e':   /* 'de', 'ce' */
1610                                         vi_end_motion(command);
1611                                         input_forward();
1612                                         break;
1613                                 case 'E':   /* 'dE', 'cE' */
1614                                         vi_End_motion(command);
1615                                         input_forward();
1616                                         break;
1617                                 }
1618                                 nc = cursor;
1619                                 input_backward(cursor - sc);
1620                                 while (nc-- > cursor)
1621                                         input_delete(1);
1622                                 break;
1623                         case 'b':  /* "db", "cb" */
1624                         case 'B':  /* implemented as B */
1625                                 if (c == 'b')
1626                                         vi_back_motion(command);
1627                                 else
1628                                         vi_Back_motion(command);
1629                                 while (sc-- > cursor)
1630                                         input_delete(1);
1631                                 break;
1632                         case ' ':  /* "d ", "c " */
1633                                 input_delete(1);
1634                                 break;
1635                         case '$':  /* "d$", "c$" */
1636                         clear_to_eol:
1637                                 while (cursor < command_len)
1638                                         input_delete(1);
1639                                 break;
1640                         }
1641                         break;
1642                 }
1643                 case 'p'|vbit:
1644                         input_forward();
1645                         /* fallthrough */
1646                 case 'P'|vbit:
1647                         put();
1648                         break;
1649                 case 'r'|vbit:
1650                         if (safe_read(STDIN_FILENO, &c, 1) < 1)
1651                                 goto prepare_to_die;
1652                         if (c == 0)
1653                                 beep();
1654                         else {
1655                                 *(command + cursor) = c;
1656                                 bb_putchar(c);
1657                                 bb_putchar('\b');
1658                         }
1659                         break;
1660 #endif /* FEATURE_COMMAND_EDITING_VI */
1661
1662                 case '\x1b': /* ESC */
1663
1664 #if ENABLE_FEATURE_EDITING_VI
1665                         if (state->flags & VI_MODE) {
1666                                 /* ESC: insert mode --> command mode */
1667                                 vi_cmdmode = 1;
1668                                 input_backward(1);
1669                                 break;
1670                         }
1671 #endif
1672                         /* escape sequence follows */
1673                         if (safe_read(STDIN_FILENO, &c, 1) < 1)
1674                                 goto prepare_to_die;
1675                         /* different vt100 emulations */
1676                         if (c == '[' || c == 'O') {
1677                 vi_case('['|vbit:)
1678                 vi_case('O'|vbit:)
1679                                 if (safe_read(STDIN_FILENO, &c, 1) < 1)
1680                                         goto prepare_to_die;
1681                         }
1682                         if (c >= '1' && c <= '9') {
1683                                 unsigned char dummy;
1684
1685                                 if (safe_read(STDIN_FILENO, &dummy, 1) < 1)
1686                                         goto prepare_to_die;
1687                                 if (dummy != '~')
1688                                         c = '\0';
1689                         }
1690
1691                         switch (c) {
1692 #if ENABLE_FEATURE_TAB_COMPLETION
1693                         case '\t':                      /* Alt-Tab */
1694                                 input_tab(&lastWasTab);
1695                                 break;
1696 #endif
1697 #if MAX_HISTORY > 0
1698                         case 'A':
1699                                 /* Up Arrow -- Get previous command from history */
1700                                 if ((state->flags & DO_HISTORY) && state->cur_history > 0) {
1701                                         get_previous_history();
1702                                         goto rewrite_line;
1703                                 }
1704                                 beep();
1705                                 break;
1706                         case 'B':
1707                                 /* Down Arrow -- Get next command in history */
1708                                 if (!get_next_history())
1709                                         break;
1710  rewrite_line:
1711                                 /* Rewrite the line with the selected history item */
1712                                 /* change command */
1713                                 command_len = strlen(strcpy(command, state->history[state->cur_history]));
1714                                 /* redraw and go to eol (bol, in vi */
1715                                 redraw(cmdedit_y, (state->flags & VI_MODE) ? 9999 : 0);
1716                                 break;
1717 #endif
1718                         case 'C':
1719                                 /* Right Arrow -- Move forward one character */
1720                                 input_forward();
1721                                 break;
1722                         case 'D':
1723                                 /* Left Arrow -- Move back one character */
1724                                 input_backward(1);
1725                                 break;
1726                         case '3':
1727                                 /* Delete */
1728                                 input_delete(0);
1729                                 break;
1730                         case '1': // vt100? linux vt? or what?
1731                         case '7': // vt100? linux vt? or what?
1732                         case 'H': /* xterm's <Home> */
1733                                 input_backward(cursor);
1734                                 break;
1735                         case '4': // vt100? linux vt? or what?
1736                         case '8': // vt100? linux vt? or what?
1737                         case 'F': /* xterm's <End> */
1738                                 input_end();
1739                                 break;
1740                         default:
1741                                 c = '\0';
1742                                 beep();
1743                         }
1744                         break;
1745
1746                 default:        /* If it's regular input, do the normal thing */
1747
1748                         /* Control-V -- force insert of next char */
1749                         if (c == CTRL('V')) {
1750                                 if (safe_read(STDIN_FILENO, &c, 1) < 1)
1751                                         goto prepare_to_die;
1752                                 if (c == 0) {
1753                                         beep();
1754                                         break;
1755                                 }
1756                         }
1757
1758 #if ENABLE_FEATURE_EDITING_VI
1759                         if (vi_cmdmode)  /* Don't self-insert */
1760                                 break;
1761 #endif
1762                         if (command_len >= (maxsize - 2))        /* Need to leave space for enter */
1763                                 break;
1764
1765                         command_len++;
1766                         if (cursor == (command_len - 1)) {      /* Append if at the end of the line */
1767                                 command[cursor] = c;
1768                                 command[cursor+1] = '\0';
1769                                 cmdedit_set_out_char(' ');
1770                         } else {                        /* Insert otherwise */
1771                                 int sc = cursor;
1772
1773                                 memmove(command + sc + 1, command + sc, command_len - sc);
1774                                 command[sc] = c;
1775                                 sc++;
1776                                 /* rewrite from cursor */
1777                                 input_end();
1778                                 /* to prev x pos + 1 */
1779                                 input_backward(cursor - sc);
1780                         }
1781                         break;
1782                 }
1783                 if (break_out)                  /* Enter is the command terminator, no more input. */
1784                         break;
1785
1786 #if ENABLE_FEATURE_TAB_COMPLETION
1787                 if (c != '\t')
1788                         lastWasTab = FALSE;
1789 #endif
1790         }
1791
1792         if (command_len > 0)
1793                 remember_in_history(command);
1794
1795         if (break_out > 0) {
1796                 command[command_len++] = '\n';
1797                 command[command_len] = '\0';
1798         }
1799
1800 #if ENABLE_FEATURE_TAB_COMPLETION
1801         free_tab_completion_data();
1802 #endif
1803
1804         /* restore initial_settings */
1805         tcsetattr(STDIN_FILENO, TCSANOW, &initial_settings);
1806         /* restore SIGWINCH handler */
1807         signal(SIGWINCH, previous_SIGWINCH_handler);
1808         fflush(stdout);
1809
1810         DEINIT_S();
1811
1812         return command_len;
1813 }
1814
1815 line_input_t *new_line_input_t(int flags)
1816 {
1817         line_input_t *n = xzalloc(sizeof(*n));
1818         n->flags = flags;
1819         return n;
1820 }
1821
1822 #else
1823
1824 #undef read_line_input
1825 int read_line_input(const char* prompt, char* command, int maxsize)
1826 {
1827         fputs(prompt, stdout);
1828         fflush(stdout);
1829         fgets(command, maxsize, stdin);
1830         return strlen(command);
1831 }
1832
1833 #endif  /* FEATURE_COMMAND_EDITING */
1834
1835
1836 /*
1837  * Testing
1838  */
1839
1840 #ifdef TEST
1841
1842 #include <locale.h>
1843
1844 const char *applet_name = "debug stuff usage";
1845
1846 int main(int argc, char **argv)
1847 {
1848         char buff[MAX_LINELEN];
1849         char *prompt =
1850 #if ENABLE_FEATURE_EDITING_FANCY_PROMPT
1851                 "\\[\\033[32;1m\\]\\u@\\[\\x1b[33;1m\\]\\h:"
1852                 "\\[\\033[34;1m\\]\\w\\[\\033[35;1m\\] "
1853                 "\\!\\[\\e[36;1m\\]\\$ \\[\\E[0m\\]";
1854 #else
1855                 "% ";
1856 #endif
1857
1858 #if ENABLE_FEATURE_NONPRINTABLE_INVERSE_PUT
1859         setlocale(LC_ALL, "");
1860 #endif
1861         while (1) {
1862                 int l;
1863                 l = read_line_input(prompt, buff);
1864                 if (l <= 0 || buff[l-1] != '\n')
1865                         break;
1866                 buff[l-1] = 0;
1867                 printf("*** read_line_input() returned line =%s=\n", buff);
1868         }
1869         printf("*** read_line_input() detect ^D\n");
1870         return 0;
1871 }
1872
1873 #endif  /* TEST */