7e408207c94e09284473b6479d6c34e49ee1cdb5
[platform/upstream/busybox.git] / libbb / lineedit.c
1 /* vi: set sw=4 ts=4: */
2 /*
3  * Termios command line History and Editing.
4  *
5  * Copyright (c) 1986-2003 may safely be consumed by a BSD or GPL license.
6  * Written by:   Vladimir Oleynik <dzo@simtreas.ru>
7  *
8  * Used ideas:
9  *      Adam Rogoyski    <rogoyski@cs.utexas.edu>
10  *      Dave Cinege      <dcinege@psychosis.com>
11  *      Jakub Jelinek (c) 1995
12  *      Erik Andersen    <andersen@codepoet.org> (Majorly adjusted for busybox)
13  *
14  * This code is 'as is' with no warranty.
15  */
16
17 /*
18    Usage and known bugs:
19    Terminal key codes are not extensive, and more will probably
20    need to be added. This version was created on Debian GNU/Linux 2.x.
21    Delete, Backspace, Home, End, and the arrow keys were tested
22    to work in an Xterm and console. Ctrl-A also works as Home.
23    Ctrl-E also works as End.
24
25    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         barrier(); \
150         cmdedit_termw = 80; \
151         USE_FEATURE_EDITING_FANCY_PROMPT(num_ok_lines = 1;) \
152         USE_FEATURE_GETUSERNAME_AND_HOMEDIR(home_pwd_buf = (char*)null_str;) \
153 } while (0)
154 static void deinit_S(void)
155 {
156 #if ENABLE_FEATURE_EDITING_FANCY_PROMPT
157         /* This one is allocated only if FANCY_PROMPT is on
158          * (otherwise it points to verbatim prompt (NOT malloced) */
159         free((char*)cmdedit_prompt);
160 #endif
161 #if ENABLE_FEATURE_GETUSERNAME_AND_HOMEDIR
162         free(user_buf);
163         if (home_pwd_buf != null_str)
164                 free(home_pwd_buf);
165 #endif
166         free(ptr_to_statics);
167 }
168 #define DEINIT_S() deinit_S()
169
170 /* Put 'command_ps[cursor]', cursor++.
171  * Advance cursor on screen. If we reached right margin, scroll text up
172  * and remove terminal margin effect by printing 'next_char' */
173 static void cmdedit_set_out_char(int next_char)
174 {
175         int c = (unsigned char)command_ps[cursor];
176
177         if (c == '\0') {
178                 /* erase character after end of input string */
179                 c = ' ';
180         }
181 #if ENABLE_FEATURE_NONPRINTABLE_INVERSE_PUT
182         /* Display non-printable characters in reverse */
183         if (!Isprint(c)) {
184                 if (c >= 128)
185                         c -= 128;
186                 if (c < ' ')
187                         c += '@';
188                 if (c == 127)
189                         c = '?';
190                 printf("\033[7m%c\033[0m", c);
191         } else
192 #endif
193         {
194                 bb_putchar(c);
195         }
196         if (++cmdedit_x >= cmdedit_termw) {
197                 /* terminal is scrolled down */
198                 cmdedit_y++;
199                 cmdedit_x = 0;
200                 /* destroy "(auto)margin" */
201                 bb_putchar(next_char);
202                 bb_putchar('\b');
203         }
204 // Huh? What if command_ps[cursor] == '\0' (we are at the end already?)
205         cursor++;
206 }
207
208 /* Move to end of line (by printing all chars till the end) */
209 static void input_end(void)
210 {
211         while (cursor < command_len)
212                 cmdedit_set_out_char(' ');
213 }
214
215 /* Go to the next line */
216 static void goto_new_line(void)
217 {
218         input_end();
219         if (cmdedit_x)
220                 bb_putchar('\n');
221 }
222
223
224 static void out1str(const char *s)
225 {
226         if (s)
227                 fputs(s, stdout);
228 }
229
230 static void beep(void)
231 {
232         bb_putchar('\007');
233 }
234
235 /* Move back one character */
236 /* (optimized for slow terminals) */
237 static void input_backward(unsigned num)
238 {
239         int count_y;
240
241         if (num > cursor)
242                 num = cursor;
243         if (!num)
244                 return;
245         cursor -= num;
246
247         if (cmdedit_x >= num) {
248                 cmdedit_x -= num;
249                 if (num <= 4) {
250                         /* This is longer by 5 bytes on x86.
251                          * Also gets mysteriously
252                          * miscompiled for some ARM users.
253                          * printf(("\b\b\b\b" + 4) - num);
254                          * return;
255                          */
256                         do {
257                                 bb_putchar('\b');
258                         } while (--num);
259                         return;
260                 }
261                 printf("\033[%uD", num);
262                 return;
263         }
264
265         /* Need to go one or more lines up */
266         num -= cmdedit_x;
267         count_y = 1 + (num / cmdedit_termw);
268         cmdedit_y -= count_y;
269         cmdedit_x = cmdedit_termw * count_y - num;
270         /* go to 1st column; go up; go to correct column */
271         printf("\r" "\033[%dA" "\033[%dC", count_y, cmdedit_x);
272 }
273
274 static void put_prompt(void)
275 {
276         out1str(cmdedit_prompt);
277         cmdedit_x = cmdedit_prmt_len;
278         cursor = 0;
279 // Huh? what if cmdedit_prmt_len >= width?
280         cmdedit_y = 0;                  /* new quasireal y */
281 }
282
283 /* draw prompt, editor line, and clear tail */
284 static void redraw(int y, int back_cursor)
285 {
286         if (y > 0)                              /* up to start y */
287                 printf("\033[%dA", y);
288         bb_putchar('\r');
289         put_prompt();
290         input_end();                            /* rewrite */
291         printf("\033[J");                       /* erase after cursor */
292         input_backward(back_cursor);
293 }
294
295 /* Delete the char in front of the cursor, optionally saving it
296  * for later putback */
297 static void input_delete(int save)
298 {
299         int j = cursor;
300
301         if (j == command_len)
302                 return;
303
304 #if ENABLE_FEATURE_EDITING_VI
305         if (save) {
306                 if (newdelflag) {
307                         delptr = delbuf;
308                         newdelflag = 0;
309                 }
310                 if ((delptr - delbuf) < DELBUFSIZ)
311                         *delptr++ = command_ps[j];
312         }
313 #endif
314
315         strcpy(command_ps + j, command_ps + j + 1);
316         command_len--;
317         input_end();                    /* rewrite new line */
318         cmdedit_set_out_char(' ');      /* erase char */
319         input_backward(cursor - j);     /* back to old pos cursor */
320 }
321
322 #if ENABLE_FEATURE_EDITING_VI
323 static void put(void)
324 {
325         int ocursor;
326         int j = delptr - delbuf;
327
328         if (j == 0)
329                 return;
330         ocursor = cursor;
331         /* open hole and then fill it */
332         memmove(command_ps + cursor + j, command_ps + cursor, command_len - cursor + 1);
333         strncpy(command_ps + cursor, delbuf, j);
334         command_len += j;
335         input_end();                    /* rewrite new line */
336         input_backward(cursor - ocursor - j + 1); /* at end of new text */
337 }
338 #endif
339
340 /* Delete the char in back of the cursor */
341 static void input_backspace(void)
342 {
343         if (cursor > 0) {
344                 input_backward(1);
345                 input_delete(0);
346         }
347 }
348
349 /* Move forward one character */
350 static void input_forward(void)
351 {
352         if (cursor < command_len)
353                 cmdedit_set_out_char(command_ps[cursor + 1]);
354 }
355
356 #if ENABLE_FEATURE_TAB_COMPLETION
357
358 static void free_tab_completion_data(void)
359 {
360         if (matches) {
361                 while (num_matches)
362                         free(matches[--num_matches]);
363                 free(matches);
364                 matches = NULL;
365         }
366 }
367
368 static void add_match(char *matched)
369 {
370         int nm = num_matches;
371         int nm1 = nm + 1;
372
373         matches = xrealloc(matches, nm1 * sizeof(char *));
374         matches[nm] = matched;
375         num_matches++;
376 }
377
378 #if ENABLE_FEATURE_USERNAME_COMPLETION
379 static void username_tab_completion(char *ud, char *with_shash_flg)
380 {
381         struct passwd *entry;
382         int userlen;
383
384         ud++;                           /* ~user/... to user/... */
385         userlen = strlen(ud);
386
387         if (with_shash_flg) {           /* "~/..." or "~user/..." */
388                 char *sav_ud = ud - 1;
389                 char *home = NULL;
390
391                 if (*ud == '/') {       /* "~/..."     */
392                         home = home_pwd_buf;
393                 } else {
394                         /* "~user/..." */
395                         char *temp;
396                         temp = strchr(ud, '/');
397                         *temp = '\0';           /* ~user\0 */
398                         entry = getpwnam(ud);
399                         *temp = '/';            /* restore ~user/... */
400                         ud = temp;
401                         if (entry)
402                                 home = entry->pw_dir;
403                 }
404                 if (home) {
405                         if ((userlen + strlen(home) + 1) < MAX_LINELEN) {
406                                 /* /home/user/... */
407                                 sprintf(sav_ud, "%s%s", home, ud);
408                         }
409                 }
410         } else {
411                 /* "~[^/]*" */
412                 /* Using _r function to avoid pulling in static buffers */
413                 char line_buff[256];
414                 struct passwd pwd;
415                 struct passwd *result;
416
417                 setpwent();
418                 while (!getpwent_r(&pwd, line_buff, sizeof(line_buff), &result)) {
419                         /* Null usernames should result in all users as possible completions. */
420                         if (/*!userlen || */ strncmp(ud, pwd.pw_name, userlen) == 0) {
421                                 add_match(xasprintf("~%s/", pwd.pw_name));
422                         }
423                 }
424                 endpwent();
425         }
426 }
427 #endif  /* FEATURE_COMMAND_USERNAME_COMPLETION */
428
429 enum {
430         FIND_EXE_ONLY = 0,
431         FIND_DIR_ONLY = 1,
432         FIND_FILE_ONLY = 2,
433 };
434
435 static int path_parse(char ***p, int flags)
436 {
437         int npth;
438         const char *pth;
439         char *tmp;
440         char **res;
441
442         /* if not setenv PATH variable, to search cur dir "." */
443         if (flags != FIND_EXE_ONLY)
444                 return 1;
445
446         if (state->flags & WITH_PATH_LOOKUP)
447                 pth = state->path_lookup;
448         else
449                 pth = getenv("PATH");
450         /* PATH=<empty> or PATH=:<empty> */
451         if (!pth || !pth[0] || LONE_CHAR(pth, ':'))
452                 return 1;
453
454         tmp = (char*)pth;
455         npth = 1; /* path component count */
456         while (1) {
457                 tmp = strchr(tmp, ':');
458                 if (!tmp)
459                         break;
460                 if (*++tmp == '\0')
461                         break;  /* :<empty> */
462                 npth++;
463         }
464
465         res = xmalloc(npth * sizeof(char*));
466         res[0] = tmp = xstrdup(pth);
467         npth = 1;
468         while (1) {
469                 tmp = strchr(tmp, ':');
470                 if (!tmp)
471                         break;
472                 *tmp++ = '\0'; /* ':' -> '\0' */
473                 if (*tmp == '\0')
474                         break; /* :<empty> */
475                 res[npth++] = tmp;
476         }
477         *p = res;
478         return npth;
479 }
480
481 static void exe_n_cwd_tab_completion(char *command, int type)
482 {
483         DIR *dir;
484         struct dirent *next;
485         struct stat st;
486         char *path1[1];
487         char **paths = path1;
488         int npaths;
489         int i;
490         char *found;
491         char *pfind = strrchr(command, '/');
492 /*      char dirbuf[MAX_LINELEN]; */
493 #define dirbuf (S.exe_n_cwd_tab_completion__dirbuf)
494
495         npaths = 1;
496         path1[0] = (char*)".";
497
498         if (pfind == NULL) {
499                 /* no dir, if flags==EXE_ONLY - get paths, else "." */
500                 npaths = path_parse(&paths, type);
501                 pfind = command;
502         } else {
503                 /* dirbuf = ".../.../.../" */
504                 safe_strncpy(dirbuf, command, (pfind - command) + 2);
505 #if ENABLE_FEATURE_USERNAME_COMPLETION
506                 if (dirbuf[0] == '~')   /* ~/... or ~user/... */
507                         username_tab_completion(dirbuf, dirbuf);
508 #endif
509                 paths[0] = dirbuf;
510                 /* point to 'l' in "..../last_component" */
511                 pfind++;
512         }
513
514         for (i = 0; i < npaths; i++) {
515                 dir = opendir(paths[i]);
516                 if (!dir)                       /* Don't print an error */
517                         continue;
518
519                 while ((next = readdir(dir)) != NULL) {
520                         int len1;
521                         const char *str_found = next->d_name;
522
523                         /* matched? */
524                         if (strncmp(str_found, pfind, strlen(pfind)))
525                                 continue;
526                         /* not see .name without .match */
527                         if (*str_found == '.' && *pfind == 0) {
528                                 if (NOT_LONE_CHAR(paths[i], '/') || str_found[1])
529                                         continue;
530                                 str_found = ""; /* only "/" */
531                         }
532                         found = concat_path_file(paths[i], str_found);
533                         /* hmm, remover in progress? */
534                         if (lstat(found, &st) < 0)
535                                 goto cont;
536                         /* find with dirs? */
537                         if (paths[i] != dirbuf)
538                                 strcpy(found, next->d_name);    /* only name */
539
540                         len1 = strlen(found);
541                         found = xrealloc(found, len1 + 2);
542                         found[len1] = '\0';
543                         found[len1+1] = '\0';
544
545                         if (S_ISDIR(st.st_mode)) {
546                                 /* name is directory      */
547                                 if (found[len1-1] != '/') {
548                                         found[len1] = '/';
549                                 }
550                         } else {
551                                 /* not put found file if search only dirs for cd */
552                                 if (type == FIND_DIR_ONLY)
553                                         goto cont;
554                         }
555                         /* Add it to the list */
556                         add_match(found);
557                         continue;
558  cont:
559                         free(found);
560                 }
561                 closedir(dir);
562         }
563         if (paths != path1) {
564                 free(paths[0]);                 /* allocated memory only in first member */
565                 free(paths);
566         }
567 #undef dirbuf
568 }
569
570 #define QUOT (UCHAR_MAX+1)
571
572 #define collapse_pos(is, in) do { \
573         memmove(int_buf+(is), int_buf+(in), (MAX_LINELEN+1-(is)-(in)) * sizeof(pos_buf[0])); \
574         memmove(pos_buf+(is), pos_buf+(in), (MAX_LINELEN+1-(is)-(in)) * sizeof(pos_buf[0])); \
575 } while (0)
576
577 static int find_match(char *matchBuf, int *len_with_quotes)
578 {
579         int i, j;
580         int command_mode;
581         int c, c2;
582 /*      int16_t int_buf[MAX_LINELEN + 1]; */
583 /*      int16_t pos_buf[MAX_LINELEN + 1]; */
584 #define int_buf (S.find_match__int_buf)
585 #define pos_buf (S.find_match__pos_buf)
586
587         /* set to integer dimension characters and own positions */
588         for (i = 0;; i++) {
589                 int_buf[i] = (unsigned char)matchBuf[i];
590                 if (int_buf[i] == 0) {
591                         pos_buf[i] = -1;        /* indicator end line */
592                         break;
593                 }
594                 pos_buf[i] = i;
595         }
596
597         /* mask \+symbol and convert '\t' to ' ' */
598         for (i = j = 0; matchBuf[i]; i++, j++)
599                 if (matchBuf[i] == '\\') {
600                         collapse_pos(j, j + 1);
601                         int_buf[j] |= QUOT;
602                         i++;
603 #if ENABLE_FEATURE_NONPRINTABLE_INVERSE_PUT
604                         if (matchBuf[i] == '\t')        /* algorithm equivalent */
605                                 int_buf[j] = ' ' | QUOT;
606 #endif
607                 }
608 #if ENABLE_FEATURE_NONPRINTABLE_INVERSE_PUT
609                 else if (matchBuf[i] == '\t')
610                         int_buf[j] = ' ';
611 #endif
612
613         /* mask "symbols" or 'symbols' */
614         c2 = 0;
615         for (i = 0; int_buf[i]; i++) {
616                 c = int_buf[i];
617                 if (c == '\'' || c == '"') {
618                         if (c2 == 0)
619                                 c2 = c;
620                         else {
621                                 if (c == c2)
622                                         c2 = 0;
623                                 else
624                                         int_buf[i] |= QUOT;
625                         }
626                 } else if (c2 != 0 && c != '$')
627                         int_buf[i] |= QUOT;
628         }
629
630         /* skip commands with arguments if line has commands delimiters */
631         /* ';' ';;' '&' '|' '&&' '||' but `>&' `<&' `>|' */
632         for (i = 0; int_buf[i]; i++) {
633                 c = int_buf[i];
634                 c2 = int_buf[i + 1];
635                 j = i ? int_buf[i - 1] : -1;
636                 command_mode = 0;
637                 if (c == ';' || c == '&' || c == '|') {
638                         command_mode = 1 + (c == c2);
639                         if (c == '&') {
640                                 if (j == '>' || j == '<')
641                                         command_mode = 0;
642                         } else if (c == '|' && j == '>')
643                                 command_mode = 0;
644                 }
645                 if (command_mode) {
646                         collapse_pos(0, i + command_mode);
647                         i = -1;                         /* hack incremet */
648                 }
649         }
650         /* collapse `command...` */
651         for (i = 0; int_buf[i]; i++)
652                 if (int_buf[i] == '`') {
653                         for (j = i + 1; int_buf[j]; j++)
654                                 if (int_buf[j] == '`') {
655                                         collapse_pos(i, j + 1);
656                                         j = 0;
657                                         break;
658                                 }
659                         if (j) {
660                                 /* not found close ` - command mode, collapse all previous */
661                                 collapse_pos(0, i + 1);
662                                 break;
663                         } else
664                                 i--;                    /* hack incremet */
665                 }
666
667         /* collapse (command...(command...)...) or {command...{command...}...} */
668         c = 0;                                          /* "recursive" level */
669         c2 = 0;
670         for (i = 0; int_buf[i]; i++)
671                 if (int_buf[i] == '(' || int_buf[i] == '{') {
672                         if (int_buf[i] == '(')
673                                 c++;
674                         else
675                                 c2++;
676                         collapse_pos(0, i + 1);
677                         i = -1;                         /* hack incremet */
678                 }
679         for (i = 0; pos_buf[i] >= 0 && (c > 0 || c2 > 0); i++)
680                 if ((int_buf[i] == ')' && c > 0) || (int_buf[i] == '}' && c2 > 0)) {
681                         if (int_buf[i] == ')')
682                                 c--;
683                         else
684                                 c2--;
685                         collapse_pos(0, i + 1);
686                         i = -1;                         /* hack incremet */
687                 }
688
689         /* skip first not quote space */
690         for (i = 0; int_buf[i]; i++)
691                 if (int_buf[i] != ' ')
692                         break;
693         if (i)
694                 collapse_pos(0, i);
695
696         /* set find mode for completion */
697         command_mode = FIND_EXE_ONLY;
698         for (i = 0; int_buf[i]; i++)
699                 if (int_buf[i] == ' ' || int_buf[i] == '<' || int_buf[i] == '>') {
700                         if (int_buf[i] == ' ' && command_mode == FIND_EXE_ONLY
701                          && matchBuf[pos_buf[0]] == 'c'
702                          && matchBuf[pos_buf[1]] == 'd'
703                         ) {
704                                 command_mode = FIND_DIR_ONLY;
705                         } else {
706                                 command_mode = FIND_FILE_ONLY;
707                                 break;
708                         }
709                 }
710         for (i = 0; int_buf[i]; i++)
711                 /* "strlen" */;
712         /* find last word */
713         for (--i; i >= 0; i--) {
714                 c = int_buf[i];
715                 if (c == ' ' || c == '<' || c == '>' || c == '|' || c == '&') {
716                         collapse_pos(0, i + 1);
717                         break;
718                 }
719         }
720         /* skip first not quoted '\'' or '"' */
721         for (i = 0; int_buf[i] == '\'' || int_buf[i] == '"'; i++)
722                 /*skip*/;
723         /* collapse quote or unquote // or /~ */
724         while ((int_buf[i] & ~QUOT) == '/'
725          && ((int_buf[i+1] & ~QUOT) == '/' || (int_buf[i+1] & ~QUOT) == '~')
726         ) {
727                 i++;
728         }
729
730         /* set only match and destroy quotes */
731         j = 0;
732         for (c = 0; pos_buf[i] >= 0; i++) {
733                 matchBuf[c++] = matchBuf[pos_buf[i]];
734                 j = pos_buf[i] + 1;
735         }
736         matchBuf[c] = '\0';
737         /* old length matchBuf with quotes symbols */
738         *len_with_quotes = j ? j - pos_buf[0] : 0;
739
740         return command_mode;
741 #undef int_buf
742 #undef pos_buf
743 }
744
745 /*
746  * display by column (original idea from ls applet,
747  * very optimized by me :)
748  */
749 static void showfiles(void)
750 {
751         int ncols, row;
752         int column_width = 0;
753         int nfiles = num_matches;
754         int nrows = nfiles;
755         int l;
756
757         /* find the longest file name-  use that as the column width */
758         for (row = 0; row < nrows; row++) {
759                 l = strlen(matches[row]);
760                 if (column_width < l)
761                         column_width = l;
762         }
763         column_width += 2;              /* min space for columns */
764         ncols = cmdedit_termw / column_width;
765
766         if (ncols > 1) {
767                 nrows /= ncols;
768                 if (nfiles % ncols)
769                         nrows++;        /* round up fractionals */
770         } else {
771                 ncols = 1;
772         }
773         for (row = 0; row < nrows; row++) {
774                 int n = row;
775                 int nc;
776
777                 for (nc = 1; nc < ncols && n+nrows < nfiles; n += nrows, nc++) {
778                         printf("%s%-*s", matches[n],
779                                 (int)(column_width - strlen(matches[n])), "");
780                 }
781                 puts(matches[n]);
782         }
783 }
784
785 static char *add_quote_for_spec_chars(char *found)
786 {
787         int l = 0;
788         char *s = xmalloc((strlen(found) + 1) * 2);
789
790         while (*found) {
791                 if (strchr(" `\"#$%^&*()=+{}[]:;\'|\\<>", *found))
792                         s[l++] = '\\';
793                 s[l++] = *found++;
794         }
795         s[l] = 0;
796         return s;
797 }
798
799 /* Do TAB completion */
800 static void input_tab(smallint *lastWasTab)
801 {
802         if (!(state->flags & TAB_COMPLETION))
803                 return;
804
805         if (!*lastWasTab) {
806                 char *tmp, *tmp1;
807                 int len_found;
808 /*              char matchBuf[MAX_LINELEN]; */
809 #define matchBuf (S.input_tab__matchBuf)
810                 int find_type;
811                 int recalc_pos;
812
813                 *lastWasTab = TRUE;             /* flop trigger */
814
815                 /* Make a local copy of the string -- up
816                  * to the position of the cursor */
817                 tmp = strncpy(matchBuf, command_ps, cursor);
818                 tmp[cursor] = '\0';
819
820                 find_type = find_match(matchBuf, &recalc_pos);
821
822                 /* Free up any memory already allocated */
823                 free_tab_completion_data();
824
825 #if ENABLE_FEATURE_USERNAME_COMPLETION
826                 /* If the word starts with `~' and there is no slash in the word,
827                  * then try completing this word as a username. */
828                 if (state->flags & USERNAME_COMPLETION)
829                         if (matchBuf[0] == '~' && strchr(matchBuf, '/') == 0)
830                                 username_tab_completion(matchBuf, NULL);
831 #endif
832                 /* Try to match any executable in our path and everything
833                  * in the current working directory */
834                 if (!matches)
835                         exe_n_cwd_tab_completion(matchBuf, find_type);
836                 /* Sort, then remove any duplicates found */
837                 if (matches) {
838                         int i, n = 0;
839                         qsort_string_vector(matches, num_matches);
840                         for (i = 0; i < num_matches - 1; ++i) {
841                                 if (matches[i] && matches[i+1]) { /* paranoia */
842                                         if (strcmp(matches[i], matches[i+1]) == 0) {
843                                                 free(matches[i]);
844                                                 matches[i] = NULL; /* paranoia */
845                                         } else {
846                                                 matches[n++] = matches[i];
847                                         }
848                                 }
849                         }
850                         matches[n] = matches[i];
851                         num_matches = n + 1;
852                 }
853                 /* Did we find exactly one match? */
854                 if (!matches || num_matches > 1) {
855                         beep();
856                         if (!matches)
857                                 return;         /* not found */
858                         /* find minimal match */
859                         tmp1 = xstrdup(matches[0]);
860                         for (tmp = tmp1; *tmp; tmp++)
861                                 for (len_found = 1; len_found < num_matches; len_found++)
862                                         if (matches[len_found][(tmp - tmp1)] != *tmp) {
863                                                 *tmp = '\0';
864                                                 break;
865                                         }
866                         if (*tmp1 == '\0') {        /* have unique */
867                                 free(tmp1);
868                                 return;
869                         }
870                         tmp = add_quote_for_spec_chars(tmp1);
871                         free(tmp1);
872                 } else {                        /* one match */
873                         tmp = add_quote_for_spec_chars(matches[0]);
874                         /* for next completion current found */
875                         *lastWasTab = FALSE;
876
877                         len_found = strlen(tmp);
878                         if (tmp[len_found-1] != '/') {
879                                 tmp[len_found] = ' ';
880                                 tmp[len_found+1] = '\0';
881                         }
882                 }
883                 len_found = strlen(tmp);
884                 /* have space to placed match? */
885                 if ((len_found - strlen(matchBuf) + command_len) < MAX_LINELEN) {
886                         /* before word for match   */
887                         command_ps[cursor - recalc_pos] = '\0';
888                         /* save   tail line        */
889                         strcpy(matchBuf, command_ps + cursor);
890                         /* add    match            */
891                         strcat(command_ps, tmp);
892                         /* add    tail             */
893                         strcat(command_ps, matchBuf);
894                         /* back to begin word for match    */
895                         input_backward(recalc_pos);
896                         /* new pos                         */
897                         recalc_pos = cursor + len_found;
898                         /* new len                         */
899                         command_len = strlen(command_ps);
900                         /* write out the matched command   */
901                         redraw(cmdedit_y, command_len - recalc_pos);
902                 }
903                 free(tmp);
904 #undef matchBuf
905         } else {
906                 /* Ok -- the last char was a TAB.  Since they
907                  * just hit TAB again, print a list of all the
908                  * available choices... */
909                 if (matches && num_matches > 0) {
910                         int sav_cursor = cursor;        /* change goto_new_line() */
911
912                         /* Go to the next line */
913                         goto_new_line();
914                         showfiles();
915                         redraw(0, command_len - sav_cursor);
916                 }
917         }
918 }
919
920 #endif  /* FEATURE_COMMAND_TAB_COMPLETION */
921
922
923 #if MAX_HISTORY > 0
924
925 /* state->flags is already checked to be nonzero */
926 static void get_previous_history(void)
927 {
928         if (command_ps[0] != '\0' || state->history[state->cur_history] == NULL) {
929                 free(state->history[state->cur_history]);
930                 state->history[state->cur_history] = xstrdup(command_ps);
931         }
932         state->cur_history--;
933 }
934
935 static int get_next_history(void)
936 {
937         if (state->flags & DO_HISTORY) {
938                 int ch = state->cur_history;
939                 if (ch < state->cnt_history) {
940                         get_previous_history(); /* save the current history line */
941                         state->cur_history = ch + 1;
942                         return state->cur_history;
943                 }
944         }
945         beep();
946         return 0;
947 }
948
949 #if ENABLE_FEATURE_EDITING_SAVEHISTORY
950 /* state->flags is already checked to be nonzero */
951 static void load_history(const char *fromfile)
952 {
953         FILE *fp;
954         int hi;
955
956         /* cleanup old */
957         for (hi = state->cnt_history; hi > 0;) {
958                 hi--;
959                 free(state->history[hi]);
960         }
961
962         fp = fopen(fromfile, "r");
963         if (fp) {
964                 for (hi = 0; hi < MAX_HISTORY;) {
965                         char *hl = xmalloc_getline(fp);
966                         int l;
967
968                         if (!hl)
969                                 break;
970                         l = strlen(hl);
971                         if (l >= MAX_LINELEN)
972                                 hl[MAX_LINELEN-1] = '\0';
973                         if (l == 0 || hl[0] == ' ') {
974                                 free(hl);
975                                 continue;
976                         }
977                         state->history[hi++] = hl;
978                 }
979                 fclose(fp);
980         }
981         state->cur_history = state->cnt_history = hi;
982 }
983
984 /* state->flags is already checked to be nonzero */
985 static void save_history(const char *tofile)
986 {
987         FILE *fp;
988
989         fp = fopen(tofile, "w");
990         if (fp) {
991                 int i;
992
993                 for (i = 0; i < state->cnt_history; i++) {
994                         fprintf(fp, "%s\n", state->history[i]);
995                 }
996                 fclose(fp);
997         }
998 }
999 #else
1000 #define load_history(a) ((void)0)
1001 #define save_history(a) ((void)0)
1002 #endif /* FEATURE_COMMAND_SAVEHISTORY */
1003
1004 static void remember_in_history(const char *str)
1005 {
1006         int i;
1007
1008         if (!(state->flags & DO_HISTORY))
1009                 return;
1010
1011         i = state->cnt_history;
1012         free(state->history[MAX_HISTORY]);
1013         state->history[MAX_HISTORY] = NULL;
1014         /* After max history, remove the oldest command */
1015         if (i >= MAX_HISTORY) {
1016                 free(state->history[0]);
1017                 for (i = 0; i < MAX_HISTORY-1; i++)
1018                         state->history[i] = state->history[i+1];
1019         }
1020 // Maybe "if (!i || strcmp(history[i-1], command) != 0) ..."
1021 // (i.e. do not save dups?)
1022         state->history[i++] = xstrdup(str);
1023         state->cur_history = i;
1024         state->cnt_history = i;
1025 #if ENABLE_FEATURE_EDITING_SAVEHISTORY
1026         if ((state->flags & SAVE_HISTORY) && state->hist_file)
1027                 save_history(state->hist_file);
1028 #endif
1029         USE_FEATURE_EDITING_FANCY_PROMPT(num_ok_lines++;)
1030 }
1031
1032 #else /* MAX_HISTORY == 0 */
1033 #define remember_in_history(a) ((void)0)
1034 #endif /* MAX_HISTORY */
1035
1036
1037 /*
1038  * This function is used to grab a character buffer
1039  * from the input file descriptor and allows you to
1040  * a string with full command editing (sort of like
1041  * a mini readline).
1042  *
1043  * The following standard commands are not implemented:
1044  * ESC-b -- Move back one word
1045  * ESC-f -- Move forward one word
1046  * ESC-d -- Delete back one word
1047  * ESC-h -- Delete forward one word
1048  * CTL-t -- Transpose two characters
1049  *
1050  * Minimalist vi-style command line editing available if configured.
1051  * vi mode implemented 2005 by Paul Fox <pgf@foxharp.boston.ma.us>
1052  */
1053
1054 #if ENABLE_FEATURE_EDITING_VI
1055 static void
1056 vi_Word_motion(char *command, int eat)
1057 {
1058         while (cursor < command_len && !isspace(command[cursor]))
1059                 input_forward();
1060         if (eat) while (cursor < command_len && isspace(command[cursor]))
1061                 input_forward();
1062 }
1063
1064 static void
1065 vi_word_motion(char *command, int eat)
1066 {
1067         if (isalnum(command[cursor]) || command[cursor] == '_') {
1068                 while (cursor < command_len
1069                  && (isalnum(command[cursor+1]) || command[cursor+1] == '_'))
1070                         input_forward();
1071         } else if (ispunct(command[cursor])) {
1072                 while (cursor < command_len && ispunct(command[cursor+1]))
1073                         input_forward();
1074         }
1075
1076         if (cursor < command_len)
1077                 input_forward();
1078
1079         if (eat && cursor < command_len && isspace(command[cursor]))
1080                 while (cursor < command_len && isspace(command[cursor]))
1081                         input_forward();
1082 }
1083
1084 static void
1085 vi_End_motion(char *command)
1086 {
1087         input_forward();
1088         while (cursor < command_len && isspace(command[cursor]))
1089                 input_forward();
1090         while (cursor < command_len-1 && !isspace(command[cursor+1]))
1091                 input_forward();
1092 }
1093
1094 static void
1095 vi_end_motion(char *command)
1096 {
1097         if (cursor >= command_len-1)
1098                 return;
1099         input_forward();
1100         while (cursor < command_len-1 && isspace(command[cursor]))
1101                 input_forward();
1102         if (cursor >= command_len-1)
1103                 return;
1104         if (isalnum(command[cursor]) || command[cursor] == '_') {
1105                 while (cursor < command_len-1
1106                  && (isalnum(command[cursor+1]) || command[cursor+1] == '_')
1107                 ) {
1108                         input_forward();
1109                 }
1110         } else if (ispunct(command[cursor])) {
1111                 while (cursor < command_len-1 && ispunct(command[cursor+1]))
1112                         input_forward();
1113         }
1114 }
1115
1116 static void
1117 vi_Back_motion(char *command)
1118 {
1119         while (cursor > 0 && isspace(command[cursor-1]))
1120                 input_backward(1);
1121         while (cursor > 0 && !isspace(command[cursor-1]))
1122                 input_backward(1);
1123 }
1124
1125 static void
1126 vi_back_motion(char *command)
1127 {
1128         if (cursor <= 0)
1129                 return;
1130         input_backward(1);
1131         while (cursor > 0 && isspace(command[cursor]))
1132                 input_backward(1);
1133         if (cursor <= 0)
1134                 return;
1135         if (isalnum(command[cursor]) || command[cursor] == '_') {
1136                 while (cursor > 0
1137                  && (isalnum(command[cursor-1]) || command[cursor-1] == '_')
1138                 ) {
1139                         input_backward(1);
1140                 }
1141         } else if (ispunct(command[cursor])) {
1142                 while (cursor > 0 && ispunct(command[cursor-1]))
1143                         input_backward(1);
1144         }
1145 }
1146 #endif
1147
1148
1149 /*
1150  * read_line_input and its helpers
1151  */
1152
1153 #if !ENABLE_FEATURE_EDITING_FANCY_PROMPT
1154 static void parse_and_put_prompt(const char *prmt_ptr)
1155 {
1156         cmdedit_prompt = prmt_ptr;
1157         cmdedit_prmt_len = strlen(prmt_ptr);
1158         put_prompt();
1159 }
1160 #else
1161 static void parse_and_put_prompt(const char *prmt_ptr)
1162 {
1163         int prmt_len = 0;
1164         size_t cur_prmt_len = 0;
1165         char flg_not_length = '[';
1166         char *prmt_mem_ptr = xzalloc(1);
1167         char *cwd_buf = xrealloc_getcwd_or_warn(NULL);
1168         char cbuf[2];
1169         char c;
1170         char *pbuf;
1171
1172         cmdedit_prmt_len = 0;
1173
1174         if (!cwd_buf) {
1175                 cwd_buf = (char *)bb_msg_unknown;
1176         }
1177
1178         cbuf[1] = '\0'; /* never changes */
1179
1180         while (*prmt_ptr) {
1181                 char *free_me = NULL;
1182
1183                 pbuf = cbuf;
1184                 c = *prmt_ptr++;
1185                 if (c == '\\') {
1186                         const char *cp = prmt_ptr;
1187                         int l;
1188
1189                         c = bb_process_escape_sequence(&prmt_ptr);
1190                         if (prmt_ptr == cp) {
1191                                 if (*cp == '\0')
1192                                         break;
1193                                 c = *prmt_ptr++;
1194
1195                                 switch (c) {
1196 #if ENABLE_FEATURE_GETUSERNAME_AND_HOMEDIR
1197                                 case 'u':
1198                                         pbuf = user_buf ? user_buf : (char*)"";
1199                                         break;
1200 #endif
1201                                 case 'h':
1202                                         pbuf = free_me = safe_gethostname();
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(NULL);
1404
1405                 if (nonblock_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 */