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