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