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 */
49 extern "C" int tgetent(void *, const char *);
50 extern "C" int tgetnum(const char *);
51 extern "C" char *tgetstr (const char*, char**);
52 extern "C" char *tgoto (const char *, int, int);
59 /* From termios library */
63 /* Forward referenced functions */
64 static void sigintcatcher(int);
65 static void add_smap(char *str, int func);
68 /* Global variables */
70 static char *t_up = "\n"; /* scroll up character */
71 static char *t_honk = "\007"; /* sound beep */
72 static char *t_il; /* insert line */
73 static char *t_dl; /* delete line */
74 static char *t_cs; /* clear screen */
75 static char *t_cl; /* clear line */
76 static int t_width = 79; /* terminal width */
77 static int t_height = 24; /* terminal height */
78 static int linsdel_ok = 0; /* set if term has line insert & delete fncs */
80 static char *t_cm; /* cursor positioning */
81 static char *t_ti; /* init sequence */
82 static char *t_te; /* end sequence */
83 static char *t_do; /* down one line */
84 static char *t_sf; /* scroll screen one line up */
86 /* Keypad and Function Keys */
87 static char *kl; /* left key */
88 static char *kr; /* right */
89 static char *ku; /* up */
90 static char *kd; /* down */
91 static char *kh; /* home */
92 static char *kb; /* backspace */
93 static char *kD; /* delete key */
94 static char *kI; /* insert */
95 static char *kN; /* next page */
96 static char *kP; /* previous page */
97 static char *kH; /* home */
98 static char *kE; /* end */
101 #define EOS '\0' /* end of string terminator */
107 * Stab entry. Input chars (str), the length, and the desired
110 typedef struct s_stab {
119 static stab_t **stab = NULL; /* array of stabs by length */
120 static int num_stab; /* size of stab array */
122 static bool old_term_params_set = false;
123 static struct termios old_term_params;
125 /* Maintain lines in a doubly linked circular pool of lines. Each line is
126 preceded by a header defined by the lstr structure */
129 struct lstr { /* line pool structure */
130 struct lstr *prevl; /* link to previous line */
131 struct lstr *nextl; /* link to next line */
132 long len; /* length of line+header */
133 char used; /* set if line valid */
134 char line; /* line is actually varying length */
138 #define POOLEN 128000 /* bytes in line pool */
140 #define POOLEN 500 /* bytes in line pool */
142 char pool[POOLEN]; /* line pool */
143 #define PHDRL ((int)sizeof(struct lstr)) /* length of line header */
145 static struct lstr *lptr; /* current line pointer */
146 static struct lstr *slptr; /* store line pointer */
148 static char *getnext(), *getprev();
149 static int first = 1;
150 static int mode_insert = 0;
151 static int mode_wspace = 1; /* words separated by spaces */
154 static short char_map[600]= {
155 0, F_SOL, /* ^a Line start */
156 F_PRVWRD, /* ^b Previous word */ F_BREAK, /* ^C break */
157 F_DELCHR, /* ^D Delete character */ F_EOL, /* ^e End of line */
158 F_CSRRGT, /* ^f Right */ F_TABBAK, /* ^G Back tab */
159 F_CSRLFT, /* ^H Left */ F_TAB, /* ^I Tab */
160 F_CSRDWN, /* ^J Down */ F_DELEOL, /* ^K kill to eol */
161 F_CLRSCRN,/* ^L clear screen */ F_RETURN, /* ^M Carriage return */
162 F_RETURN, /* ^N enter line */ F_CONCAT, /* ^O Concatenate lines */
163 F_CSRUP, /* ^P cursor up */ F_TINS, /* ^Q Insert character mode */
164 F_PAGUP, /* ^R Page up */ F_CENTER, /* ^S Center text */
165 F_PAGDWN, /* ^T Page down */ F_DELSOL, /* ^U delete to start of line */
166 F_DELWRD, /* ^V Delete word */ F_PRVWRD, /* ^W Previous word */
167 F_NXTMCH, /* ^X Next match */ F_DELEOL, /* ^Y Delete to end of line */
168 F_BACKGND,/* ^Z Background */ 0x1B, /* ^[=ESC escape */
169 F_TENTRY, /* ^\ Entry mode */ F_PASTECB,/* ^]=paste clipboard */
170 F_HOME, /* ^^ Home */ F_ERSLIN, /* ^_ Erase line */
172 ' ','!','"','#','$','%','&','\047',
173 '(',')','*','+','\054','-','.','/',
174 '0','1','2','3','4','5','6','7',
175 '8','9',':',';','<','=','>','?',
176 '@','A','B','C','D','E','F','G',
177 'H','I','J','K','L','M','N','O',
178 'P','Q','R','S','T','U','V','W',
179 'X','Y','Z','[','\\',']','^','_',
180 '\140','a','b','c','d','e','f','g',
181 'h','i','j','k','l','m','n','o',
182 'p','q','r','s','t','u','v','w',
183 'x','y','z','{','|','}','\176',F_ERSCHR /* erase character */
188 /* Local variables */
190 #define CR '\r' /* carriage return */
193 /* Function Prototypes */
195 static int input_char(void);
196 static int t_gnc(void);
197 static void insert_space(char *curline, int line_len);
198 static void forward(int i, char *str, int str_len);
199 static void backup(int i);
200 static void delchr(int cnt, char *curline, int line_len);
201 static int iswordc(char c);
202 static int next_word(char *ldb_buf);
203 static int prev_word(char *ldb_buf);
204 static void prtcur(char *str);
205 static void poolinit(void);
206 static char * getnext(void);
207 static char * getprev(void);
208 static void putline(char *newl, int newlen);
209 static void t_honk_horn(void);
210 static void t_insert_line(void);
211 static void t_delete_line(void);
212 static void t_clrline(int pos, int width);
213 void t_sendl(char *msg, int len);
214 void t_send(char *msg);
216 static void asclrs();
217 static void ascurs(int y, int x);
219 static void rawmode(FILE *input);
220 static void normode(void);
221 static int t_getch();
222 static void asclrl(int pos, int width);
223 static void asinsl();
224 static void asdell();
226 int input_line(char *string, int length);
232 void con_init(FILE *input)
242 void con_set_zed_keys(void)
244 char_map[1] = F_NXTWRD; /* ^A Next Word */
245 char_map[2] = F_SPLIT; /* ^B Split line */
246 char_map[3] = F_EOI; /* ^C Quit */
247 char_map[4] = F_DELCHR; /* ^D Delete character */
248 char_map[5] = F_EOF; /* ^E End of file */
249 char_map[6] = F_INSCHR; /* ^F Insert character */
250 char_map[7] = F_TABBAK; /* ^G Back tab */
251 char_map[8] = F_CSRLFT; /* ^H Left */
252 char_map[9] = F_TAB; /* ^I Tab */
253 char_map[10] = F_CSRDWN; /* ^J Down */
254 char_map[11] = F_CSRUP; /* ^K Up */
255 char_map[12] = F_CSRRGT; /* ^L Right */
256 char_map[13] = F_RETURN; /* ^M Carriage return */
257 char_map[14] = F_EOL; /* ^N End of line */
258 char_map[15] = F_CONCAT; /* ^O Concatenate lines */
259 char_map[16] = F_MARK; /* ^P Set marker */
260 char_map[17] = F_TINS; /* ^Q Insert character mode */
261 char_map[18] = F_PAGUP; /* ^R Page up */
262 char_map[19] = F_CENTER; /* ^S Center text */
263 char_map[20] = F_PAGDWN; /* ^T Page down */
264 char_map[21] = F_SOL; /* ^U Line start */
265 char_map[22] = F_DELWRD; /* ^V Delete word */
266 char_map[23] = F_PRVWRD; /* ^W Previous word */
267 char_map[24] = F_NXTMCH; /* ^X Next match */
268 char_map[25] = F_DELEOL; /* ^Y Delete to end of line */
269 char_map[26] = F_DELLIN; /* ^Z Delete line */
271 char_map[28] = F_TENTRY; /* ^\ Entry mode */
272 char_map[29] = F_PASTECB;/* ^]=paste clipboard */
273 char_map[30] = F_HOME; /* ^^ Home */
274 char_map[31] = F_ERSLIN; /* ^_ Erase line */
285 * Guarantee that the string is properly terminated */
286 char *bstrncpy(char *dest, const char *src, int maxlen)
288 strncpy(dest, src, maxlen-1);
296 * New style string mapping to function code
298 static int do_smap(int c)
317 for (i=len-1; i<MAX_STAB; i++) {
318 for (tstab=stab[i]; tstab; tstab=tstab->next) {
319 if (strncmp(str, tstab->str, len) == 0) {
320 if (len == tstab->len) {
324 break; /* found possibility continue searching */
331 /* found partial match, so get next character and retry */
332 str[len++] = t_gnc();
338 static void dump_stab()
344 for (i=0; i<MAX_STAB; i++) {
345 for (tstab=stab[i]; tstab; tstab=tstab->next) {
346 for (j=0; j<tstab->len; j++) {
348 if (c < 0x20 || c > 0x7F) {
349 sprintf(buf, " 0x%x ", c);
357 sprintf(buf, " func=%d len=%d\n\r", tstab->func, tstab->len);
365 * New routine. Add string to string->func mapping table.
367 static void add_smap(char *str, int func)
377 /* errmsg("String for func %d is zero length\n", func); */
380 tstab = (stab_t *)malloc(sizeof(stab_t));
381 memset(tstab, 0, sizeof(stab_t));
383 tstab->str = (char *)malloc(tstab->len + 1);
384 bstrncpy(tstab->str, str, tstab->len + 1);
386 if (tstab->len > num_stab) {
387 printf("stab string too long %d. Max is %d\n", tstab->len, num_stab);
390 tstab->next = stab[tstab->len-1];
391 stab[tstab->len-1] = tstab;
392 /* printf("Add_smap tstab=%x len=%d func=%d tstab->next=%x\n\r", tstab, len,
393 func, tstab->next); */
398 /* Get the next character from the terminal - performs table lookup on
399 the character to do the desired translation */
405 if ((c=t_gnc()) <= 599) { /* IBM generates codes up to 260 */
407 } else if (c > 1000) { /* stuffed function */
408 c -= 1000; /* convert back to function code */
413 /* if we got a screen size escape sequence, read height, width */
416 y = t_gnc() - 0x20; /* y */
417 x = t_gnc() - 0x20; /* x */
424 /* Get a complete input line */
427 input_line(char *string, int length)
429 char curline[2000]; /* edit buffer */
434 poolinit(); /* build line pool */
437 noline = 1; /* no line fetched yet */
438 for (cl=cp=0; cl<length && cl<(int)sizeof(curline); ) {
443 switch (c=(int)input_char()) {
444 case F_RETURN: /* CR */
445 t_sendl("\r\n", 2); /* yes, print it and */
446 goto done; /* get out */
447 case F_CLRSCRN: /* clear screen */
449 t_sendl(curline, cl);
453 if (noline) { /* no line fetched yet */
454 getnext(); /* getnext so getprev gets current */
455 noline = 0; /* we now have line */
457 bstrncpy(curline, getprev(), sizeof(curline));
461 noline = 0; /* mark line fetched */
462 bstrncpy(curline, getnext(), sizeof(curline));
466 insert_space(curline, sizeof(curline));
469 delchr(1, curline, sizeof(curline)); /* delete one character */
471 case F_CSRLFT: /* Backspace */
475 forward(1,curline, sizeof(curline));
477 case F_ERSCHR: /* Rubout */
479 delchr(1, curline, sizeof(curline));
482 t_clrline(0, t_width);
487 forward(next_word(curline),curline, sizeof(curline));
490 backup(prev_word(curline));
493 delchr(next_word(curline), curline, sizeof(curline)); /* delete word */
495 case F_NXTMCH: /* Ctl-X */
497 *string = EOS; /* terminate string */
498 return(c); /* give it to him */
500 /* Note fall through */
503 backup(cp); /* backup to beginning of line */
504 t_clrline(0,t_width); /* erase line */
506 cl = 0; /* reset cursor counter */
513 forward(1,curline, sizeof(curline));
519 case F_TINS: /* toggle insert mode */
520 mode_insert = !mode_insert; /* flip bit */
523 if (c > 255) { /* function key hit */
524 if (cl==0) { /* if first character then */
525 *string = EOS; /* terminate string */
526 return c; /* return it */
528 t_honk_horn(); /* complain */
531 insert_space(curline, sizeof(curline));
533 curline[cp++] = c; /* store character in line being built */
534 t_char((char)c); /* echo character to terminal */
536 cl = cp; /* keep current length */
542 /* If we fall through here rather than goto done, the line is too long
543 simply return what we have now. */
545 curline[cl++] = EOS; /* terminate */
546 bstrncpy(string,curline,length); /* return line to caller */
547 /* Note, put line zaps curline */
548 putline(curline,cl); /* save line for posterity */
549 return 0; /* give it to him/her */
552 /* Insert a space at the current cursor position */
554 insert_space(char *curline, int curline_len)
558 if (cp > cl || cl+1 > curline_len) return;
559 /* Note! source and destination overlap */
560 memmove(&curline[cp+1],&curline[cp],i=cl-cp);
564 forward(i,curline, curline_len);
569 /* Move cursor forward keeping characters under it */
571 forward(int i, char *str, int str_len)
587 /* Backup cursor keeping characters under it */
591 for ( ; i && cp; i--,cp--) {
596 /* Delete the character under the cursor */
598 delchr(int cnt, char *curline, int line_len)
604 if ((i=cl-cp-cnt+1) > 0) {
605 memcpy(&curline[cp], &curline[cp+cnt],i);
607 curline[cl -= cnt] = EOS;
608 t_clrline(0,t_width);
610 forward(i=cl-cp,curline, line_len);
615 /* Determine if character is part of a word */
621 if (c >= '0' && c <= '9')
623 if (c == '$' || c == '%')
628 /* Return number of characters to get to next word */
630 next_word(char *ldb_buf)
637 for ( ; ncp<cl && iswordc(*(ldb_buf+ncp)); ncp++) ;
638 for ( ; ncp<cl && !iswordc(*(ldb_buf+ncp)); ncp++) ;
642 /* Return number of characters to get to previous word */
644 prev_word(char *ldb_buf)
648 if (cp == 0) /* if at begin of line stop now */
650 if (cp > cl) /* if past eol start at eol */
654 /* backup to end of previous word - i.e. skip special chars */
655 for (i=ncp-1; i && !iswordc(*(ldb_buf+i)); i--) ;
656 if (i == 0) { /* at beginning of line? */
657 return cp; /* backup to beginning */
659 /* now move back through word to beginning of word */
660 for ( ; i && iswordc(*(ldb_buf+i)); i--) ;
661 ncp = i+1; /* position to first char of word */
662 if (i==0 && iswordc(*ldb_buf)) /* check for beginning of line */
664 return cp-ncp; /* return count */
667 /* Display new current line */
672 t_clrline(0,t_width);
673 cp = cl = strlen(str);
678 /* Initialize line pool. Split pool into two pieces. */
682 slptr = lptr = (struct lstr *)pool;
691 /* Return pointer to next line in the pool and advance current line pointer */
695 do { /* find next used line */
697 } while (!lptr->used);
698 return (char *)&lptr->line;
701 /* Return pointer to previous line in the pool */
705 do { /* find previous used line */
707 } while (!lptr->used);
708 return (char *)&lptr->line;
712 putline(char *newl, int newlen)
714 struct lstr *nptr; /* points to next line */
717 lptr = slptr; /* get ptr to last line stored */
718 lptr = lptr->nextl; /* advance pointer */
719 if ((char *)lptr-pool+newlen+PHDRL > POOLEN) { /* not enough room */
720 lptr->used = 0; /* delete line */
721 lptr = (struct lstr *)pool; /* start at beginning of buffer */
723 while (lptr->len < newlen+PHDRL) { /* concatenate buffers */
724 nptr = lptr->nextl; /* point to next line */
725 lptr->nextl = nptr->nextl; /* unlink it from list */
726 nptr->nextl->prevl = lptr;
727 lptr->len += nptr->len;
729 if (lptr->len > newlen + 2 * PHDRL) { /* split buffer */
730 nptr = (struct lstr *)((char *)lptr + newlen + PHDRL);
731 /* Appropriate byte alignment - normally 2 byte, but on
732 sparc we need 4 byte alignment, so we always do 4 */
733 if (((long unsigned)nptr & 3) != 0) { /* test four byte alignment */
735 nptr = (struct lstr *)((((long unsigned) p) & ~3) + 4);
737 nptr->len = lptr->len - ((char *)nptr - (char *)lptr);
738 lptr->len -= nptr->len;
739 nptr->nextl = lptr->nextl; /* link in new buffer */
740 lptr->nextl->prevl = nptr;
745 memcpy(&lptr->line,newl,newlen);
746 lptr->used = 1; /* mark line used */
747 slptr = lptr; /* save as stored line */
752 dump(struct lstr *ptr, char *msg)
754 printf("%s buf=%x nextl=%x prevl=%x len=%d used=%d\n",
755 msg,ptr,ptr->nextl,ptr->prevl,ptr->len,ptr->used);
757 printf("line=%s\n",&ptr->line);
759 #endif /* DEBUGOUT */
762 /* Honk horn on terminal */
769 /* Insert line on terminal */
776 /* Delete line from terminal */
783 /* clear line from pos to width */
785 t_clrline(int pos, int width)
787 asclrl(pos, width); /* clear to end of line */
790 /* Helper function to add string preceded by
791 * ESC to smap table */
792 static void add_esc_smap(char *str, int func)
795 buf[0] = 0x1B; /* esc */
796 bstrncpy(buf+1, str, sizeof(buf)-1);
800 /* Set raw mode on terminal file. Basically, get the terminal into a
801 mode in which all characters can be read as they are entered. CBREAK
802 mode is not sufficient.
804 static void rawmode(FILE *input)
807 static char term_buf[2048];
808 static char *term_buffer = term_buf;
809 char *termtype = (char *)getenv("TERM");
811 /* Make sure we are dealing with a terminal */
812 if (!isatty(fileno(input))) {
815 if (tcgetattr(0, &old_term_params) != 0) {
816 printf("conio: Cannot tcgetattr()\n");
819 old_term_params_set = true;
821 t.c_cc[VMIN] = 1; /* satisfy read after 1 char */
823 t.c_iflag &= ~(BRKINT | IGNPAR | PARMRK | INPCK |
824 ISTRIP | ICRNL | IXON | IXOFF | INLCR | IGNCR);
827 t.c_lflag &= ~(ECHO | ECHOE | ECHOK | ECHONL | ICANON |
829 tcflush(0, TCIFLUSH);
830 if (tcsetattr(0, TCSANOW, &t) == -1) {
831 printf("Cannot tcsetattr()\n");
834 /* Defaults, the main program can override these */
835 signal(SIGQUIT, SIG_IGN);
836 signal(SIGHUP, SIG_IGN);
837 // signal(SIGSTOP, SIG_IGN);
838 signal(SIGINT, sigintcatcher);
839 signal(SIGWINCH, SIG_IGN);
840 signal(SIGQUIT, SIG_IGN);
841 signal(SIGCHLD, SIG_IGN);
842 // signal(SIGTSTP, SIG_IGN);
845 printf("Cannot get terminal type.\n");
849 if (tgetent(term_buffer, termtype) < 0) {
850 printf("Cannot get terminal termcap entry.\n");
854 t_width = t_height = -1;
855 t_width = tgetnum("co") - 1;
856 t_height = tgetnum("li");
859 t_cm = (char *)tgetstr("cm", &term_buffer);
860 t_cs = (char *)tgetstr("cl", &term_buffer); /* clear screen */
861 t_cl = (char *)tgetstr("ce", &term_buffer); /* clear line */
862 t_dl = (char *)tgetstr("dl", &term_buffer); /* delete line */
863 t_il = (char *)tgetstr("al", &term_buffer); /* insert line */
864 t_honk = (char *)tgetstr("bl", &term_buffer); /* beep */
865 t_ti = (char *)tgetstr("ti", &term_buffer);
866 t_te = (char *)tgetstr("te", &term_buffer);
867 t_up = (char *)tgetstr("up", &term_buffer);
868 t_do = (char *)tgetstr("do", &term_buffer);
869 t_sf = (char *)tgetstr("sf", &term_buffer);
871 num_stab = MAX_STAB; /* get default stab size */
872 stab = (stab_t **)malloc(sizeof(stab_t *) * num_stab);
873 memset(stab, 0, sizeof(stab_t *) * num_stab);
876 kl = (char *)tgetstr("kl", &term_buffer);
877 kr = (char *)tgetstr("kr", &term_buffer);
878 ku = (char *)tgetstr("ku", &term_buffer);
879 kd = (char *)tgetstr("kd", &term_buffer);
880 kh = (char *)tgetstr("kh", &term_buffer);
881 kb = (char *)tgetstr("kb", &term_buffer);
882 kD = (char *)tgetstr("kD", &term_buffer);
883 kI = (char *)tgetstr("kI", &term_buffer);
884 kN = (char *)tgetstr("kN", &term_buffer);
885 kP = (char *)tgetstr("kP", &term_buffer);
886 kH = (char *)tgetstr("kH", &term_buffer);
887 kE = (char *)tgetstr("kE", &term_buffer);
889 add_smap(kl, F_CSRLFT);
890 add_smap(kr, F_CSRRGT);
891 add_smap(ku, F_CSRUP);
892 add_smap(kd, F_CSRDWN);
893 add_smap(kI, F_TINS);
894 add_smap(kN, F_PAGDWN);
895 add_smap(kP, F_PAGUP);
896 add_smap(kH, F_HOME);
900 add_esc_smap("[A", F_CSRUP);
901 add_esc_smap("[B", F_CSRDWN);
902 add_esc_smap("[C", F_CSRRGT);
903 add_esc_smap("[D", F_CSRLFT);
904 add_esc_smap("[1~", F_HOME);
905 add_esc_smap("[2~", F_TINS);
906 add_esc_smap("[3~", F_DELCHR);
907 add_esc_smap("[4~", F_EOF);
908 add_esc_smap("f", F_NXTWRD);
909 add_esc_smap("b", F_PRVWRD);
913 /* Restore tty mode */
914 static void normode()
916 if (old_term_params_set) {
917 tcsetattr(0, TCSANOW, &old_term_params);
918 old_term_params_set = false;
922 /* Get next character from terminal/script file/unget buffer */
930 /* Get next character from OS */
931 static int t_getch(void)
935 if (read(0, &c, 1) != 1) {
941 /* Send message to terminal - primitive routine */
943 t_sendl(char *msg, int len)
954 t_sendl(msg, strlen(msg)); /* faster than one char at time */
957 /* Send single character to terminal - primitive routine - */
965 static int brkflg = 0; /* set on user break */
967 /* Routine to return true if user types break */
973 /* Clear break flag */
980 /* Interrupt caught here */
981 static void sigintcatcher(int sig)
988 signal(SIGINT, sigintcatcher);
995 signal(SIGINT, sigintcatcher);
999 /* ASCLRL() -- Clear to end of line from current position */
1000 static void asclrl(int pos, int width)
1005 t_send(t_cl); /* use clear to eol function */
1008 if (pos==1 && linsdel_ok) {
1009 t_delete_line(); /* delete line */
1010 t_insert_line(); /* reinsert it */
1013 for (i=1; i<=width-pos+1; i++)
1014 t_char(' '); /* last resort, blank it out */
1015 for (i=1; i<=width-pos+1; i++) /* backspace to original position */
1022 /* ASCURS -- Set cursor position */
1023 static void ascurs(int y, int x)
1025 t_send((char *)tgoto(t_cm, x, y));
1029 /* ASCLRS -- Clear whole screen */
1030 static void asclrs()
1038 /* ASINSL -- insert new line after cursor */
1039 static void asinsl()
1041 t_clrline(0, t_width);
1042 t_send(t_il); /* insert before */
1045 /* ASDELL -- Delete line at cursor */
1046 static void asdell()