2 Generalized console input/output handler
3 A maintanable replacement for readline()
5 Kern Sibbald, December MMIII
7 This code is in part derived from code that I wrote in
8 1981, so some of it is a bit old and could use a cleanup.
12 Copyright (C) 1981-2004 Kern Sibbald and John Walker
13 Yes, that is 1981 no error.
15 This program is free software; you can redistribute it and/or
16 modify it under the terms of the GNU General Public License as
17 published by the Free Software Foundation; either version 2 of
18 the License, or (at your option) any later version.
20 This program is distributed in the hope that it will be useful,
21 but WITHOUT ANY WARRANTY; without even the implied warranty of
22 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
23 General Public License for more details.
25 You should have received a copy of the GNU General Public
26 License along with this program; if not, write to the Free
27 Software Foundation, Inc., 59 Temple Place - Suite 330, Boston,
42 /* We are in Bacula */
52 /* From termios library */
56 /* Forward referenced functions */
57 static void sigintcatcher(int);
58 static void add_smap(char *str, int func);
61 /* Global variables */
63 static char *t_up = "\n"; /* scroll up character */
64 static char *t_honk = "\007"; /* sound beep */
65 static char *t_il; /* insert line */
66 static char *t_dl; /* delete line */
67 static char *t_cs; /* clear screen */
68 static char *t_cl; /* clear line */
69 static int t_width = 79; /* terminal width */
70 static int t_height = 24; /* terminal height */
71 static int linsdel_ok = 0; /* set if term has line insert & delete fncs */
73 static char *t_cm; /* cursor positioning */
74 static char *t_ti; /* init sequence */
75 static char *t_te; /* end sequence */
76 static char *t_do; /* down one line */
77 static char *t_sf; /* scroll screen one line up */
79 /* Keypad and Function Keys */
80 static char *kl; /* left key */
81 static char *kr; /* right */
82 static char *ku; /* up */
83 static char *kd; /* down */
84 static char *kh; /* home */
85 static char *kb; /* backspace */
86 static char *kD; /* delete key */
87 static char *kI; /* insert */
88 static char *kN; /* next page */
89 static char *kP; /* previous page */
90 static char *kH; /* home */
91 static char *kE; /* end */
94 #define EOS '\0' /* end of string terminator */
100 * Stab entry. Input chars (str), the length, and the desired
103 typedef struct s_stab {
112 static stab_t **stab = NULL; /* array of stabs by length */
113 static int num_stab; /* size of stab array */
115 static bool old_term_params_set = false;
116 static struct termios old_term_params;
118 /* Maintain lines in a doubly linked circular pool of lines. Each line is
119 preceded by a header defined by the lstr structure */
122 struct lstr { /* line pool structure */
123 struct lstr *prevl; /* link to previous line */
124 struct lstr *nextl; /* link to next line */
125 long len; /* length of line+header */
126 char used; /* set if line valid */
127 char line; /* line is actually varying length */
131 #define POOLEN 128000 /* bytes in line pool */
133 #define POOLEN 500 /* bytes in line pool */
135 char pool[POOLEN]; /* line pool */
136 #define PHDRL ((int)sizeof(struct lstr)) /* length of line header */
138 static struct lstr *lptr; /* current line pointer */
139 static struct lstr *slptr; /* store line pointer */
141 static char *getnext(), *getprev();
142 static int first = 1;
143 static int mode_insert = 0;
144 static int mode_wspace = 1; /* words separated by spaces */
147 static short char_map[600]= {
148 0, F_SOL, /* ^a Line start */
149 F_PRVWRD, /* ^b Previous word */ F_BREAK, /* ^C break */
150 F_DELCHR, /* ^D Delete character */ F_EOL, /* ^e End of line */
151 F_CSRRGT, /* ^f Right */ F_TABBAK, /* ^G Back tab */
152 F_CSRLFT, /* ^H Left */ F_TAB, /* ^I Tab */
153 F_CSRDWN, /* ^J Down */ F_DELEOL, /* ^K kill to eol */
154 F_CLRSCRN,/* ^L clear screen */ F_RETURN, /* ^M Carriage return */
155 F_RETURN, /* ^N enter line */ F_CONCAT, /* ^O Concatenate lines */
156 F_CSRUP, /* ^P cursor up */ F_TINS, /* ^Q Insert character mode */
157 F_PAGUP, /* ^R Page up */ F_CENTER, /* ^S Center text */
158 F_PAGDWN, /* ^T Page down */ F_DELSOL, /* ^U delete to start of line */
159 F_DELWRD, /* ^V Delete word */ F_PRVWRD, /* ^W Previous word */
160 F_NXTMCH, /* ^X Next match */ F_DELEOL, /* ^Y Delete to end of line */
161 F_BACKGND,/* ^Z Background */ 0x1B, /* ^[=ESC escape */
162 F_TENTRY, /* ^\ Entry mode */ F_PASTECB,/* ^]=paste clipboard */
163 F_HOME, /* ^^ Home */ F_ERSLIN, /* ^_ Erase line */
165 ' ','!','"','#','$','%','&','\047',
166 '(',')','*','+','\054','-','.','/',
167 '0','1','2','3','4','5','6','7',
168 '8','9',':',';','<','=','>','?',
169 '@','A','B','C','D','E','F','G',
170 'H','I','J','K','L','M','N','O',
171 'P','Q','R','S','T','U','V','W',
172 'X','Y','Z','[','\\',']','^','_',
173 '\140','a','b','c','d','e','f','g',
174 'h','i','j','k','l','m','n','o',
175 'p','q','r','s','t','u','v','w',
176 'x','y','z','{','|','}','\176',F_ERSCHR /* erase character */
181 /* Local variables */
183 #define CR '\r' /* carriage return */
186 /* Function Prototypes */
188 static int input_char(void);
189 static int t_gnc(void);
190 static void insert_space(char *curline, int line_len);
191 static void forward(int i, char *str, int str_len);
192 static void backup(int i);
193 static void delchr(int cnt, char *curline, int line_len);
194 static int iswordc(char c);
195 static int next_word(char *ldb_buf);
196 static int prev_word(char *ldb_buf);
197 static void prtcur(char *str);
198 static void poolinit(void);
199 static char * getnext(void);
200 static char * getprev(void);
201 static void putline(char *newl, int newlen);
202 static void t_honk_horn(void);
203 static void t_insert_line(void);
204 static void t_delete_line(void);
205 static void t_clrline(int pos, int width);
206 void t_sendl(char *msg, int len);
207 void t_send(char *msg);
209 static void asclrs();
210 static void ascurs(int y, int x);
212 static void rawmode(FILE *input);
213 static void normode(void);
214 static int t_getch();
215 static void asclrl(int pos, int width);
216 static void asinsl();
217 static void asdell();
219 int input_line(char *string, int length);
225 void con_init(FILE *input)
235 void con_set_zed_keys(void)
237 char_map[1] = F_NXTWRD; /* ^A Next Word */
238 char_map[2] = F_SPLIT; /* ^B Split line */
239 char_map[3] = F_EOI; /* ^C Quit */
240 char_map[4] = F_DELCHR; /* ^D Delete character */
241 char_map[5] = F_EOF; /* ^E End of file */
242 char_map[6] = F_INSCHR; /* ^F Insert character */
243 char_map[7] = F_TABBAK; /* ^G Back tab */
244 char_map[8] = F_CSRLFT; /* ^H Left */
245 char_map[9] = F_TAB; /* ^I Tab */
246 char_map[10] = F_CSRDWN; /* ^J Down */
247 char_map[11] = F_CSRUP; /* ^K Up */
248 char_map[12] = F_CSRRGT; /* ^L Right */
249 char_map[13] = F_RETURN; /* ^M Carriage return */
250 char_map[14] = F_EOL; /* ^N End of line */
251 char_map[15] = F_CONCAT; /* ^O Concatenate lines */
252 char_map[16] = F_MARK; /* ^P Set marker */
253 char_map[17] = F_TINS; /* ^Q Insert character mode */
254 char_map[18] = F_PAGUP; /* ^R Page up */
255 char_map[19] = F_CENTER; /* ^S Center text */
256 char_map[20] = F_PAGDWN; /* ^T Page down */
257 char_map[21] = F_SOL; /* ^U Line start */
258 char_map[22] = F_DELWRD; /* ^V Delete word */
259 char_map[23] = F_PRVWRD; /* ^W Previous word */
260 char_map[24] = F_NXTMCH; /* ^X Next match */
261 char_map[25] = F_DELEOL; /* ^Y Delete to end of line */
262 char_map[26] = F_DELLIN; /* ^Z Delete line */
264 char_map[28] = F_TENTRY; /* ^\ Entry mode */
265 char_map[29] = F_PASTECB;/* ^]=paste clipboard */
266 char_map[30] = F_HOME; /* ^^ Home */
267 char_map[31] = F_ERSLIN; /* ^_ Erase line */
278 * Guarantee that the string is properly terminated */
279 char *bstrncpy(char *dest, const char *src, int maxlen)
281 strncpy(dest, src, maxlen-1);
289 * New style string mapping to function code
291 static int do_smap(int c)
310 for (i=len-1; i<MAX_STAB; i++) {
311 for (tstab=stab[i]; tstab; tstab=tstab->next) {
312 if (strncmp(str, tstab->str, len) == 0) {
313 if (len == tstab->len) {
317 break; /* found possibility continue searching */
324 /* found partial match, so get next character and retry */
325 str[len++] = t_gnc();
331 static void dump_stab()
337 for (i=0; i<MAX_STAB; i++) {
338 for (tstab=stab[i]; tstab; tstab=tstab->next) {
339 for (j=0; j<tstab->len; j++) {
341 if (c < 0x20 || c > 0x7F) {
342 sprintf(buf, " 0x%x ", c);
350 sprintf(buf, " func=%d len=%d\n\r", tstab->func, tstab->len);
358 * New routine. Add string to string->func mapping table.
360 static void add_smap(char *str, int func)
370 /* errmsg("String for func %d is zero length\n", func); */
373 tstab = (stab_t *)malloc(sizeof(stab_t));
374 memset(tstab, 0, sizeof(stab_t));
376 tstab->str = (char *)malloc(tstab->len + 1);
377 bstrncpy(tstab->str, str, tstab->len + 1);
379 if (tstab->len > num_stab) {
380 printf("stab string too long %d. Max is %d\n", tstab->len, num_stab);
383 tstab->next = stab[tstab->len-1];
384 stab[tstab->len-1] = tstab;
385 /* printf("Add_smap tstab=%x len=%d func=%d tstab->next=%x\n\r", tstab, len,
386 func, tstab->next); */
391 /* Get the next character from the terminal - performs table lookup on
392 the character to do the desired translation */
398 if ((c=t_gnc()) <= 599) { /* IBM generates codes up to 260 */
400 } else if (c > 1000) { /* stuffed function */
401 c -= 1000; /* convert back to function code */
406 /* if we got a screen size escape sequence, read height, width */
409 y = t_gnc() - 0x20; /* y */
410 x = t_gnc() - 0x20; /* x */
417 /* Get a complete input line */
420 input_line(char *string, int length)
422 char curline[2000]; /* edit buffer */
427 poolinit(); /* build line pool */
430 noline = 1; /* no line fetched yet */
431 for (cl=cp=0; cl<length && cl<(int)sizeof(curline); ) {
436 switch (c=(int)input_char()) {
437 case F_RETURN: /* CR */
438 t_sendl("\r\n", 2); /* yes, print it and */
439 goto done; /* get out */
440 case F_CLRSCRN: /* clear screen */
442 t_sendl(curline, cl);
446 if (noline) { /* no line fetched yet */
447 getnext(); /* getnext so getprev gets current */
448 noline = 0; /* we now have line */
450 bstrncpy(curline, getprev(), sizeof(curline));
454 noline = 0; /* mark line fetched */
455 bstrncpy(curline, getnext(), sizeof(curline));
459 insert_space(curline, sizeof(curline));
462 delchr(1, curline, sizeof(curline)); /* delete one character */
464 case F_CSRLFT: /* Backspace */
468 forward(1,curline, sizeof(curline));
470 case F_ERSCHR: /* Rubout */
472 delchr(1, curline, sizeof(curline));
475 t_clrline(0, t_width);
480 forward(next_word(curline),curline, sizeof(curline));
483 backup(prev_word(curline));
486 delchr(next_word(curline), curline, sizeof(curline)); /* delete word */
488 case F_NXTMCH: /* Ctl-X */
490 *string = EOS; /* terminate string */
491 return(c); /* give it to him */
493 /* Note fall through */
496 backup(cp); /* backup to beginning of line */
497 t_clrline(0,t_width); /* erase line */
499 cl = 0; /* reset cursor counter */
506 forward(1,curline, sizeof(curline));
512 case F_TINS: /* toggle insert mode */
513 mode_insert = !mode_insert; /* flip bit */
516 if (c > 255) { /* function key hit */
517 if (cl==0) { /* if first character then */
518 *string = EOS; /* terminate string */
519 return c; /* return it */
521 t_honk_horn(); /* complain */
524 insert_space(curline, sizeof(curline));
526 curline[cp++] = c; /* store character in line being built */
527 t_char((char)c); /* echo character to terminal */
529 cl = cp; /* keep current length */
535 /* If we fall through here rather than goto done, the line is too long
536 simply return what we have now. */
538 curline[cl++] = EOS; /* terminate */
539 bstrncpy(string,curline,length); /* return line to caller */
540 /* Note, put line zaps curline */
541 putline(curline,cl); /* save line for posterity */
542 return 0; /* give it to him/her */
545 /* Insert a space at the current cursor position */
547 insert_space(char *curline, int curline_len)
551 if (cp > cl || cl+1 > curline_len) return;
552 /* Note! source and destination overlap */
553 memmove(&curline[cp+1],&curline[cp],i=cl-cp);
557 forward(i,curline, curline_len);
562 /* Move cursor forward keeping characters under it */
564 forward(int i, char *str, int str_len)
580 /* Backup cursor keeping characters under it */
584 for ( ; i && cp; i--,cp--) {
589 /* Delete the character under the cursor */
591 delchr(int cnt, char *curline, int line_len)
597 if ((i=cl-cp-cnt+1) > 0) {
598 memcpy(&curline[cp], &curline[cp+cnt],i);
600 curline[cl -= cnt] = EOS;
601 t_clrline(0,t_width);
603 forward(i=cl-cp,curline, line_len);
608 /* Determine if character is part of a word */
614 if (c >= '0' && c <= '9')
616 if (c == '$' || c == '%')
621 /* Return number of characters to get to next word */
623 next_word(char *ldb_buf)
630 for ( ; ncp<cl && iswordc(*(ldb_buf+ncp)); ncp++) ;
631 for ( ; ncp<cl && !iswordc(*(ldb_buf+ncp)); ncp++) ;
635 /* Return number of characters to get to previous word */
637 prev_word(char *ldb_buf)
641 if (cp == 0) /* if at begin of line stop now */
643 if (cp > cl) /* if past eol start at eol */
647 /* backup to end of previous word - i.e. skip special chars */
648 for (i=ncp-1; i && !iswordc(*(ldb_buf+i)); i--) ;
649 if (i == 0) { /* at beginning of line? */
650 return cp; /* backup to beginning */
652 /* now move back through word to beginning of word */
653 for ( ; i && iswordc(*(ldb_buf+i)); i--) ;
654 ncp = i+1; /* position to first char of word */
655 if (i==0 && iswordc(*ldb_buf)) /* check for beginning of line */
657 return cp-ncp; /* return count */
660 /* Display new current line */
665 t_clrline(0,t_width);
666 cp = cl = strlen(str);
671 /* Initialize line pool. Split pool into two pieces. */
675 slptr = lptr = (struct lstr *)pool;
684 /* Return pointer to next line in the pool and advance current line pointer */
688 do { /* find next used line */
690 } while (!lptr->used);
691 return (char *)&lptr->line;
694 /* Return pointer to previous line in the pool */
698 do { /* find previous used line */
700 } while (!lptr->used);
701 return (char *)&lptr->line;
705 putline(char *newl, int newlen)
707 struct lstr *nptr; /* points to next line */
710 lptr = slptr; /* get ptr to last line stored */
711 lptr = lptr->nextl; /* advance pointer */
712 if ((char *)lptr-pool+newlen+PHDRL > POOLEN) { /* not enough room */
713 lptr->used = 0; /* delete line */
714 lptr = (struct lstr *)pool; /* start at beginning of buffer */
716 while (lptr->len < newlen+PHDRL) { /* concatenate buffers */
717 nptr = lptr->nextl; /* point to next line */
718 lptr->nextl = nptr->nextl; /* unlink it from list */
719 nptr->nextl->prevl = lptr;
720 lptr->len += nptr->len;
722 if (lptr->len > newlen + 2 * PHDRL) { /* split buffer */
723 nptr = (struct lstr *)((char *)lptr + newlen + PHDRL);
724 /* Appropriate byte alignment - normally 2 byte, but on
725 sparc we need 4 byte alignment, so we always do 4 */
726 if (((long unsigned)nptr & 3) != 0) { /* test four byte alignment */
728 nptr = (struct lstr *)((((long unsigned) p) & ~3) + 4);
730 nptr->len = lptr->len - ((char *)nptr - (char *)lptr);
731 lptr->len -= nptr->len;
732 nptr->nextl = lptr->nextl; /* link in new buffer */
733 lptr->nextl->prevl = nptr;
738 memcpy(&lptr->line,newl,newlen);
739 lptr->used = 1; /* mark line used */
740 slptr = lptr; /* save as stored line */
745 dump(struct lstr *ptr, char *msg)
747 printf("%s buf=%x nextl=%x prevl=%x len=%d used=%d\n",
748 msg,ptr,ptr->nextl,ptr->prevl,ptr->len,ptr->used);
750 printf("line=%s\n",&ptr->line);
752 #endif /* DEBUGOUT */
755 /* Honk horn on terminal */
762 /* Insert line on terminal */
769 /* Delete line from terminal */
776 /* clear line from pos to width */
778 t_clrline(int pos, int width)
780 asclrl(pos, width); /* clear to end of line */
783 /* Helper function to add string preceded by
784 * ESC to smap table */
785 static void add_esc_smap(char *str, int func)
788 buf[0] = 0x1B; /* esc */
789 bstrncpy(buf+1, str, sizeof(buf)-1);
793 /* Set raw mode on terminal file. Basically, get the terminal into a
794 mode in which all characters can be read as they are entered. CBREAK
795 mode is not sufficient.
797 static void rawmode(FILE *input)
800 static char term_buf[2048];
801 static char *term_buffer = term_buf;
802 char *termtype = (char *)getenv("TERM");
804 /* Make sure we are dealing with a terminal */
805 if (!isatty(fileno(input))) {
808 if (tcgetattr(0, &old_term_params) != 0) {
809 printf("conio: Cannot tcgetattr()\n");
812 old_term_params_set = true;
814 t.c_cc[VMIN] = 1; /* satisfy read after 1 char */
816 t.c_iflag &= ~(BRKINT | IGNPAR | PARMRK | INPCK |
817 ISTRIP | ICRNL | IXON | IXOFF | INLCR | IGNCR);
820 t.c_lflag &= ~(ECHO | ECHOE | ECHOK | ECHONL | ICANON |
822 tcflush(0, TCIFLUSH);
823 if (tcsetattr(0, TCSANOW, &t) == -1) {
824 printf("Cannot tcsetattr()\n");
827 /* Defaults, the main program can override these */
828 signal(SIGQUIT, SIG_IGN);
829 signal(SIGHUP, SIG_IGN);
830 // signal(SIGSTOP, SIG_IGN);
831 signal(SIGINT, sigintcatcher);
832 signal(SIGWINCH, SIG_IGN);
833 signal(SIGQUIT, SIG_IGN);
834 signal(SIGCHLD, SIG_IGN);
835 // signal(SIGTSTP, SIG_IGN);
838 printf("Cannot get terminal type.\n");
842 if (tgetent(term_buffer, termtype) < 0) {
843 printf("Cannot get terminal termcap entry.\n");
847 t_width = t_height = -1;
848 t_width = tgetnum("co") - 1;
849 t_height = tgetnum("li");
852 t_cm = (char *)tgetstr("cm", &term_buffer);
853 t_cs = (char *)tgetstr("cl", &term_buffer); /* clear screen */
854 t_cl = (char *)tgetstr("ce", &term_buffer); /* clear line */
855 t_dl = (char *)tgetstr("dl", &term_buffer); /* delete line */
856 t_il = (char *)tgetstr("al", &term_buffer); /* insert line */
857 t_honk = (char *)tgetstr("bl", &term_buffer); /* beep */
858 t_ti = (char *)tgetstr("ti", &term_buffer);
859 t_te = (char *)tgetstr("te", &term_buffer);
860 t_up = (char *)tgetstr("up", &term_buffer);
861 t_do = (char *)tgetstr("do", &term_buffer);
862 t_sf = (char *)tgetstr("sf", &term_buffer);
864 num_stab = MAX_STAB; /* get default stab size */
865 stab = (stab_t **)malloc(sizeof(stab_t *) * num_stab);
866 memset(stab, 0, sizeof(stab_t *) * num_stab);
869 kl = (char *)tgetstr("kl", &term_buffer);
870 kr = (char *)tgetstr("kr", &term_buffer);
871 ku = (char *)tgetstr("ku", &term_buffer);
872 kd = (char *)tgetstr("kd", &term_buffer);
873 kh = (char *)tgetstr("kh", &term_buffer);
874 kb = (char *)tgetstr("kb", &term_buffer);
875 kD = (char *)tgetstr("kD", &term_buffer);
876 kI = (char *)tgetstr("kI", &term_buffer);
877 kN = (char *)tgetstr("kN", &term_buffer);
878 kP = (char *)tgetstr("kP", &term_buffer);
879 kH = (char *)tgetstr("kH", &term_buffer);
880 kE = (char *)tgetstr("kE", &term_buffer);
882 add_smap(kl, F_CSRLFT);
883 add_smap(kr, F_CSRRGT);
884 add_smap(ku, F_CSRUP);
885 add_smap(kd, F_CSRDWN);
886 add_smap(kI, F_TINS);
887 add_smap(kN, F_PAGDWN);
888 add_smap(kP, F_PAGUP);
889 add_smap(kH, F_HOME);
893 add_esc_smap("[A", F_CSRUP);
894 add_esc_smap("[B", F_CSRDWN);
895 add_esc_smap("[C", F_CSRRGT);
896 add_esc_smap("[D", F_CSRLFT);
897 add_esc_smap("[1~", F_HOME);
898 add_esc_smap("[2~", F_TINS);
899 add_esc_smap("[3~", F_DELCHR);
900 add_esc_smap("[4~", F_EOF);
901 add_esc_smap("f", F_NXTWRD);
902 add_esc_smap("b", F_PRVWRD);
906 /* Restore tty mode */
907 static void normode()
909 if (old_term_params_set) {
910 tcsetattr(0, TCSANOW, &old_term_params);
911 old_term_params_set = false;
915 /* Get next character from terminal/script file/unget buffer */
923 /* Get next character from OS */
924 static int t_getch(void)
928 if (read(0, &c, 1) != 1) {
934 /* Send message to terminal - primitive routine */
936 t_sendl(char *msg, int len)
947 t_sendl(msg, strlen(msg)); /* faster than one char at time */
950 /* Send single character to terminal - primitive routine - */
958 static int brkflg = 0; /* set on user break */
960 /* Routine to return true if user types break */
966 /* Clear break flag */
973 /* Interrupt caught here */
974 static void sigintcatcher(int sig)
981 signal(SIGINT, sigintcatcher);
988 signal(SIGINT, sigintcatcher);
992 /* ASCLRL() -- Clear to end of line from current position */
993 static void asclrl(int pos, int width)
998 t_send(t_cl); /* use clear to eol function */
1001 if (pos==1 && linsdel_ok) {
1002 t_delete_line(); /* delete line */
1003 t_insert_line(); /* reinsert it */
1006 for (i=1; i<=width-pos+1; i++)
1007 t_char(' '); /* last resort, blank it out */
1008 for (i=1; i<=width-pos+1; i++) /* backspace to original position */
1015 /* ASCURS -- Set cursor position */
1016 static void ascurs(int y, int x)
1018 t_send((char *)tgoto(t_cm, x, y));
1022 /* ASCLRS -- Clear whole screen */
1023 static void asclrs()
1031 /* ASINSL -- insert new line after cursor */
1032 static void asinsl()
1034 t_clrline(0, t_width);
1035 t_send(t_il); /* insert before */
1038 /* ASDELL -- Delete line at cursor */
1039 static void asdell()