*: add optimization barrier to all "G trick" locations
[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         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 static int match_compare(const void *a, const void *b)
800 {
801         return strcmp(*(char**)a, *(char**)b);
802 }
803
804 /* Do TAB completion */
805 static void input_tab(smallint *lastWasTab)
806 {
807         if (!(state->flags & TAB_COMPLETION))
808                 return;
809
810         if (!*lastWasTab) {
811                 char *tmp, *tmp1;
812                 int len_found;
813 /*              char matchBuf[MAX_LINELEN]; */
814 #define matchBuf (S.input_tab__matchBuf)
815                 int find_type;
816                 int recalc_pos;
817
818                 *lastWasTab = TRUE;             /* flop trigger */
819
820                 /* Make a local copy of the string -- up
821                  * to the position of the cursor */
822                 tmp = strncpy(matchBuf, command_ps, cursor);
823                 tmp[cursor] = '\0';
824
825                 find_type = find_match(matchBuf, &recalc_pos);
826
827                 /* Free up any memory already allocated */
828                 free_tab_completion_data();
829
830 #if ENABLE_FEATURE_USERNAME_COMPLETION
831                 /* If the word starts with `~' and there is no slash in the word,
832                  * then try completing this word as a username. */
833                 if (state->flags & USERNAME_COMPLETION)
834                         if (matchBuf[0] == '~' && strchr(matchBuf, '/') == 0)
835                                 username_tab_completion(matchBuf, NULL);
836 #endif
837                 /* Try to match any executable in our path and everything
838                  * in the current working directory */
839                 if (!matches)
840                         exe_n_cwd_tab_completion(matchBuf, find_type);
841                 /* Sort, then remove any duplicates found */
842                 if (matches) {
843                         int i, n = 0;
844                         qsort(matches, num_matches, sizeof(char*), match_compare);
845                         for (i = 0; i < num_matches - 1; ++i) {
846                                 if (matches[i] && matches[i+1]) { /* paranoia */
847                                         if (strcmp(matches[i], matches[i+1]) == 0) {
848                                                 free(matches[i]);
849                                                 matches[i] = NULL; /* paranoia */
850                                         } else {
851                                                 matches[n++] = matches[i];
852                                         }
853                                 }
854                         }
855                         matches[n] = matches[i];
856                         num_matches = n + 1;
857                 }
858                 /* Did we find exactly one match? */
859                 if (!matches || num_matches > 1) {
860                         beep();
861                         if (!matches)
862                                 return;         /* not found */
863                         /* find minimal match */
864                         tmp1 = xstrdup(matches[0]);
865                         for (tmp = tmp1; *tmp; tmp++)
866                                 for (len_found = 1; len_found < num_matches; len_found++)
867                                         if (matches[len_found][(tmp - tmp1)] != *tmp) {
868                                                 *tmp = '\0';
869                                                 break;
870                                         }
871                         if (*tmp1 == '\0') {        /* have unique */
872                                 free(tmp1);
873                                 return;
874                         }
875                         tmp = add_quote_for_spec_chars(tmp1);
876                         free(tmp1);
877                 } else {                        /* one match */
878                         tmp = add_quote_for_spec_chars(matches[0]);
879                         /* for next completion current found */
880                         *lastWasTab = FALSE;
881
882                         len_found = strlen(tmp);
883                         if (tmp[len_found-1] != '/') {
884                                 tmp[len_found] = ' ';
885                                 tmp[len_found+1] = '\0';
886                         }
887                 }
888                 len_found = strlen(tmp);
889                 /* have space to placed match? */
890                 if ((len_found - strlen(matchBuf) + command_len) < MAX_LINELEN) {
891                         /* before word for match   */
892                         command_ps[cursor - recalc_pos] = '\0';
893                         /* save   tail line        */
894                         strcpy(matchBuf, command_ps + cursor);
895                         /* add    match            */
896                         strcat(command_ps, tmp);
897                         /* add    tail             */
898                         strcat(command_ps, matchBuf);
899                         /* back to begin word for match    */
900                         input_backward(recalc_pos);
901                         /* new pos                         */
902                         recalc_pos = cursor + len_found;
903                         /* new len                         */
904                         command_len = strlen(command_ps);
905                         /* write out the matched command   */
906                         redraw(cmdedit_y, command_len - recalc_pos);
907                 }
908                 free(tmp);
909 #undef matchBuf
910         } else {
911                 /* Ok -- the last char was a TAB.  Since they
912                  * just hit TAB again, print a list of all the
913                  * available choices... */
914                 if (matches && num_matches > 0) {
915                         int sav_cursor = cursor;        /* change goto_new_line() */
916
917                         /* Go to the next line */
918                         goto_new_line();
919                         showfiles();
920                         redraw(0, command_len - sav_cursor);
921                 }
922         }
923 }
924
925 #endif  /* FEATURE_COMMAND_TAB_COMPLETION */
926
927
928 #if MAX_HISTORY > 0
929
930 /* state->flags is already checked to be nonzero */
931 static void get_previous_history(void)
932 {
933         if (command_ps[0] != '\0' || state->history[state->cur_history] == NULL) {
934                 free(state->history[state->cur_history]);
935                 state->history[state->cur_history] = xstrdup(command_ps);
936         }
937         state->cur_history--;
938 }
939
940 static int get_next_history(void)
941 {
942         if (state->flags & DO_HISTORY) {
943                 int ch = state->cur_history;
944                 if (ch < state->cnt_history) {
945                         get_previous_history(); /* save the current history line */
946                         state->cur_history = ch + 1;
947                         return state->cur_history;
948                 }
949         }
950         beep();
951         return 0;
952 }
953
954 #if ENABLE_FEATURE_EDITING_SAVEHISTORY
955 /* state->flags is already checked to be nonzero */
956 static void load_history(const char *fromfile)
957 {
958         FILE *fp;
959         int hi;
960
961         /* cleanup old */
962         for (hi = state->cnt_history; hi > 0;) {
963                 hi--;
964                 free(state->history[hi]);
965         }
966
967         fp = fopen(fromfile, "r");
968         if (fp) {
969                 for (hi = 0; hi < MAX_HISTORY;) {
970                         char *hl = xmalloc_getline(fp);
971                         int l;
972
973                         if (!hl)
974                                 break;
975                         l = strlen(hl);
976                         if (l >= MAX_LINELEN)
977                                 hl[MAX_LINELEN-1] = '\0';
978                         if (l == 0 || hl[0] == ' ') {
979                                 free(hl);
980                                 continue;
981                         }
982                         state->history[hi++] = hl;
983                 }
984                 fclose(fp);
985         }
986         state->cur_history = state->cnt_history = hi;
987 }
988
989 /* state->flags is already checked to be nonzero */
990 static void save_history(const char *tofile)
991 {
992         FILE *fp;
993
994         fp = fopen(tofile, "w");
995         if (fp) {
996                 int i;
997
998                 for (i = 0; i < state->cnt_history; i++) {
999                         fprintf(fp, "%s\n", state->history[i]);
1000                 }
1001                 fclose(fp);
1002         }
1003 }
1004 #else
1005 #define load_history(a) ((void)0)
1006 #define save_history(a) ((void)0)
1007 #endif /* FEATURE_COMMAND_SAVEHISTORY */
1008
1009 static void remember_in_history(const char *str)
1010 {
1011         int i;
1012
1013         if (!(state->flags & DO_HISTORY))
1014                 return;
1015
1016         i = state->cnt_history;
1017         free(state->history[MAX_HISTORY]);
1018         state->history[MAX_HISTORY] = NULL;
1019         /* After max history, remove the oldest command */
1020         if (i >= MAX_HISTORY) {
1021                 free(state->history[0]);
1022                 for (i = 0; i < MAX_HISTORY-1; i++)
1023                         state->history[i] = state->history[i+1];
1024         }
1025 // Maybe "if (!i || strcmp(history[i-1], command) != 0) ..."
1026 // (i.e. do not save dups?)
1027         state->history[i++] = xstrdup(str);
1028         state->cur_history = i;
1029         state->cnt_history = i;
1030 #if ENABLE_FEATURE_EDITING_SAVEHISTORY
1031         if ((state->flags & SAVE_HISTORY) && state->hist_file)
1032                 save_history(state->hist_file);
1033 #endif
1034         USE_FEATURE_EDITING_FANCY_PROMPT(num_ok_lines++;)
1035 }
1036
1037 #else /* MAX_HISTORY == 0 */
1038 #define remember_in_history(a) ((void)0)
1039 #endif /* MAX_HISTORY */
1040
1041
1042 /*
1043  * This function is used to grab a character buffer
1044  * from the input file descriptor and allows you to
1045  * a string with full command editing (sort of like
1046  * a mini readline).
1047  *
1048  * The following standard commands are not implemented:
1049  * ESC-b -- Move back one word
1050  * ESC-f -- Move forward one word
1051  * ESC-d -- Delete back one word
1052  * ESC-h -- Delete forward one word
1053  * CTL-t -- Transpose two characters
1054  *
1055  * Minimalist vi-style command line editing available if configured.
1056  * vi mode implemented 2005 by Paul Fox <pgf@foxharp.boston.ma.us>
1057  */
1058
1059 #if ENABLE_FEATURE_EDITING_VI
1060 static void
1061 vi_Word_motion(char *command, int eat)
1062 {
1063         while (cursor < command_len && !isspace(command[cursor]))
1064                 input_forward();
1065         if (eat) while (cursor < command_len && isspace(command[cursor]))
1066                 input_forward();
1067 }
1068
1069 static void
1070 vi_word_motion(char *command, int eat)
1071 {
1072         if (isalnum(command[cursor]) || command[cursor] == '_') {
1073                 while (cursor < command_len
1074                  && (isalnum(command[cursor+1]) || command[cursor+1] == '_'))
1075                         input_forward();
1076         } else if (ispunct(command[cursor])) {
1077                 while (cursor < command_len && ispunct(command[cursor+1]))
1078                         input_forward();
1079         }
1080
1081         if (cursor < command_len)
1082                 input_forward();
1083
1084         if (eat && cursor < command_len && isspace(command[cursor]))
1085                 while (cursor < command_len && isspace(command[cursor]))
1086                         input_forward();
1087 }
1088
1089 static void
1090 vi_End_motion(char *command)
1091 {
1092         input_forward();
1093         while (cursor < command_len && isspace(command[cursor]))
1094                 input_forward();
1095         while (cursor < command_len-1 && !isspace(command[cursor+1]))
1096                 input_forward();
1097 }
1098
1099 static void
1100 vi_end_motion(char *command)
1101 {
1102         if (cursor >= command_len-1)
1103                 return;
1104         input_forward();
1105         while (cursor < command_len-1 && isspace(command[cursor]))
1106                 input_forward();
1107         if (cursor >= command_len-1)
1108                 return;
1109         if (isalnum(command[cursor]) || command[cursor] == '_') {
1110                 while (cursor < command_len-1
1111                  && (isalnum(command[cursor+1]) || command[cursor+1] == '_')
1112                 ) {
1113                         input_forward();
1114                 }
1115         } else if (ispunct(command[cursor])) {
1116                 while (cursor < command_len-1 && ispunct(command[cursor+1]))
1117                         input_forward();
1118         }
1119 }
1120
1121 static void
1122 vi_Back_motion(char *command)
1123 {
1124         while (cursor > 0 && isspace(command[cursor-1]))
1125                 input_backward(1);
1126         while (cursor > 0 && !isspace(command[cursor-1]))
1127                 input_backward(1);
1128 }
1129
1130 static void
1131 vi_back_motion(char *command)
1132 {
1133         if (cursor <= 0)
1134                 return;
1135         input_backward(1);
1136         while (cursor > 0 && isspace(command[cursor]))
1137                 input_backward(1);
1138         if (cursor <= 0)
1139                 return;
1140         if (isalnum(command[cursor]) || command[cursor] == '_') {
1141                 while (cursor > 0
1142                  && (isalnum(command[cursor-1]) || command[cursor-1] == '_')
1143                 ) {
1144                         input_backward(1);
1145                 }
1146         } else if (ispunct(command[cursor])) {
1147                 while (cursor > 0 && ispunct(command[cursor-1]))
1148                         input_backward(1);
1149         }
1150 }
1151 #endif
1152
1153
1154 /*
1155  * read_line_input and its helpers
1156  */
1157
1158 #if !ENABLE_FEATURE_EDITING_FANCY_PROMPT
1159 static void parse_and_put_prompt(const char *prmt_ptr)
1160 {
1161         cmdedit_prompt = prmt_ptr;
1162         cmdedit_prmt_len = strlen(prmt_ptr);
1163         put_prompt();
1164 }
1165 #else
1166 static void parse_and_put_prompt(const char *prmt_ptr)
1167 {
1168         int prmt_len = 0;
1169         size_t cur_prmt_len = 0;
1170         char flg_not_length = '[';
1171         char *prmt_mem_ptr = xzalloc(1);
1172         char *cwd_buf = xrealloc_getcwd_or_warn(NULL);
1173         char cbuf[2];
1174         char c;
1175         char *pbuf;
1176
1177         cmdedit_prmt_len = 0;
1178
1179         if (!cwd_buf) {
1180                 cwd_buf = (char *)bb_msg_unknown;
1181         }
1182
1183         cbuf[1] = '\0'; /* never changes */
1184
1185         while (*prmt_ptr) {
1186                 char *free_me = NULL;
1187
1188                 pbuf = cbuf;
1189                 c = *prmt_ptr++;
1190                 if (c == '\\') {
1191                         const char *cp = prmt_ptr;
1192                         int l;
1193
1194                         c = bb_process_escape_sequence(&prmt_ptr);
1195                         if (prmt_ptr == cp) {
1196                                 if (*cp == '\0')
1197                                         break;
1198                                 c = *prmt_ptr++;
1199
1200                                 switch (c) {
1201 #if ENABLE_FEATURE_GETUSERNAME_AND_HOMEDIR
1202                                 case 'u':
1203                                         pbuf = user_buf ? user_buf : (char*)"";
1204                                         break;
1205 #endif
1206                                 case 'h':
1207                                         pbuf = free_me = safe_gethostname();
1208                                         *strchrnul(pbuf, '.') = '\0';
1209                                         break;
1210                                 case '$':
1211                                         c = (geteuid() == 0 ? '#' : '$');
1212                                         break;
1213 #if ENABLE_FEATURE_GETUSERNAME_AND_HOMEDIR
1214                                 case 'w':
1215                                         /* /home/user[/something] -> ~[/something] */
1216                                         pbuf = cwd_buf;
1217                                         l = strlen(home_pwd_buf);
1218                                         if (l != 0
1219                                          && strncmp(home_pwd_buf, cwd_buf, l) == 0
1220                                          && (cwd_buf[l]=='/' || cwd_buf[l]=='\0')
1221                                          && strlen(cwd_buf + l) < PATH_MAX
1222                                         ) {
1223                                                 pbuf = free_me = xasprintf("~%s", cwd_buf + l);
1224                                         }
1225                                         break;
1226 #endif
1227                                 case 'W':
1228                                         pbuf = cwd_buf;
1229                                         cp = strrchr(pbuf, '/');
1230                                         if (cp != NULL && cp != pbuf)
1231                                                 pbuf += (cp-pbuf) + 1;
1232                                         break;
1233                                 case '!':
1234                                         pbuf = free_me = xasprintf("%d", num_ok_lines);
1235                                         break;
1236                                 case 'e': case 'E':     /* \e \E = \033 */
1237                                         c = '\033';
1238                                         break;
1239                                 case 'x': case 'X': {
1240                                         char buf2[4];
1241                                         for (l = 0; l < 3;) {
1242                                                 unsigned h;
1243                                                 buf2[l++] = *prmt_ptr;
1244                                                 buf2[l] = '\0';
1245                                                 h = strtoul(buf2, &pbuf, 16);
1246                                                 if (h > UCHAR_MAX || (pbuf - buf2) < l) {
1247                                                         buf2[--l] = '\0';
1248                                                         break;
1249                                                 }
1250                                                 prmt_ptr++;
1251                                         }
1252                                         c = (char)strtoul(buf2, NULL, 16);
1253                                         if (c == 0)
1254                                                 c = '?';
1255                                         pbuf = cbuf;
1256                                         break;
1257                                 }
1258                                 case '[': case ']':
1259                                         if (c == flg_not_length) {
1260                                                 flg_not_length = (flg_not_length == '[' ? ']' : '[');
1261                                                 continue;
1262                                         }
1263                                         break;
1264                                 } /* switch */
1265                         } /* if */
1266                 } /* if */
1267                 cbuf[0] = c;
1268                 cur_prmt_len = strlen(pbuf);
1269                 prmt_len += cur_prmt_len;
1270                 if (flg_not_length != ']')
1271                         cmdedit_prmt_len += cur_prmt_len;
1272                 prmt_mem_ptr = strcat(xrealloc(prmt_mem_ptr, prmt_len+1), pbuf);
1273                 free(free_me);
1274         } /* while */
1275
1276         if (cwd_buf != (char *)bb_msg_unknown)
1277                 free(cwd_buf);
1278         cmdedit_prompt = prmt_mem_ptr;
1279         put_prompt();
1280 }
1281 #endif
1282
1283 static void cmdedit_setwidth(unsigned w, int redraw_flg)
1284 {
1285         cmdedit_termw = w;
1286         if (redraw_flg) {
1287                 /* new y for current cursor */
1288                 int new_y = (cursor + cmdedit_prmt_len) / w;
1289                 /* redraw */
1290                 redraw((new_y >= cmdedit_y ? new_y : cmdedit_y), command_len - cursor);
1291                 fflush(stdout);
1292         }
1293 }
1294
1295 static void win_changed(int nsig)
1296 {
1297         int width;
1298         get_terminal_width_height(0, &width, NULL);
1299         cmdedit_setwidth(width, nsig /* - just a yes/no flag */);
1300         if (nsig == SIGWINCH)
1301                 signal(SIGWINCH, win_changed); /* rearm ourself */
1302 }
1303
1304 /*
1305  * The emacs and vi modes share much of the code in the big
1306  * command loop.  Commands entered when in vi's command mode (aka
1307  * "escape mode") get an extra bit added to distinguish them --
1308  * this keeps them from being self-inserted.  This clutters the
1309  * big switch a bit, but keeps all the code in one place.
1310  */
1311
1312 #define vbit 0x100
1313
1314 /* leave out the "vi-mode"-only case labels if vi editing isn't
1315  * configured. */
1316 #define vi_case(caselabel) USE_FEATURE_EDITING(case caselabel)
1317
1318 /* convert uppercase ascii to equivalent control char, for readability */
1319 #undef CTRL
1320 #define CTRL(a) ((a) & ~0x40)
1321
1322 /* Returns:
1323  * -1 on read errors or EOF, or on bare Ctrl-D,
1324  * 0  on ctrl-C (the line entered is still returned in 'command'),
1325  * >0 length of input string, including terminating '\n'
1326  */
1327 int read_line_input(const char *prompt, char *command, int maxsize, line_input_t *st)
1328 {
1329 #if ENABLE_FEATURE_TAB_COMPLETION
1330         smallint lastWasTab = FALSE;
1331 #endif
1332         unsigned int ic;
1333         unsigned char c;
1334         smallint break_out = 0;
1335 #if ENABLE_FEATURE_EDITING_VI
1336         smallint vi_cmdmode = 0;
1337         smalluint prevc;
1338 #endif
1339         struct termios initial_settings;
1340         struct termios new_settings;
1341
1342         INIT_S();
1343
1344         if (tcgetattr(STDIN_FILENO, &initial_settings) < 0
1345          || !(initial_settings.c_lflag & ECHO)
1346         ) {
1347                 /* Happens when e.g. stty -echo was run before */
1348                 int len;
1349                 parse_and_put_prompt(prompt);
1350                 fflush(stdout);
1351                 if (fgets(command, maxsize, stdin) == NULL)
1352                         len = -1; /* EOF or error */
1353                 else
1354                         len = strlen(command);
1355                 DEINIT_S();
1356                 return len;
1357         }
1358
1359 // FIXME: audit & improve this
1360         if (maxsize > MAX_LINELEN)
1361                 maxsize = MAX_LINELEN;
1362
1363         /* With null flags, no other fields are ever used */
1364         state = st ? st : (line_input_t*) &const_int_0;
1365 #if ENABLE_FEATURE_EDITING_SAVEHISTORY
1366         if ((state->flags & SAVE_HISTORY) && state->hist_file)
1367                 load_history(state->hist_file);
1368 #endif
1369
1370         /* prepare before init handlers */
1371         cmdedit_y = 0;  /* quasireal y, not true if line > xt*yt */
1372         command_len = 0;
1373         command_ps = command;
1374         command[0] = '\0';
1375
1376         new_settings = initial_settings;
1377         new_settings.c_lflag &= ~ICANON;        /* unbuffered input */
1378         /* Turn off echoing and CTRL-C, so we can trap it */
1379         new_settings.c_lflag &= ~(ECHO | ECHONL | ISIG);
1380         /* Hmm, in linux c_cc[] is not parsed if ICANON is off */
1381         new_settings.c_cc[VMIN] = 1;
1382         new_settings.c_cc[VTIME] = 0;
1383         /* Turn off CTRL-C, so we can trap it */
1384 #ifndef _POSIX_VDISABLE
1385 #define _POSIX_VDISABLE '\0'
1386 #endif
1387         new_settings.c_cc[VINTR] = _POSIX_VDISABLE;
1388         tcsetattr(STDIN_FILENO, TCSANOW, &new_settings);
1389
1390         /* Now initialize things */
1391         previous_SIGWINCH_handler = signal(SIGWINCH, win_changed);
1392         win_changed(0); /* do initial resizing */
1393 #if ENABLE_FEATURE_GETUSERNAME_AND_HOMEDIR
1394         {
1395                 struct passwd *entry;
1396
1397                 entry = getpwuid(geteuid());
1398                 if (entry) {
1399                         user_buf = xstrdup(entry->pw_name);
1400                         home_pwd_buf = xstrdup(entry->pw_dir);
1401                 }
1402         }
1403 #endif
1404         /* Print out the command prompt */
1405         parse_and_put_prompt(prompt);
1406
1407         while (1) {
1408                 fflush(NULL);
1409
1410                 if (nonblock_safe_read(STDIN_FILENO, &c, 1) < 1) {
1411                         /* if we can't read input then exit */
1412                         goto prepare_to_die;
1413                 }
1414
1415                 ic = c;
1416
1417 #if ENABLE_FEATURE_EDITING_VI
1418                 newdelflag = 1;
1419                 if (vi_cmdmode)
1420                         ic |= vbit;
1421 #endif
1422                 switch (ic) {
1423                 case '\n':
1424                 case '\r':
1425                 vi_case('\n'|vbit:)
1426                 vi_case('\r'|vbit:)
1427                         /* Enter */
1428                         goto_new_line();
1429                         break_out = 1;
1430                         break;
1431                 case CTRL('A'):
1432                 vi_case('0'|vbit:)
1433                         /* Control-a -- Beginning of line */
1434                         input_backward(cursor);
1435                         break;
1436                 case CTRL('B'):
1437                 vi_case('h'|vbit:)
1438                 vi_case('\b'|vbit:)
1439                 vi_case('\x7f'|vbit:) /* DEL */
1440                         /* Control-b -- Move back one character */
1441                         input_backward(1);
1442                         break;
1443                 case CTRL('C'):
1444                 vi_case(CTRL('C')|vbit:)
1445                         /* Control-c -- stop gathering input */
1446                         goto_new_line();
1447                         command_len = 0;
1448                         break_out = -1; /* "do not append '\n'" */
1449                         break;
1450                 case CTRL('D'):
1451                         /* Control-d -- Delete one character, or exit
1452                          * if the len=0 and no chars to delete */
1453                         if (command_len == 0) {
1454                                 errno = 0;
1455  prepare_to_die:
1456                                 /* to control stopped jobs */
1457                                 break_out = command_len = -1;
1458                                 break;
1459                         }
1460                         input_delete(0);
1461                         break;
1462
1463                 case CTRL('E'):
1464                 vi_case('$'|vbit:)
1465                         /* Control-e -- End of line */
1466                         input_end();
1467                         break;
1468                 case CTRL('F'):
1469                 vi_case('l'|vbit:)
1470                 vi_case(' '|vbit:)
1471                         /* Control-f -- Move forward one character */
1472                         input_forward();
1473                         break;
1474
1475                 case '\b':
1476                 case '\x7f': /* DEL */
1477                         /* Control-h and DEL */
1478                         input_backspace();
1479                         break;
1480
1481 #if ENABLE_FEATURE_TAB_COMPLETION
1482                 case '\t':
1483                         input_tab(&lastWasTab);
1484                         break;
1485 #endif
1486
1487                 case CTRL('K'):
1488                         /* Control-k -- clear to end of line */
1489                         command[cursor] = 0;
1490                         command_len = cursor;
1491                         printf("\033[J");
1492                         break;
1493                 case CTRL('L'):
1494                 vi_case(CTRL('L')|vbit:)
1495                         /* Control-l -- clear screen */
1496                         printf("\033[H");
1497                         redraw(0, command_len - cursor);
1498                         break;
1499
1500 #if MAX_HISTORY > 0
1501                 case CTRL('N'):
1502                 vi_case(CTRL('N')|vbit:)
1503                 vi_case('j'|vbit:)
1504                         /* Control-n -- Get next command in history */
1505                         if (get_next_history())
1506                                 goto rewrite_line;
1507                         break;
1508                 case CTRL('P'):
1509                 vi_case(CTRL('P')|vbit:)
1510                 vi_case('k'|vbit:)
1511                         /* Control-p -- Get previous command from history */
1512                         if ((state->flags & DO_HISTORY) && state->cur_history > 0) {
1513                                 get_previous_history();
1514                                 goto rewrite_line;
1515                         }
1516                         beep();
1517                         break;
1518 #endif
1519
1520                 case CTRL('U'):
1521                 vi_case(CTRL('U')|vbit:)
1522                         /* Control-U -- Clear line before cursor */
1523                         if (cursor) {
1524                                 strcpy(command, command + cursor);
1525                                 command_len -= cursor;
1526                                 redraw(cmdedit_y, command_len);
1527                         }
1528                         break;
1529                 case CTRL('W'):
1530                 vi_case(CTRL('W')|vbit:)
1531                         /* Control-W -- Remove the last word */
1532                         while (cursor > 0 && isspace(command[cursor-1]))
1533                                 input_backspace();
1534                         while (cursor > 0 && !isspace(command[cursor-1]))
1535                                 input_backspace();
1536                         break;
1537
1538 #if ENABLE_FEATURE_EDITING_VI
1539                 case 'i'|vbit:
1540                         vi_cmdmode = 0;
1541                         break;
1542                 case 'I'|vbit:
1543                         input_backward(cursor);
1544                         vi_cmdmode = 0;
1545                         break;
1546                 case 'a'|vbit:
1547                         input_forward();
1548                         vi_cmdmode = 0;
1549                         break;
1550                 case 'A'|vbit:
1551                         input_end();
1552                         vi_cmdmode = 0;
1553                         break;
1554                 case 'x'|vbit:
1555                         input_delete(1);
1556                         break;
1557                 case 'X'|vbit:
1558                         if (cursor > 0) {
1559                                 input_backward(1);
1560                                 input_delete(1);
1561                         }
1562                         break;
1563                 case 'W'|vbit:
1564                         vi_Word_motion(command, 1);
1565                         break;
1566                 case 'w'|vbit:
1567                         vi_word_motion(command, 1);
1568                         break;
1569                 case 'E'|vbit:
1570                         vi_End_motion(command);
1571                         break;
1572                 case 'e'|vbit:
1573                         vi_end_motion(command);
1574                         break;
1575                 case 'B'|vbit:
1576                         vi_Back_motion(command);
1577                         break;
1578                 case 'b'|vbit:
1579                         vi_back_motion(command);
1580                         break;
1581                 case 'C'|vbit:
1582                         vi_cmdmode = 0;
1583                         /* fall through */
1584                 case 'D'|vbit:
1585                         goto clear_to_eol;
1586
1587                 case 'c'|vbit:
1588                         vi_cmdmode = 0;
1589                         /* fall through */
1590                 case 'd'|vbit: {
1591                         int nc, sc;
1592                         sc = cursor;
1593                         prevc = ic;
1594                         if (safe_read(STDIN_FILENO, &c, 1) < 1)
1595                                 goto prepare_to_die;
1596                         if (c == (prevc & 0xff)) {
1597                                 /* "cc", "dd" */
1598                                 input_backward(cursor);
1599                                 goto clear_to_eol;
1600                                 break;
1601                         }
1602                         switch (c) {
1603                         case 'w':
1604                         case 'W':
1605                         case 'e':
1606                         case 'E':
1607                                 switch (c) {
1608                                 case 'w':   /* "dw", "cw" */
1609                                         vi_word_motion(command, vi_cmdmode);
1610                                         break;
1611                                 case 'W':   /* 'dW', 'cW' */
1612                                         vi_Word_motion(command, vi_cmdmode);
1613                                         break;
1614                                 case 'e':   /* 'de', 'ce' */
1615                                         vi_end_motion(command);
1616                                         input_forward();
1617                                         break;
1618                                 case 'E':   /* 'dE', 'cE' */
1619                                         vi_End_motion(command);
1620                                         input_forward();
1621                                         break;
1622                                 }
1623                                 nc = cursor;
1624                                 input_backward(cursor - sc);
1625                                 while (nc-- > cursor)
1626                                         input_delete(1);
1627                                 break;
1628                         case 'b':  /* "db", "cb" */
1629                         case 'B':  /* implemented as B */
1630                                 if (c == 'b')
1631                                         vi_back_motion(command);
1632                                 else
1633                                         vi_Back_motion(command);
1634                                 while (sc-- > cursor)
1635                                         input_delete(1);
1636                                 break;
1637                         case ' ':  /* "d ", "c " */
1638                                 input_delete(1);
1639                                 break;
1640                         case '$':  /* "d$", "c$" */
1641                         clear_to_eol:
1642                                 while (cursor < command_len)
1643                                         input_delete(1);
1644                                 break;
1645                         }
1646                         break;
1647                 }
1648                 case 'p'|vbit:
1649                         input_forward();
1650                         /* fallthrough */
1651                 case 'P'|vbit:
1652                         put();
1653                         break;
1654                 case 'r'|vbit:
1655                         if (safe_read(STDIN_FILENO, &c, 1) < 1)
1656                                 goto prepare_to_die;
1657                         if (c == 0)
1658                                 beep();
1659                         else {
1660                                 *(command + cursor) = c;
1661                                 bb_putchar(c);
1662                                 bb_putchar('\b');
1663                         }
1664                         break;
1665 #endif /* FEATURE_COMMAND_EDITING_VI */
1666
1667                 case '\x1b': /* ESC */
1668
1669 #if ENABLE_FEATURE_EDITING_VI
1670                         if (state->flags & VI_MODE) {
1671                                 /* ESC: insert mode --> command mode */
1672                                 vi_cmdmode = 1;
1673                                 input_backward(1);
1674                                 break;
1675                         }
1676 #endif
1677                         /* escape sequence follows */
1678                         if (safe_read(STDIN_FILENO, &c, 1) < 1)
1679                                 goto prepare_to_die;
1680                         /* different vt100 emulations */
1681                         if (c == '[' || c == 'O') {
1682                 vi_case('['|vbit:)
1683                 vi_case('O'|vbit:)
1684                                 if (safe_read(STDIN_FILENO, &c, 1) < 1)
1685                                         goto prepare_to_die;
1686                         }
1687                         if (c >= '1' && c <= '9') {
1688                                 unsigned char dummy;
1689
1690                                 if (safe_read(STDIN_FILENO, &dummy, 1) < 1)
1691                                         goto prepare_to_die;
1692                                 if (dummy != '~')
1693                                         c = '\0';
1694                         }
1695
1696                         switch (c) {
1697 #if ENABLE_FEATURE_TAB_COMPLETION
1698                         case '\t':                      /* Alt-Tab */
1699                                 input_tab(&lastWasTab);
1700                                 break;
1701 #endif
1702 #if MAX_HISTORY > 0
1703                         case 'A':
1704                                 /* Up Arrow -- Get previous command from history */
1705                                 if ((state->flags & DO_HISTORY) && state->cur_history > 0) {
1706                                         get_previous_history();
1707                                         goto rewrite_line;
1708                                 }
1709                                 beep();
1710                                 break;
1711                         case 'B':
1712                                 /* Down Arrow -- Get next command in history */
1713                                 if (!get_next_history())
1714                                         break;
1715  rewrite_line:
1716                                 /* Rewrite the line with the selected history item */
1717                                 /* change command */
1718                                 command_len = strlen(strcpy(command, state->history[state->cur_history]));
1719                                 /* redraw and go to eol (bol, in vi */
1720                                 redraw(cmdedit_y, (state->flags & VI_MODE) ? 9999 : 0);
1721                                 break;
1722 #endif
1723                         case 'C':
1724                                 /* Right Arrow -- Move forward one character */
1725                                 input_forward();
1726                                 break;
1727                         case 'D':
1728                                 /* Left Arrow -- Move back one character */
1729                                 input_backward(1);
1730                                 break;
1731                         case '3':
1732                                 /* Delete */
1733                                 input_delete(0);
1734                                 break;
1735                         case '1': // vt100? linux vt? or what?
1736                         case '7': // vt100? linux vt? or what?
1737                         case 'H': /* xterm's <Home> */
1738                                 input_backward(cursor);
1739                                 break;
1740                         case '4': // vt100? linux vt? or what?
1741                         case '8': // vt100? linux vt? or what?
1742                         case 'F': /* xterm's <End> */
1743                                 input_end();
1744                                 break;
1745                         default:
1746                                 c = '\0';
1747                                 beep();
1748                         }
1749                         break;
1750
1751                 default:        /* If it's regular input, do the normal thing */
1752
1753                         /* Control-V -- force insert of next char */
1754                         if (c == CTRL('V')) {
1755                                 if (safe_read(STDIN_FILENO, &c, 1) < 1)
1756                                         goto prepare_to_die;
1757                                 if (c == 0) {
1758                                         beep();
1759                                         break;
1760                                 }
1761                         }
1762
1763 #if ENABLE_FEATURE_EDITING_VI
1764                         if (vi_cmdmode)  /* Don't self-insert */
1765                                 break;
1766 #endif
1767                         if (command_len >= (maxsize - 2))        /* Need to leave space for enter */
1768                                 break;
1769
1770                         command_len++;
1771                         if (cursor == (command_len - 1)) {      /* Append if at the end of the line */
1772                                 command[cursor] = c;
1773                                 command[cursor+1] = '\0';
1774                                 cmdedit_set_out_char(' ');
1775                         } else {                        /* Insert otherwise */
1776                                 int sc = cursor;
1777
1778                                 memmove(command + sc + 1, command + sc, command_len - sc);
1779                                 command[sc] = c;
1780                                 sc++;
1781                                 /* rewrite from cursor */
1782                                 input_end();
1783                                 /* to prev x pos + 1 */
1784                                 input_backward(cursor - sc);
1785                         }
1786                         break;
1787                 }
1788                 if (break_out)                  /* Enter is the command terminator, no more input. */
1789                         break;
1790
1791 #if ENABLE_FEATURE_TAB_COMPLETION
1792                 if (c != '\t')
1793                         lastWasTab = FALSE;
1794 #endif
1795         }
1796
1797         if (command_len > 0)
1798                 remember_in_history(command);
1799
1800         if (break_out > 0) {
1801                 command[command_len++] = '\n';
1802                 command[command_len] = '\0';
1803         }
1804
1805 #if ENABLE_FEATURE_TAB_COMPLETION
1806         free_tab_completion_data();
1807 #endif
1808
1809         /* restore initial_settings */
1810         tcsetattr(STDIN_FILENO, TCSANOW, &initial_settings);
1811         /* restore SIGWINCH handler */
1812         signal(SIGWINCH, previous_SIGWINCH_handler);
1813         fflush(stdout);
1814
1815         DEINIT_S();
1816
1817         return command_len;
1818 }
1819
1820 line_input_t *new_line_input_t(int flags)
1821 {
1822         line_input_t *n = xzalloc(sizeof(*n));
1823         n->flags = flags;
1824         return n;
1825 }
1826
1827 #else
1828
1829 #undef read_line_input
1830 int read_line_input(const char* prompt, char* command, int maxsize)
1831 {
1832         fputs(prompt, stdout);
1833         fflush(stdout);
1834         fgets(command, maxsize, stdin);
1835         return strlen(command);
1836 }
1837
1838 #endif  /* FEATURE_COMMAND_EDITING */
1839
1840
1841 /*
1842  * Testing
1843  */
1844
1845 #ifdef TEST
1846
1847 #include <locale.h>
1848
1849 const char *applet_name = "debug stuff usage";
1850
1851 int main(int argc, char **argv)
1852 {
1853         char buff[MAX_LINELEN];
1854         char *prompt =
1855 #if ENABLE_FEATURE_EDITING_FANCY_PROMPT
1856                 "\\[\\033[32;1m\\]\\u@\\[\\x1b[33;1m\\]\\h:"
1857                 "\\[\\033[34;1m\\]\\w\\[\\033[35;1m\\] "
1858                 "\\!\\[\\e[36;1m\\]\\$ \\[\\E[0m\\]";
1859 #else
1860                 "% ";
1861 #endif
1862
1863 #if ENABLE_FEATURE_NONPRINTABLE_INVERSE_PUT
1864         setlocale(LC_ALL, "");
1865 #endif
1866         while (1) {
1867                 int l;
1868                 l = read_line_input(prompt, buff);
1869                 if (l <= 0 || buff[l-1] != '\n')
1870                         break;
1871                 buff[l-1] = 0;
1872                 printf("*** read_line_input() returned line =%s=\n", buff);
1873         }
1874         printf("*** read_line_input() detect ^D\n");
1875         return 0;
1876 }
1877
1878 #endif  /* TEST */