0c9bda760375ad35ab86ea60bf1ddedf86443434
[oweals/busybox.git] / cmdedit.c
1 /* vi: set sw=4 ts=4: */
2 /*
3  * Termios command line History and Editting, originally 
4  * intended for NetBSD sh (ash)
5  * Copyright (c) 1999
6  *      Main code:            Adam Rogoyski <rogoyski@cs.utexas.edu> 
7  *      Etc:                  Dave Cinege <dcinege@psychosis.com>
8  *  Majorly adjusted/re-written for busybox:
9  *                            Erik Andersen <andersee@debian.org>
10  *
11  * You may use this code as you wish, so long as the original author(s)
12  * are attributed in any redistributions of the source code.
13  * This code is 'as is' with no warranty.
14  * This code may safely be consumed by a BSD or GPL license.
15  *
16  * v 0.5  19990328      Initial release 
17  *
18  * Future plans: Simple file and path name completion. (like BASH)
19  *
20  */
21
22 /*
23    Usage and Known bugs:
24    Terminal key codes are not extensive, and more will probably
25    need to be added. This version was created on Debian GNU/Linux 2.x.
26    Delete, Backspace, Home, End, and the arrow keys were tested
27    to work in an Xterm and console. Ctrl-A also works as Home.
28    Ctrl-E also works as End. The binary size increase is <3K.
29
30    Editting will not display correctly for lines greater then the 
31    terminal width. (more then one line.) However, history will.
32  */
33
34 #include "busybox.h"
35 #ifdef BB_FEATURE_SH_COMMAND_EDITING
36
37 #include <stdio.h>
38 #include <errno.h>
39 #include <unistd.h>
40 #include <stdlib.h>
41 #include <string.h>
42 #include <sys/ioctl.h>
43 #include <ctype.h>
44 #include <signal.h>
45
46
47 #define  MAX_HISTORY   15               /* Maximum length of the linked list for the command line history */
48
49 #define ESC     27
50 #define DEL     127
51 #define member(c, s) ((c) ? ((char *)strchr ((s), (c)) != (char *)NULL) : 0)
52 #define whitespace(c) (((c) == ' ') || ((c) == '\t'))
53
54 static struct history *his_front = NULL;        /* First element in command line list */
55 static struct history *his_end = NULL;  /* Last element in command line list */
56
57 /* ED: sparc termios is broken: revert back to old termio handling. */
58 #ifdef BB_FEATURE_USE_TERMIOS
59
60 #if #cpu(sparc)
61 #      include <termio.h>
62 #      define termios termio
63 #      define setTermSettings(fd,argp) ioctl(fd,TCSETAF,argp)
64 #      define getTermSettings(fd,argp) ioctl(fd,TCGETA,argp)
65 #else
66 #      include <termios.h>
67 #      define setTermSettings(fd,argp) tcsetattr(fd,TCSANOW,argp)
68 #      define getTermSettings(fd,argp) tcgetattr(fd, argp);
69 #endif
70
71 /* Current termio and the previous termio before starting sh */
72 static struct termios initial_settings, new_settings;
73
74
75 #ifndef _POSIX_VDISABLE
76 #define _POSIX_VDISABLE '\0'
77 #endif
78
79 #endif
80
81
82
83 static int cmdedit_termw = 80;  /* actual terminal width */
84 static int cmdedit_scroll = 27; /* width of EOL scrolling region */
85 static int history_counter = 0; /* Number of commands in history list */
86 static int reset_term = 0;              /* Set to true if the terminal needs to be reset upon exit */
87 static int exithandler_set = 0; /* Set to true when atexit() has been called */
88         
89
90 /* Link into lash to reset context to 0
91  * on ^C and such */
92 extern unsigned int shell_context;
93
94
95 struct history {
96         char *s;
97         struct history *p;
98         struct history *n;
99 };
100
101 #define xwrite write
102
103 /*
104  * TODO: Someday we want to implement 'horizontal scrolling' of the
105  * command-line when the user has typed more than the current width. This
106  * would allow the user to see a 'window' of what he has typed.
107  */
108 void
109 cmdedit_setwidth(int w)
110 {
111         if (w > 20) {
112                 cmdedit_termw = w;
113                 cmdedit_scroll = w / 3;
114         } else {
115                 error_msg("\n*** Error: minimum screen width is 21\n");
116         }
117 }
118
119
120 void cmdedit_reset_term(void)
121 {
122         if (reset_term)
123                 /* sparc and other have broken termios support: use old termio handling. */
124                 setTermSettings(fileno(stdin), (void*) &initial_settings);
125 #ifdef BB_FEATURE_CLEAN_UP
126         if (his_front) {
127                 struct history *n;
128                 //while(his_front!=his_end) {
129                 while(his_front!=his_end) {
130                         n = his_front->n;
131                         free(his_front->s);
132                         free(his_front);
133                         his_front=n;
134                 }
135         }
136 #endif
137 }
138
139 void clean_up_and_die(int sig)
140 {
141         cmdedit_reset_term();
142         fprintf(stdout, "\n");
143         if (sig!=SIGINT)
144                 exit(EXIT_SUCCESS);
145 }
146
147 /* Go to HOME position */
148 void input_home(int outputFd, int *cursor)
149 {
150         while (*cursor > 0) {
151                 xwrite(outputFd, "\b", 1);
152                 --*cursor;
153         }
154 }
155
156 /* Go to END position */
157 void input_end(int outputFd, int *cursor, int len)
158 {
159         while (*cursor < len) {
160                 xwrite(outputFd, "\033[C", 3);
161                 ++*cursor;
162         }
163 }
164
165 /* Delete the char in back of the cursor */
166 void input_backspace(char* command, int outputFd, int *cursor, int *len)
167 {
168         int j = 0;
169
170 /* Debug crap */
171 //fprintf(stderr, "\nerik: len=%d, cursor=%d, strlen(command)='%d'\n", *len, *cursor, strlen(command));
172 //xwrite(outputFd, command, *len);
173 //*cursor = *len;
174
175
176         if (*cursor > 0) {
177                 xwrite(outputFd, "\b \b", 3);
178                 --*cursor;
179                 memmove(command + *cursor, command + *cursor + 1,
180                                 BUFSIZ - *cursor + 1);
181
182                 for (j = *cursor; j < (BUFSIZ - 1); j++) {
183                         if (!*(command + j))
184                                 break;
185                         else
186                                 xwrite(outputFd, (command + j), 1);
187                 }
188
189                 xwrite(outputFd, " \b", 2);
190
191                 while (j-- > *cursor)
192                         xwrite(outputFd, "\b", 1);
193
194                 --*len;
195         }
196 }
197
198 /* Delete the char in front of the cursor */
199 void input_delete(char* command, int outputFd, int cursor, int *len)
200 {
201         int j = 0;
202
203         if (cursor == *len)
204                 return;
205         
206         memmove(command + cursor, command + cursor + 1,
207                         BUFSIZ - cursor - 1);
208         for (j = cursor; j < (BUFSIZ - 1); j++) {
209                 if (!*(command + j))
210                         break;
211                 else
212                         xwrite(outputFd, (command + j), 1);
213         }
214
215         xwrite(outputFd, " \b", 2);
216
217         while (j-- > cursor)
218                 xwrite(outputFd, "\b", 1);
219         --*len;
220 }
221
222 /* Move forward one charactor */
223 void input_forward(int outputFd, int *cursor, int len)
224 {
225         if (*cursor < len) {
226                 xwrite(outputFd, "\033[C", 3);
227                 ++*cursor;
228         }
229 }
230
231 /* Move back one charactor */
232 void input_backward(int outputFd, int *cursor)
233 {
234         if (*cursor > 0) {
235                 xwrite(outputFd, "\033[D", 3);
236                 --*cursor;
237         }
238 }
239
240
241
242 #ifdef BB_FEATURE_SH_TAB_COMPLETION
243 char** username_tab_completion(char* command, int *num_matches)
244 {
245         char **matches = (char **) NULL;
246         *num_matches=0;
247         fprintf(stderr, "\nin username_tab_completion\n");
248         return (matches);
249 }
250
251 #include <dirent.h>
252 char** exe_n_cwd_tab_completion(char* command, int *num_matches)
253 {
254         char *dirName;
255         char **matches;
256         DIR *dir;
257         struct dirent *next;
258                         
259         matches = xmalloc( sizeof(char*)*50);
260
261         /* Stick a wildcard onto the command, for later use */
262         strcat( command, "*");
263
264         /* Now wall the current directory */
265         dirName = get_current_dir_name();
266         dir = opendir(dirName);
267         if (!dir) {
268                 /* Don't print an error, just shut up and return */
269                 *num_matches=0;
270                 return (matches);
271         }
272         while ((next = readdir(dir)) != NULL) {
273
274                 /* Some quick sanity checks */
275                 if ((strcmp(next->d_name, "..") == 0)
276                         || (strcmp(next->d_name, ".") == 0)) {
277                         continue;
278                 } 
279                 /* See if this matches */
280                 if (check_wildcard_match(next->d_name, command) == TRUE) {
281                         /* Cool, found a match.  Add it to the list */
282                         matches[*num_matches] = xmalloc(strlen(next->d_name)+1);
283                         strcpy( matches[*num_matches], next->d_name);
284                         ++*num_matches;
285                         //matches = realloc( matches, sizeof(char*)*(*num_matches));
286                 }
287         }
288
289         return (matches);
290 }
291
292 void input_tab(char* command, char* prompt, int outputFd, int *cursor, int *len, int lastWasTab)
293 {
294         /* Do TAB completion */
295         static int num_matches=0;
296         static char **matches = (char **) NULL;
297         int pos = *cursor;
298
299
300         if (lastWasTab == FALSE) {
301                 char *tmp, *tmp1, *matchBuf;
302
303                 /* For now, we will not bother with trying to distinguish
304                  * whether the cursor is in/at a command extression -- we
305                  * will always try all possible matches.  If you don't like
306                  * that then feel free to fix it.
307                  */
308
309                 /* Make a local copy of the string -- up 
310                  * to the position of the cursor */
311                 matchBuf = (char *) xcalloc(BUFSIZ, sizeof(char));
312                 strncpy(matchBuf, command, *cursor);
313                 tmp=matchBuf;
314
315                 /* skip past any command seperator tokens */
316                 while (*tmp && (tmp1=strpbrk(tmp, ";|&{(`")) != NULL) {
317                         tmp=++tmp1;
318                         /* skip any leading white space */
319                         while (*tmp && isspace(*tmp)) 
320                                 ++tmp;
321                 }
322
323                 /* skip any leading white space */
324                 while (*tmp && isspace(*tmp)) 
325                         ++tmp;
326
327                 /* Free up any memory already allocated */
328                 if (matches) {
329                         free(matches);
330                         matches = (char **) NULL;
331                 }
332
333                 /* If the word starts with `~' and there is no slash in the word, 
334                  * then try completing this word as a username. */
335
336                 /* FIXME -- this check is broken! */
337                 if (*tmp == '~' && !strchr(tmp, '/'))
338                         matches = username_tab_completion(tmp, &num_matches);
339
340                 /* Try to match any executable in our path and everything 
341                  * in the current working directory that matches.  */
342                 if (!matches)
343                         matches = exe_n_cwd_tab_completion(tmp, &num_matches);
344
345                 /* Don't leak memory */
346                 free( matchBuf);
347
348                 /* Did we find exactly one match? */
349                 if (matches && num_matches==1) {
350                         /* write out the matched command */
351                         strncpy(command+pos, matches[0]+pos, strlen(matches[0])-pos);
352                         *len=strlen(command);
353                         *cursor=*len;
354                         xwrite(outputFd, matches[0]+pos, strlen(matches[0])-pos);
355                         return;
356                 }
357         } else {
358                 /* Ok -- the last char was a TAB.  Since they
359                  * just hit TAB again, print a list of all the
360                  * available choices... */
361                 if ( matches && num_matches>0 ) {
362                         int i, col;
363
364                         /* Go to the next line */
365                         xwrite(outputFd, "\n", 1);
366                         /* Print the list of matches */
367                         for (i=0,col=0; i<num_matches; i++) {
368                                 char foo[17];
369                                 sprintf(foo, "%-14s  ", matches[i]);
370                                 col += xwrite(outputFd, foo, strlen(foo));
371                                 if (col > 60 && matches[i+1] != NULL) {
372                                         xwrite(outputFd, "\n", 1);
373                                         col = 0;
374                                 }
375                         }
376                         /* Go to the next line */
377                         xwrite(outputFd, "\n", 1);
378                         /* Rewrite the prompt */
379                         xwrite(outputFd, prompt, strlen(prompt));
380                         /* Rewrite the command */
381                         xwrite(outputFd, command, *len);
382                         /* Put the cursor back to where it used to be */
383                         for (cursor=len; *cursor > pos; cursor--)
384                                 xwrite(outputFd, "\b", 1);
385                 }
386         }
387 }
388 #endif
389
390 void get_previous_history(struct history **hp, char* command)
391 {
392         if ((*hp)->s)
393                 free((*hp)->s);
394         (*hp)->s = strdup(command);
395         *hp = (*hp)->p;
396 }
397
398 void get_next_history(struct history **hp, char* command)
399 {
400         if ((*hp)->s)
401                 free((*hp)->s);
402         (*hp)->s = strdup(command);
403         *hp = (*hp)->n;
404 }
405
406 /*
407  * This function is used to grab a character buffer
408  * from the input file descriptor and allows you to
409  * a string with full command editing (sortof like
410  * a mini readline).
411  *
412  * The following standard commands are not implemented:
413  * ESC-b -- Move back one word
414  * ESC-f -- Move forward one word
415  * ESC-d -- Delete back one word
416  * ESC-h -- Delete forward one word
417  * CTL-t -- Transpose two characters
418  *
419  * Furthermore, the "vi" command editing keys are not implemented.
420  *
421  * TODO: implement TAB command completion. :)
422  */
423 extern void cmdedit_read_input(char* prompt, char command[BUFSIZ])
424 {
425
426         int inputFd=fileno(stdin);
427         int outputFd=fileno(stdout);
428         int nr = 0;
429         int len = 0;
430         int j = 0;
431         int cursor = 0;
432         int break_out = 0;
433         int ret = 0;
434         int lastWasTab = FALSE;
435         char c = 0;
436         struct history *hp = his_end;
437
438         if (!reset_term) {
439                 
440                 getTermSettings(inputFd, (void*) &initial_settings);
441                 memcpy(&new_settings, &initial_settings, sizeof(struct termios));
442                 new_settings.c_cc[VMIN] = 1;
443                 new_settings.c_cc[VTIME] = 0;
444                 new_settings.c_cc[VINTR] = _POSIX_VDISABLE; /* Turn off CTRL-C, so we can trap it */
445                 new_settings.c_lflag &= ~ICANON;        /* unbuffered input */
446                 new_settings.c_lflag &= ~(ECHO|ECHOCTL|ECHONL); /* Turn off echoing */
447                 reset_term = 1;
448         }
449         setTermSettings(inputFd, (void*) &new_settings);
450
451         memset(command, 0, BUFSIZ);
452
453         while (1) {
454
455                 if ((ret = read(inputFd, &c, 1)) < 1)
456                         return;
457                 //fprintf(stderr, "got a '%c' (%d)\n", c, c);
458
459                 switch (c) {
460                 case '\n':
461                 case '\r':
462                         /* Enter */
463                         *(command + len++ + 1) = c;
464                         xwrite(outputFd, &c, 1);
465                         break_out = 1;
466                         break;
467                 case 1:
468                         /* Control-a -- Beginning of line */
469                         input_home(outputFd, &cursor);
470                 case 2:
471                         /* Control-b -- Move back one character */
472                         input_backward(outputFd, &cursor);
473                         break;
474                 case 3:
475                         /* Control-c -- stop gathering input */
476                         
477                         /* Link into lash to reset context to 0 on ^C and such */
478                         shell_context = 0;
479
480                         /* Go to the next line */
481                         xwrite(outputFd, "\n", 1);
482
483 #if 0
484                         /* Rewrite the prompt */
485                         xwrite(outputFd, prompt, strlen(prompt));
486
487                         /* Reset the command string */
488                         memset(command, 0, BUFSIZ);
489                         len = cursor = 0;
490 #endif
491                         return;
492
493                 case 4:
494                         /* Control-d -- Delete one character, or exit 
495                          * if the len=0 and no chars to delete */
496                         if (len == 0) {
497                                 xwrite(outputFd, "exit", 4);
498                                 clean_up_and_die(0);
499                         } else {
500                                 input_delete(command, outputFd, cursor, &len);
501                         }
502                         break;
503                 case 5:
504                         /* Control-e -- End of line */
505                         input_end(outputFd, &cursor, len);
506                         break;
507                 case 6:
508                         /* Control-f -- Move forward one character */
509                         input_forward(outputFd, &cursor, len);
510                         break;
511                 case '\b':
512                 case DEL:
513                         /* Control-h and DEL */
514                         input_backspace(command, outputFd, &cursor, &len);
515                         break;
516                 case '\t':
517 #ifdef BB_FEATURE_SH_TAB_COMPLETION
518                         input_tab(command, prompt, outputFd, &cursor,
519 &len, lastWasTab);
520 #endif
521                         break;
522                 case 14:
523                         /* Control-n -- Get next command in history */
524                         if (hp && hp->n && hp->n->s) {
525                                 get_next_history(&hp, command);
526                                 goto rewrite_line;
527                         } else {
528                                 xwrite(outputFd, "\007", 1);
529                         }
530                         break;
531                 case 16:
532                         /* Control-p -- Get previous command from history */
533                         if (hp && hp->p) {
534                                 get_previous_history(&hp, command);
535                                 goto rewrite_line;
536                         } else {
537                                 xwrite(outputFd, "\007", 1);
538                         }
539                         break;
540                 case ESC:{
541                                 /* escape sequence follows */
542                                 if ((ret = read(inputFd, &c, 1)) < 1)
543                                         return;
544
545                                 if (c == '[') { /* 91 */
546                                         if ((ret = read(inputFd, &c, 1)) < 1)
547                                                 return;
548
549                                         switch (c) {
550                                         case 'A':
551                                                 /* Up Arrow -- Get previous command from history */
552                                                 if (hp && hp->p) {
553                                                         get_previous_history(&hp, command);
554                                                         goto rewrite_line;
555                                                 } else {
556                                                         xwrite(outputFd, "\007", 1);
557                                                 }
558                                                 break;
559                                         case 'B':
560                                                 /* Down Arrow -- Get next command in history */
561                                                 if (hp && hp->n && hp->n->s) {
562                                                         get_next_history(&hp, command);
563                                                         goto rewrite_line;
564                                                 } else {
565                                                         xwrite(outputFd, "\007", 1);
566                                                 }
567                                                 break;
568
569                                                 /* Rewrite the line with the selected history item */
570                                           rewrite_line:
571                                                 /* erase old command from command line */
572                                                 len = strlen(command)-strlen(hp->s);
573
574                                                 while (len>cursor)
575                                                         input_delete(command, outputFd, cursor, &len);
576                                                 while (cursor>0)
577                                                         input_backspace(command, outputFd, &cursor, &len);
578                                                 input_home(outputFd, &cursor);
579                                                 
580                                                 /* write new command */
581                                                 strcpy(command, hp->s);
582                                                 len = strlen(hp->s);
583                                                 xwrite(outputFd, command, len);
584                                                 cursor = len;
585                                                 break;
586                                         case 'C':
587                                                 /* Right Arrow -- Move forward one character */
588                                                 input_forward(outputFd, &cursor, len);
589                                                 break;
590                                         case 'D':
591                                                 /* Left Arrow -- Move back one character */
592                                                 input_backward(outputFd, &cursor);
593                                                 break;
594                                         case '3':
595                                                 /* Delete */
596                                                 input_delete(command, outputFd, cursor, &len);
597                                                 break;
598                                         case '1':
599                                                 /* Home (Ctrl-A) */
600                                                 input_home(outputFd, &cursor);
601                                                 break;
602                                         case '4':
603                                                 /* End (Ctrl-E) */
604                                                 input_end(outputFd, &cursor, len);
605                                                 break;
606                                         default:
607                                                 xwrite(outputFd, "\007", 1);
608                                         }
609                                         if (c == '1' || c == '3' || c == '4')
610                                                 if ((ret = read(inputFd, &c, 1)) < 1)
611                                                         return; /* read 126 (~) */
612                                 }
613                                 if (c == 'O') {
614                                         /* 79 */
615                                         if ((ret = read(inputFd, &c, 1)) < 1)
616                                                 return;
617                                         switch (c) {
618                                         case 'H':
619                                                 /* Home (xterm) */
620                                                 input_home(outputFd, &cursor);
621                                                 break;
622                                         case 'F':
623                                                 /* End (xterm) */
624                                                 input_end(outputFd, &cursor, len);
625                                                 break;
626                                         default:
627                                                 xwrite(outputFd, "\007", 1);
628                                         }
629                                 }
630                                 c = 0;
631                                 break;
632                         }
633
634                 default:                                /* If it's regular input, do the normal thing */
635
636                         if (!isprint(c)) {      /* Skip non-printable characters */
637                                 break;
638                         }
639
640                         if (len >= (BUFSIZ - 2))        /* Need to leave space for enter */
641                                 break;
642
643                         len++;
644
645                         if (cursor == (len - 1)) {      /* Append if at the end of the line */
646                                 *(command + cursor) = c;
647                         } else {                        /* Insert otherwise */
648                                 memmove(command + cursor + 1, command + cursor,
649                                                 len - cursor - 1);
650
651                                 *(command + cursor) = c;
652
653                                 for (j = cursor; j < len; j++)
654                                         xwrite(outputFd, command + j, 1);
655                                 for (; j > cursor; j--)
656                                         xwrite(outputFd, "\033[D", 3);
657                         }
658
659                         cursor++;
660                         xwrite(outputFd, &c, 1);
661                         break;
662                 }
663                 if (c == '\t')
664                         lastWasTab = TRUE;
665                 else
666                         lastWasTab = FALSE;
667
668                 if (break_out)                  /* Enter is the command terminator, no more input. */
669                         break;
670         }
671
672         nr = len + 1;
673         setTermSettings(inputFd, (void *) &initial_settings);
674         reset_term = 0;
675
676
677         /* Handle command history log */
678         if (*(command)) {
679
680                 struct history *h = his_end;
681
682                 if (!h) {
683                         /* No previous history -- this memory is never freed */
684                         h = his_front = xmalloc(sizeof(struct history));
685                         h->n = xmalloc(sizeof(struct history));
686
687                         h->p = NULL;
688                         h->s = strdup(command);
689                         h->n->p = h;
690                         h->n->n = NULL;
691                         h->n->s = NULL;
692                         his_end = h->n;
693                         history_counter++;
694                 } else {
695                         /* Add a new history command -- this memory is never freed */
696                         h->n = xmalloc(sizeof(struct history));
697
698                         h->n->p = h;
699                         h->n->n = NULL;
700                         h->n->s = NULL;
701                         h->s = strdup(command);
702                         his_end = h->n;
703
704                         /* After max history, remove the oldest command */
705                         if (history_counter >= MAX_HISTORY) {
706
707                                 struct history *p = his_front->n;
708
709                                 p->p = NULL;
710                                 free(his_front->s);
711                                 free(his_front);
712                                 his_front = p;
713                         } else {
714                                 history_counter++;
715                         }
716                 }
717         }
718
719         return;
720 }
721
722 extern void cmdedit_init(void)
723 {
724         if(exithandler_set == 0) {
725                 atexit(cmdedit_reset_term);     /* be sure to do this only once */
726                 exithandler_set = 1;
727         }
728         signal(SIGKILL, clean_up_and_die);
729         signal(SIGINT, clean_up_and_die);
730         signal(SIGQUIT, clean_up_and_die);
731         signal(SIGTERM, clean_up_and_die);
732 }
733
734 /*
735 ** Undo the effects of cmdedit_init() as good as we can:
736 ** I am not aware of a way to revoke an atexit() handler,
737 ** but, fortunately, our particular handler can be made
738 ** a no-op by setting reset_term = 0.
739 */
740 extern void cmdedit_terminate(void)
741 {
742         cmdedit_reset_term();
743         reset_term = 0;
744         signal(SIGKILL, SIG_DFL);
745         signal(SIGINT, SIG_DFL);
746         signal(SIGQUIT, SIG_DFL);
747         signal(SIGTERM, SIG_DFL);
748 }
749
750
751
752 #endif                                                  /* BB_FEATURE_SH_COMMAND_EDITING */