2 * Copyright (C) 1984-2015 Mark Nudelman
4 * You may distribute under the terms of either the GNU General Public
5 * License or the Less License, as specified in the README file.
7 * For more information, see the README file.
12 * Routines which deal with the characteristics of the terminal.
13 * Uses termcap to be as terminal-independent as possible.
21 #if MSDOS_COMPILER==MSOFTC
24 #if MSDOS_COMPILER==BORLANDC || MSDOS_COMPILER==DJGPPC
26 #if MSDOS_COMPILER==DJGPPC
31 #if MSDOS_COMPILER==WIN32C
41 #include <sys/ioctl.h>
44 #if HAVE_TERMIOS_H && HAVE_TERMIOS_FUNCS
65 #include <sys/signal.h>
69 #include <sys/stream.h>
75 #endif /* MSDOS_COMPILER */
78 * Check for broken termios package that forces you to manually
79 * set the line discipline.
82 #define MUST_SET_LINE_DISCIPLINE 1
84 #define MUST_SET_LINE_DISCIPLINE 0
88 #define DEFAULT_TERM "ansi"
89 static char *windowid;
91 #define DEFAULT_TERM "unknown"
94 #if MSDOS_COMPILER==MSOFTC
95 static int videopages;
96 static long msec_loops;
97 static int flash_created = 0;
98 #define SETCOLORS(fg,bg) { _settextcolor(fg); _setbkcolor(bg); }
101 #if MSDOS_COMPILER==BORLANDC
102 static unsigned short *whitescreen;
103 static int flash_created = 0;
105 #if MSDOS_COMPILER==BORLANDC || MSDOS_COMPILER==DJGPPC
106 #define _settextposition(y,x) gotoxy(x,y)
107 #define _clearscreen(m) clrscr()
108 #define _outtext(s) cputs(s)
109 #define SETCOLORS(fg,bg) { textcolor(fg); textbackground(bg); }
110 extern int sc_height;
113 #if MSDOS_COMPILER==WIN32C
120 static int keyCount = 0;
121 static WORD curr_attr;
122 static int pending_scancode = 0;
123 static WORD *whitescreen;
125 static HANDLE con_out_save = INVALID_HANDLE_VALUE; /* previous console */
126 static HANDLE con_out_ours = INVALID_HANDLE_VALUE; /* our own */
127 HANDLE con_out = INVALID_HANDLE_VALUE; /* current console */
130 static void win32_init_term();
131 static void win32_deinit_term();
133 #define FG_COLORS (FOREGROUND_RED | FOREGROUND_GREEN | FOREGROUND_BLUE | FOREGROUND_INTENSITY)
134 #define BG_COLORS (BACKGROUND_RED | BACKGROUND_GREEN | BACKGROUND_BLUE | BACKGROUND_INTENSITY)
135 #define MAKEATTR(fg,bg) ((WORD)((fg)|((bg)<<4)))
136 #define SETCOLORS(fg,bg) { curr_attr = MAKEATTR(fg,bg); \
137 if (SetConsoleTextAttribute(con_out, curr_attr) == 0) \
138 error("SETCOLORS failed"); }
142 public int nm_fg_color; /* Color of normal text */
143 public int nm_bg_color;
144 public int bo_fg_color; /* Color of bold text */
145 public int bo_bg_color;
146 public int ul_fg_color; /* Color of underlined text */
147 public int ul_bg_color;
148 public int so_fg_color; /* Color of standout text */
149 public int so_bg_color;
150 public int bl_fg_color; /* Color of blinking text */
151 public int bl_bg_color;
152 static int sy_fg_color; /* Color of system text (before less) */
153 static int sy_bg_color;
158 * Strings passed to tputs() to do various terminal functions.
161 *sc_pad, /* Pad string */
162 *sc_home, /* Cursor home */
163 *sc_addline, /* Add line, scroll down following lines */
164 *sc_lower_left, /* Cursor to last line, first column */
165 *sc_return, /* Cursor to beginning of current line */
166 *sc_move, /* General cursor positioning */
167 *sc_clear, /* Clear screen */
168 *sc_eol_clear, /* Clear to end of line */
169 *sc_eos_clear, /* Clear to end of screen */
170 *sc_s_in, /* Enter standout (highlighted) mode */
171 *sc_s_out, /* Exit standout mode */
172 *sc_u_in, /* Enter underline mode */
173 *sc_u_out, /* Exit underline mode */
174 *sc_b_in, /* Enter bold mode */
175 *sc_b_out, /* Exit bold mode */
176 *sc_bl_in, /* Enter blink mode */
177 *sc_bl_out, /* Exit blink mode */
178 *sc_visual_bell, /* Visual bell (flash screen) sequence */
179 *sc_backspace, /* Backspace cursor */
180 *sc_s_keypad, /* Start keypad mode */
181 *sc_e_keypad, /* End keypad mode */
182 *sc_init, /* Startup terminal initialization */
183 *sc_deinit; /* Exit terminal de-initialization */
186 static int init_done = 0;
188 public int auto_wrap; /* Terminal does \r\n when write past margin */
189 public int ignaw; /* Terminal ignores \n immediately after wrap */
190 public int erase_char; /* The user's erase char */
191 public int erase2_char; /* The user's other erase char */
192 public int kill_char; /* The user's line-kill char */
193 public int werase_char; /* The user's word-erase char */
194 public int sc_width, sc_height; /* Height & width of screen */
195 public int bo_s_width, bo_e_width; /* Printing width of boldface seq */
196 public int ul_s_width, ul_e_width; /* Printing width of underline seq */
197 public int so_s_width, so_e_width; /* Printing width of standout seq */
198 public int bl_s_width, bl_e_width; /* Printing width of blink seq */
199 public int above_mem, below_mem; /* Memory retained above/below screen */
200 public int can_goto_line; /* Can move cursor to any line */
201 public int clear_bg; /* Clear fills with background color */
202 public int missing_cap = 0; /* Some capability is missing */
204 static int attrmode = AT_NORMAL;
208 static char *cheaper(char *t1, char *t2, char *def);
209 static void tmodes(char *incap, char *outcap, char **instr, char **outstr,
210 char *def_instr, char *def_outstr, char **spp);
214 * These two variables are sometimes defined in,
215 * and needed by, the termcap library.
217 #if MUST_DEFINE_OSPEED
218 extern short ospeed; /* Terminal output baud rate */
219 extern char PC; /* Pad character */
226 extern int quiet; /* If VERY_QUIET, use visual bell for bell */
227 extern int no_back_scroll;
230 extern int no_keypad;
233 extern int screen_trashed;
235 extern int top_scroll;
238 extern int hilite_search;
241 extern char *tgetstr();
242 extern char *tgoto();
246 * Change terminal to "raw mode", or restore to "normal" mode.
248 * 1. An outstanding read will complete on receipt of a single keystroke.
249 * 2. Input is not echoed.
250 * 3. On output, \n is mapped to \r\n.
251 * 4. \t is NOT expanded into spaces.
252 * 5. Signal-causing characters such as ctrl-C (interrupt),
253 * etc. are NOT disabled.
254 * It doesn't matter whether an input \n is mapped to \r, or vice versa.
259 static int curr_on = 0;
263 erase2_char = '\b'; /* in case OS doesn't know about erase2 */
264 #if HAVE_TERMIOS_H && HAVE_TERMIOS_FUNCS
267 static struct termios save_term;
268 static int saved_term = 0;
273 * Get terminal modes.
278 * Save modes and set certain variables dependent on modes.
286 switch (cfgetospeed(&s))
289 case B0: ospeed = 0; break;
292 case B50: ospeed = 1; break;
295 case B75: ospeed = 2; break;
298 case B110: ospeed = 3; break;
301 case B134: ospeed = 4; break;
304 case B150: ospeed = 5; break;
307 case B200: ospeed = 6; break;
310 case B300: ospeed = 7; break;
313 case B600: ospeed = 8; break;
316 case B1200: ospeed = 9; break;
319 case B1800: ospeed = 10; break;
322 case B2400: ospeed = 11; break;
325 case B4800: ospeed = 12; break;
328 case B9600: ospeed = 13; break;
331 case EXTA: ospeed = 14; break;
334 case EXTB: ospeed = 15; break;
337 case B57600: ospeed = 16; break;
340 case B115200: ospeed = 17; break;
345 erase_char = s.c_cc[VERASE];
347 erase2_char = s.c_cc[VERASE2];
349 kill_char = s.c_cc[VKILL];
351 werase_char = s.c_cc[VWERASE];
353 werase_char = CONTROL('W');
357 * Set the modes to the way we want them.
419 #if MUST_SET_LINE_DISCIPLINE
421 * System's termios is broken; need to explicitly
422 * request TERMIODISC line discipline.
424 s.c_line = TERMIODISC;
429 * Restore saved modes.
436 tcsetattr(tty, TCSADRAIN, &s);
437 #if MUST_SET_LINE_DISCIPLINE
441 * Broken termios *ignores* any line discipline
442 * except TERMIODISC. A different old line discipline
443 * is therefore not restored, yet. Restore the old
444 * line discipline by hand.
446 ioctl(tty, TIOCSETD, &save_term.c_line);
454 static struct termio save_term;
455 static int saved_term = 0;
460 * Get terminal modes.
462 ioctl(tty, TCGETA, &s);
465 * Save modes and set certain variables dependent on modes.
473 ospeed = s.c_cflag & CBAUD;
475 erase_char = s.c_cc[VERASE];
476 kill_char = s.c_cc[VKILL];
478 werase_char = s.c_cc[VWERASE];
480 werase_char = CONTROL('W');
484 * Set the modes to the way we want them.
486 s.c_lflag &= ~(ICANON|ECHO|ECHOE|ECHOK|ECHONL);
487 s.c_oflag |= (OPOST|ONLCR|TAB3);
488 s.c_oflag &= ~(OCRNL|ONOCR|ONLRET);
494 * Restore saved modes.
498 ioctl(tty, TCSETAW, &s);
504 static struct sgttyb save_term;
505 static int saved_term = 0;
510 * Get terminal modes.
512 ioctl(tty, TIOCGETP, &s);
515 * Save modes and set certain variables dependent on modes.
523 ospeed = s.sg_ospeed;
525 erase_char = s.sg_erase;
526 kill_char = s.sg_kill;
527 werase_char = CONTROL('W');
530 * Set the modes to the way we want them.
532 s.sg_flags |= CBREAK;
533 s.sg_flags &= ~(ECHO|XTABS);
537 * Restore saved modes.
541 ioctl(tty, TIOCSETN, &s);
547 static struct sgbuf save_term;
548 static int saved_term = 0;
553 * Get terminal modes.
558 * Save modes and set certain variables dependent on modes.
565 erase_char = s.sg_bspch;
566 kill_char = s.sg_dlnch;
567 werase_char = CONTROL('W');
570 * Set the modes to the way we want them.
579 * Restore saved modes.
586 /* MS-DOS, Windows, or OS2 */
589 LSIGNAL(SIGINT, SIG_IGN);
592 #if MSDOS_COMPILER==DJGPPC
593 kill_char = CONTROL('U');
595 * So that when we shell out or run another program, its
596 * stdin is in cooked mode. We do not switch stdin to binary
597 * mode if fd0 is zero, since that means we were called before
598 * tty was reopened in open_getchr, in which case we would be
599 * changing the original stdin device outside less.
602 setmode(0, on ? O_BINARY : O_TEXT);
606 werase_char = CONTROL('W');
616 * Some glue to prevent calling termcap functions if tgetent() failed.
621 ltget_env(char *capname)
626 s = lgetenv("LESS_TERMCAP_DEBUG");
627 if (s != NULL && *s != '\0')
629 struct env { struct env *next; char *name; char *value; };
630 static struct env *envs = NULL;
632 for (p = envs; p != NULL; p = p->next)
633 if (strcmp(p->name, capname) == 0)
635 p = (struct env *) ecalloc(1, sizeof(struct env));
636 p->name = save(capname);
637 p->value = (char *) ecalloc(strlen(capname)+3, sizeof(char));
638 sprintf(p->value, "<%s>", capname);
643 strcpy(name, "LESS_TERMCAP_");
644 strcat(name, capname);
645 return (lgetenv(name));
649 ltgetflag(char *capname)
653 if ((s = ltget_env(capname)) != NULL)
654 return (*s != '\0' && *s != '0');
657 return (tgetflag(capname));
661 ltgetnum(char *capname)
665 if ((s = ltget_env(capname)) != NULL)
669 return (tgetnum(capname));
673 ltgetstr(char *capname, char **pp)
677 if ((s = ltget_env(capname)) != NULL)
681 return (tgetstr(capname, pp));
683 #endif /* MSDOS_COMPILER */
686 * Get size of the output screen.
698 #define DEF_SC_WIDTH 80
700 #define DEF_SC_HEIGHT 25
702 #define DEF_SC_HEIGHT 24
706 sys_width = sys_height = 0;
708 #if MSDOS_COMPILER==MSOFTC
710 struct videoconfig w;
712 sys_height = w.numtextrows;
713 sys_width = w.numtextcols;
716 #if MSDOS_COMPILER==BORLANDC || MSDOS_COMPILER==DJGPPC
720 sys_height = w.screenheight;
721 sys_width = w.screenwidth;
724 #if MSDOS_COMPILER==WIN32C
726 CONSOLE_SCREEN_BUFFER_INFO scr;
727 GetConsoleScreenBufferInfo(con_out, &scr);
728 sys_height = scr.srWindow.Bottom - scr.srWindow.Top + 1;
729 sys_width = scr.srWindow.Right - scr.srWindow.Left + 1;
739 * When using terminal emulators for XFree86/OS2, the
740 * _scrsize function does not work well.
741 * Call the scrsize.exe program to get the window size.
743 windowid = getenv("WINDOWID");
744 if (windowid != NULL)
746 FILE *fd = popen("scrsize", "rt");
750 fscanf(fd, "%i %i", &w, &h);
764 if (ioctl(2, TIOCGWINSZ, &w) == 0)
767 sys_height = w.ws_row;
769 sys_width = w.ws_col;
776 if (ioctl(2, WIOCGETD, &w) == 0)
779 sys_height = w.uw_height / w.uw_vs;
781 sys_width = w.uw_width / w.uw_hs;
792 sc_height = sys_height;
793 else if ((s = lgetenv("LINES")) != NULL)
796 else if ((n = ltgetnum("li")) > 0)
800 sc_height = DEF_SC_HEIGHT;
803 sc_width = sys_width;
804 else if ((s = lgetenv("COLUMNS")) != NULL)
807 else if ((n = ltgetnum("co")) > 0)
811 sc_width = DEF_SC_WIDTH;
814 #if MSDOS_COMPILER==MSOFTC
816 * Figure out how many empty loops it takes to delay a millisecond.
824 * Get synchronized at the start of a tick.
827 while (clock() == start)
830 * Now count loops till the next tick.
834 while (clock() == start)
837 * Convert from (loops per clock) to (loops per millisecond).
839 msec_loops *= CLOCKS_PER_SEC;
844 * Delay for a specified number of milliseconds.
849 static long delay_dummy = 0;
860 for (i = 0; i < msec_loops; i++)
863 * Make it look like we're doing something here,
864 * so the optimizer doesn't remove the whole loop.
873 * Return the characters actually input by a "special" key.
876 special_key_str(int key)
878 static char tbuf[40];
880 #if MSDOS_COMPILER || OS2
881 static char k_right[] = { '\340', PCK_RIGHT, 0 };
882 static char k_left[] = { '\340', PCK_LEFT, 0 };
883 static char k_ctl_right[] = { '\340', PCK_CTL_RIGHT, 0 };
884 static char k_ctl_left[] = { '\340', PCK_CTL_LEFT, 0 };
885 static char k_insert[] = { '\340', PCK_INSERT, 0 };
886 static char k_delete[] = { '\340', PCK_DELETE, 0 };
887 static char k_ctl_delete[] = { '\340', PCK_CTL_DELETE, 0 };
888 static char k_ctl_backspace[] = { '\177', 0 };
889 static char k_home[] = { '\340', PCK_HOME, 0 };
890 static char k_end[] = { '\340', PCK_END, 0 };
891 static char k_up[] = { '\340', PCK_UP, 0 };
892 static char k_down[] = { '\340', PCK_DOWN, 0 };
893 static char k_backtab[] = { '\340', PCK_SHIFT_TAB, 0 };
894 static char k_pagedown[] = { '\340', PCK_PAGEDOWN, 0 };
895 static char k_pageup[] = { '\340', PCK_PAGEUP, 0 };
896 static char k_f1[] = { '\340', PCK_F1, 0 };
906 * If windowid is not NULL, assume less is executed in
907 * the XFree86 environment.
910 s = windowid ? ltgetstr("kr", &sp) : k_right;
913 s = windowid ? ltgetstr("kl", &sp) : k_left;
916 s = windowid ? ltgetstr("ku", &sp) : k_up;
919 s = windowid ? ltgetstr("kd", &sp) : k_down;
922 s = windowid ? ltgetstr("kP", &sp) : k_pageup;
925 s = windowid ? ltgetstr("kN", &sp) : k_pagedown;
928 s = windowid ? ltgetstr("kh", &sp) : k_home;
931 s = windowid ? ltgetstr("@7", &sp) : k_end;
936 s = ltgetstr("kD", &sp);
976 #if MSDOS_COMPILER || OS2
980 case SK_CTL_LEFT_ARROW:
983 case SK_CTL_RIGHT_ARROW:
986 case SK_CTL_BACKSPACE:
1000 s = ltgetstr("kr", &sp);
1003 s = ltgetstr("kl", &sp);
1006 s = ltgetstr("ku", &sp);
1009 s = ltgetstr("kd", &sp);
1012 s = ltgetstr("kP", &sp);
1015 s = ltgetstr("kN", &sp);
1018 s = ltgetstr("kh", &sp);
1021 s = ltgetstr("@7", &sp);
1024 s = ltgetstr("kD", &sp);
1034 tbuf[0] = CONTROL('K');
1045 * Get terminal capabilities via termcap.
1056 * Set up default colors.
1057 * The xx_s_width and xx_e_width vars are already initialized to 0.
1059 #if MSDOS_COMPILER==MSOFTC
1060 sy_bg_color = _getbkcolor();
1061 sy_fg_color = _gettextcolor();
1064 #if MSDOS_COMPILER==BORLANDC || MSDOS_COMPILER==DJGPPC
1068 sy_bg_color = (w.attribute >> 4) & 0x0F;
1069 sy_fg_color = (w.attribute >> 0) & 0x0F;
1072 #if MSDOS_COMPILER==WIN32C
1075 CONSOLE_SCREEN_BUFFER_INFO scr;
1077 con_out_save = con_out = GetStdHandle(STD_OUTPUT_HANDLE);
1079 * Always open stdin in binary. Note this *must* be done
1080 * before any file operations have been done on fd0.
1083 GetConsoleScreenBufferInfo(con_out, &scr);
1084 ReadConsoleOutputAttribute(con_out, &curr_attr,
1085 1, scr.dwCursorPosition, &nread);
1086 sy_bg_color = (curr_attr & BG_COLORS) >> 4; /* normalize */
1087 sy_fg_color = curr_attr & FG_COLORS;
1092 nm_fg_color = sy_fg_color;
1093 nm_bg_color = sy_bg_color;
1104 * Get size of the screen.
1110 #else /* !MSDOS_COMPILER */
1115 char termbuf[TERMBUF_SIZE];
1117 static char sbuf[TERMSBUF_SIZE];
1121 * Make sure the termcap database is available.
1123 sp = lgetenv("TERMCAP");
1124 if (sp == NULL || *sp == '\0')
1127 if ((sp = homefile("termcap.dat")) != NULL)
1129 termcap = (char *) ecalloc(strlen(sp)+9, sizeof(char));
1130 sprintf(termcap, "TERMCAP=%s", sp);
1137 * Find out what kind of terminal this is.
1139 if ((term = lgetenv("TERM")) == NULL)
1140 term = DEFAULT_TERM;
1142 if (tgetent(termbuf, term) != TGETENT_OK)
1144 if (ltgetflag("hc"))
1148 * Get size of the screen.
1153 auto_wrap = ltgetflag("am");
1154 ignaw = ltgetflag("xn");
1155 above_mem = ltgetflag("da");
1156 below_mem = ltgetflag("db");
1157 clear_bg = ltgetflag("ut");
1160 * Assumes termcap variable "sg" is the printing width of:
1161 * the standout sequence, the end standout sequence,
1162 * the underline sequence, the end underline sequence,
1163 * the boldface sequence, and the end boldface sequence.
1165 if ((so_s_width = ltgetnum("sg")) < 0)
1167 so_e_width = so_s_width;
1169 bo_s_width = bo_e_width = so_s_width;
1170 ul_s_width = ul_e_width = so_s_width;
1171 bl_s_width = bl_e_width = so_s_width;
1174 if (so_s_width > 0 || so_e_width > 0)
1176 * Disable highlighting by default on magic cookie terminals.
1177 * Turning on highlighting might change the displayed width
1178 * of a line, causing the display to get messed up.
1179 * The user can turn it back on with -g,
1180 * but she won't like the results.
1186 * Get various string-valued capabilities.
1191 sc_pad = ltgetstr("pc", &sp);
1196 sc_s_keypad = ltgetstr("ks", &sp);
1197 if (sc_s_keypad == NULL)
1199 sc_e_keypad = ltgetstr("ke", &sp);
1200 if (sc_e_keypad == NULL)
1203 sc_init = ltgetstr("ti", &sp);
1204 if (sc_init == NULL)
1207 sc_deinit= ltgetstr("te", &sp);
1208 if (sc_deinit == NULL)
1211 sc_eol_clear = ltgetstr("ce", &sp);
1212 if (sc_eol_clear == NULL || *sc_eol_clear == '\0')
1218 sc_eos_clear = ltgetstr("cd", &sp);
1219 if (below_mem && (sc_eos_clear == NULL || *sc_eos_clear == '\0'))
1225 sc_clear = ltgetstr("cl", &sp);
1226 if (sc_clear == NULL || *sc_clear == '\0')
1232 sc_move = ltgetstr("cm", &sp);
1233 if (sc_move == NULL || *sc_move == '\0')
1236 * This is not an error here, because we don't
1237 * always need sc_move.
1238 * We need it only if we don't have home or lower-left.
1245 tmodes("so", "se", &sc_s_in, &sc_s_out, "", "", &sp);
1246 tmodes("us", "ue", &sc_u_in, &sc_u_out, sc_s_in, sc_s_out, &sp);
1247 tmodes("md", "me", &sc_b_in, &sc_b_out, sc_s_in, sc_s_out, &sp);
1248 tmodes("mb", "me", &sc_bl_in, &sc_bl_out, sc_s_in, sc_s_out, &sp);
1250 sc_visual_bell = ltgetstr("vb", &sp);
1251 if (sc_visual_bell == NULL)
1252 sc_visual_bell = "";
1254 if (ltgetflag("bs"))
1255 sc_backspace = "\b";
1258 sc_backspace = ltgetstr("bc", &sp);
1259 if (sc_backspace == NULL || *sc_backspace == '\0')
1260 sc_backspace = "\b";
1264 * Choose between using "ho" and "cm" ("home" and "cursor move")
1265 * to move the cursor to the upper left corner of the screen.
1267 t1 = ltgetstr("ho", &sp);
1270 if (*sc_move == '\0')
1274 strcpy(sp, tgoto(sc_move, 0, 0));
1276 sp += strlen(sp) + 1;
1278 sc_home = cheaper(t1, t2, "|\b^");
1281 * Choose between using "ll" and "cm" ("lower left" and "cursor move")
1282 * to move the cursor to the lower left corner of the screen.
1284 t1 = ltgetstr("ll", &sp);
1287 if (*sc_move == '\0')
1291 strcpy(sp, tgoto(sc_move, 0, sc_height-1));
1293 sp += strlen(sp) + 1;
1295 sc_lower_left = cheaper(t1, t2, "\r");
1298 * Get carriage return string.
1300 sc_return = ltgetstr("cr", &sp);
1301 if (sc_return == NULL)
1305 * Choose between using "al" or "sr" ("add line" or "scroll reverse")
1306 * to add a line at the top of the screen.
1308 t1 = ltgetstr("al", &sp);
1311 t2 = ltgetstr("sr", &sp);
1315 if (*t1 == '\0' && *t2 == '\0')
1322 sc_addline = cheaper(t1, t2, "");
1323 if (*sc_addline == '\0')
1326 * Force repaint on any backward movement.
1330 #endif /* MSDOS_COMPILER */
1335 * Return the cost of displaying a termcap string.
1336 * We use the trick of calling tputs, but as a char printing function
1337 * we give it inc_costcount, which just increments "costcount".
1338 * This tells us how many chars would be printed by using this string.
1339 * {{ Couldn't we just use strlen? }}
1341 static int costcount;
1345 inc_costcount(int c)
1355 tputs(t, sc_height, inc_costcount);
1360 * Return the "best" of the two given termcap strings.
1361 * The best, if both exist, is the one with the lower
1362 * cost (see cost() function).
1365 cheaper(char *t1, char *t2, char *def)
1367 if (*t1 == '\0' && *t2 == '\0')
1376 if (cost(t1) < cost(t2))
1382 tmodes(char *incap, char *outcap, char **instr, char **outstr, char *def_instr,
1383 char *def_outstr, char **spp)
1385 *instr = ltgetstr(incap, spp);
1390 *outstr = def_outstr;
1394 *outstr = ltgetstr(outcap, spp);
1395 if (*outstr == NULL)
1396 /* No specific out capability; use "me". */
1397 *outstr = ltgetstr("me", spp);
1398 if (*outstr == NULL)
1399 /* Don't even have "me"; use a null string. */
1403 #endif /* MSDOS_COMPILER */
1407 * Below are the functions which perform all the
1408 * terminal-specific screen manipulation.
1414 #if MSDOS_COMPILER==WIN32C
1416 _settextposition(int row, int col)
1419 CONSOLE_SCREEN_BUFFER_INFO csbi;
1421 GetConsoleScreenBufferInfo(con_out, &csbi);
1422 cpos.X = csbi.srWindow.Left + (col - 1);
1423 cpos.Y = csbi.srWindow.Top + (row - 1);
1424 SetConsoleCursorPosition(con_out, cpos);
1429 * Initialize the screen to the correct color at startup.
1434 SETCOLORS(nm_fg_color, nm_bg_color);
1437 * This clears the screen at startup. This is different from
1438 * the behavior of other versions of less. Disable it for now.
1445 * Create a complete, blank screen using "normal" colors.
1447 SETCOLORS(nm_fg_color, nm_bg_color);
1448 blanks = (char *) ecalloc(width+1, sizeof(char));
1449 for (col = 0; col < sc_width; col++)
1451 blanks[sc_width] = '\0';
1452 for (row = 0; row < sc_height; row++)
1459 #if MSDOS_COMPILER==WIN32C
1462 * Termcap-like init with a private win32 console.
1465 win32_init_term(void)
1467 CONSOLE_SCREEN_BUFFER_INFO scr;
1470 if (con_out_save == INVALID_HANDLE_VALUE)
1473 GetConsoleScreenBufferInfo(con_out_save, &scr);
1475 if (con_out_ours == INVALID_HANDLE_VALUE)
1478 * Create our own screen buffer, so that we
1479 * may restore the original when done.
1481 con_out_ours = CreateConsoleScreenBuffer(
1482 GENERIC_WRITE | GENERIC_READ,
1483 FILE_SHARE_WRITE | FILE_SHARE_READ,
1484 (LPSECURITY_ATTRIBUTES) NULL,
1485 CONSOLE_TEXTMODE_BUFFER,
1489 size.X = scr.srWindow.Right - scr.srWindow.Left + 1;
1490 size.Y = scr.srWindow.Bottom - scr.srWindow.Top + 1;
1491 SetConsoleScreenBufferSize(con_out_ours, size);
1492 SetConsoleActiveScreenBuffer(con_out_ours);
1493 con_out = con_out_ours;
1497 * Restore the startup console.
1502 if (con_out_save == INVALID_HANDLE_VALUE)
1505 (void) CloseHandle(con_out_ours);
1506 SetConsoleActiveScreenBuffer(con_out_save);
1507 con_out = con_out_save;
1513 * Initialize terminal
1520 tputs(sc_init, sc_height, putchr);
1522 tputs(sc_s_keypad, sc_height, putchr);
1528 * This is nice to terminals with no alternate screen,
1529 * but with saved scrolled-off-the-top lines. This way,
1530 * no previous line is lost, but we start with a whole
1531 * screen to ourself.
1533 for (i = 1; i < sc_height; i++)
1538 #if MSDOS_COMPILER==WIN32C
1549 * Deinitialize terminal
1558 tputs(sc_e_keypad, sc_height, putchr);
1560 tputs(sc_deinit, sc_height, putchr);
1562 /* Restore system colors. */
1563 SETCOLORS(sy_fg_color, sy_bg_color);
1564 #if MSDOS_COMPILER==WIN32C
1566 win32_deinit_term();
1568 /* Need clreol to make SETCOLORS take effect. */
1576 * Home cursor (move to upper left corner of screen).
1582 tputs(sc_home, 1, putchr);
1585 _settextposition(1,1);
1590 * Add a blank line (called with cursor at home).
1591 * Should scroll the display down.
1597 tputs(sc_addline, sc_height, putchr);
1600 #if MSDOS_COMPILER==MSOFTC
1601 _scrolltextwindow(_GSCROLLDOWN);
1602 _settextposition(1,1);
1604 #if MSDOS_COMPILER==BORLANDC || MSDOS_COMPILER==DJGPPC
1605 movetext(1,1, sc_width,sc_height-1, 1,2);
1609 #if MSDOS_COMPILER==WIN32C
1612 SMALL_RECT rcSrc, rcClip;
1614 CONSOLE_SCREEN_BUFFER_INFO csbi;
1616 GetConsoleScreenBufferInfo(con_out,&csbi);
1618 /* The clip rectangle is the entire visible screen. */
1619 rcClip.Left = csbi.srWindow.Left;
1620 rcClip.Top = csbi.srWindow.Top;
1621 rcClip.Right = csbi.srWindow.Right;
1622 rcClip.Bottom = csbi.srWindow.Bottom;
1624 /* The source rectangle is the visible screen minus the last line. */
1628 /* Move the top left corner of the source window down one row. */
1629 new_org.X = rcSrc.Left;
1630 new_org.Y = rcSrc.Top + 1;
1632 /* Fill the right character and attributes. */
1633 fillchar.Char.AsciiChar = ' ';
1634 curr_attr = MAKEATTR(nm_fg_color, nm_bg_color);
1635 fillchar.Attributes = curr_attr;
1636 ScrollConsoleScreenBuffer(con_out, &rcSrc, &rcClip, new_org, &fillchar);
1637 _settextposition(1,1);
1647 * Remove the n topmost lines and scroll everything below it in the
1648 * window upward. This is needed to stop leaking the topmost line
1649 * into the scrollback buffer when we go down-one-line (in WIN32).
1654 #if MSDOS_COMPILER==WIN32C
1655 SMALL_RECT rcSrc, rcClip;
1658 CONSOLE_SCREEN_BUFFER_INFO csbi; /* to get buffer info */
1660 if (n >= sc_height - 1)
1669 GetConsoleScreenBufferInfo(con_out, &csbi);
1671 /* Get the extent of all-visible-rows-but-the-last. */
1672 rcSrc.Left = csbi.srWindow.Left;
1673 rcSrc.Top = csbi.srWindow.Top + n;
1674 rcSrc.Right = csbi.srWindow.Right;
1675 rcSrc.Bottom = csbi.srWindow.Bottom;
1677 /* Get the clip rectangle. */
1678 rcClip.Left = rcSrc.Left;
1679 rcClip.Top = csbi.srWindow.Top;
1680 rcClip.Right = rcSrc.Right;
1681 rcClip.Bottom = rcSrc.Bottom ;
1683 /* Move the source window up n rows. */
1684 new_org.X = rcSrc.Left;
1685 new_org.Y = rcSrc.Top - n;
1687 /* Fill the right character and attributes. */
1688 fillchar.Char.AsciiChar = ' ';
1689 curr_attr = MAKEATTR(nm_fg_color, nm_bg_color);
1690 fillchar.Attributes = curr_attr;
1692 ScrollConsoleScreenBuffer(con_out, &rcSrc, &rcClip, new_org, &fillchar);
1694 /* Position cursor on first blank line. */
1695 goto_line(sc_height - n - 1);
1700 #if MSDOS_COMPILER==WIN32C
1708 * This will clear only the currently visible rows of the NT
1709 * console buffer, which means none of the precious scrollback
1710 * rows are touched making for faster scrolling. Note that, if
1711 * the window has fewer columns than the console buffer (i.e.
1712 * there is a horizontal scrollbar as well), the entire width
1713 * of the visible rows will be cleared.
1718 CONSOLE_SCREEN_BUFFER_INFO csbi;
1720 /* get the number of cells in the current buffer */
1721 GetConsoleScreenBufferInfo(con_out, &csbi);
1722 winsz = csbi.dwSize.X * (csbi.srWindow.Bottom - csbi.srWindow.Top + 1);
1724 topleft.Y = csbi.srWindow.Top;
1726 curr_attr = MAKEATTR(nm_fg_color, nm_bg_color);
1727 FillConsoleOutputCharacter(con_out, ' ', winsz, topleft, &nchars);
1728 FillConsoleOutputAttribute(con_out, curr_attr, winsz, topleft, &nchars);
1732 * Remove the n topmost lines and scroll everything below it in the
1736 win32_scroll_up(int n)
1738 SMALL_RECT rcSrc, rcClip;
1744 CONSOLE_SCREEN_BUFFER_INFO csbi;
1749 if (n >= sc_height - 1)
1752 _settextposition(1,1);
1756 /* Get the extent of what will remain visible after scrolling. */
1757 GetConsoleScreenBufferInfo(con_out, &csbi);
1758 rcSrc.Left = csbi.srWindow.Left;
1759 rcSrc.Top = csbi.srWindow.Top + n;
1760 rcSrc.Right = csbi.srWindow.Right;
1761 rcSrc.Bottom = csbi.srWindow.Bottom;
1763 /* Get the clip rectangle. */
1764 rcClip.Left = rcSrc.Left;
1765 rcClip.Top = csbi.srWindow.Top;
1766 rcClip.Right = rcSrc.Right;
1767 rcClip.Bottom = rcSrc.Bottom ;
1769 /* Move the source text to the top of the screen. */
1770 new_org.X = rcSrc.Left;
1771 new_org.Y = rcClip.Top;
1773 /* Fill the right character and attributes. */
1774 fillchar.Char.AsciiChar = ' ';
1775 fillchar.Attributes = MAKEATTR(nm_fg_color, nm_bg_color);
1777 /* Scroll the window. */
1778 SetConsoleTextAttribute(con_out, fillchar.Attributes);
1779 ScrollConsoleScreenBuffer(con_out, &rcSrc, &rcClip, new_org, &fillchar);
1781 /* Clear remaining lines at bottom. */
1782 topleft.X = csbi.dwCursorPosition.X;
1783 topleft.Y = rcSrc.Bottom - n;
1784 size = (n * csbi.dwSize.X) + (rcSrc.Right - topleft.X);
1785 FillConsoleOutputCharacter(con_out, ' ', size, topleft,
1787 FillConsoleOutputAttribute(con_out, fillchar.Attributes, size, topleft,
1789 SetConsoleTextAttribute(con_out, curr_attr);
1791 /* Move cursor n lines up from where it was. */
1792 csbi.dwCursorPosition.Y -= n;
1793 SetConsoleCursorPosition(con_out, csbi.dwCursorPosition);
1798 * Move cursor to lower left corner of screen.
1804 tputs(sc_lower_left, 1, putchr);
1807 _settextposition(sc_height, 1);
1812 * Move cursor to left position of current line.
1818 tputs(sc_return, 1, putchr);
1822 #if MSDOS_COMPILER==WIN32C
1824 CONSOLE_SCREEN_BUFFER_INFO scr;
1825 GetConsoleScreenBufferInfo(con_out, &scr);
1826 row = scr.dwCursorPosition.Y - scr.srWindow.Top + 1;
1829 #if MSDOS_COMPILER==BORLANDC || MSDOS_COMPILER==DJGPPC
1833 struct rccoord tpos = _gettextposition();
1838 _settextposition(row, 1);
1843 * Check if the console size has changed and reset internals
1844 * (in lieu of SIGWINCH for WIN32).
1849 #if MSDOS_COMPILER==WIN32C
1850 CONSOLE_SCREEN_BUFFER_INFO scr;
1853 if (con_out == INVALID_HANDLE_VALUE)
1857 GetConsoleScreenBufferInfo(con_out, &scr);
1858 size.Y = scr.srWindow.Bottom - scr.srWindow.Top + 1;
1859 size.X = scr.srWindow.Right - scr.srWindow.Left + 1;
1860 if (size.Y != sc_height || size.X != sc_width)
1864 if (!no_init && con_out_ours == con_out)
1865 SetConsoleScreenBufferSize(con_out, size);
1867 wscroll = (sc_height + 1) / 2;
1874 * Goto a specific line on the screen.
1877 goto_line(int slinenum)
1880 tputs(tgoto(sc_move, 0, slinenum), 1, putchr);
1883 _settextposition(slinenum+1, 1);
1887 #if MSDOS_COMPILER==MSOFTC || MSDOS_COMPILER==BORLANDC
1889 * Create an alternate screen which is all white.
1890 * This screen is used to create a "flash" effect, by displaying it
1891 * briefly and then switching back to the normal screen.
1892 * {{ Yuck! There must be a better way to get a visual bell. }}
1897 #if MSDOS_COMPILER==MSOFTC
1898 struct videoconfig w;
1902 _getvideoconfig(&w);
1903 videopages = w.numvideopages;
1906 at_enter(AT_STANDOUT);
1911 at_enter(AT_STANDOUT);
1912 blanks = (char *) ecalloc(w.numtextcols, sizeof(char));
1913 for (col = 0; col < w.numtextcols; col++)
1915 for (row = w.numtextrows; row > 0; row--)
1916 _outmem(blanks, w.numtextcols);
1923 #if MSDOS_COMPILER==BORLANDC
1926 whitescreen = (unsigned short *)
1927 malloc(sc_width * sc_height * sizeof(short));
1928 if (whitescreen == NULL)
1930 for (n = 0; n < sc_width * sc_height; n++)
1931 whitescreen[n] = 0x7020;
1933 #if MSDOS_COMPILER==WIN32C
1936 whitescreen = (WORD *)
1937 malloc(sc_height * sc_width * sizeof(WORD));
1938 if (whitescreen == NULL)
1940 /* Invert the standard colors. */
1941 for (n = 0; n < sc_width * sc_height; n++)
1942 whitescreen[n] = (WORD)((nm_fg_color << 4) | nm_bg_color);
1948 #endif /* MSDOS_COMPILER */
1951 * Output the "visual bell", if there is one.
1957 if (*sc_visual_bell == '\0')
1959 tputs(sc_visual_bell, sc_height, putchr);
1961 #if MSDOS_COMPILER==DJGPPC
1964 #if MSDOS_COMPILER==MSOFTC
1966 * Create a flash screen on the second video page.
1967 * Switch to that page, then switch back.
1977 #if MSDOS_COMPILER==BORLANDC
1978 unsigned short *currscreen;
1981 * Get a copy of the current screen.
1982 * Display the flash screen.
1983 * Then restore the old screen.
1987 if (whitescreen == NULL)
1989 currscreen = (unsigned short *)
1990 malloc(sc_width * sc_height * sizeof(short));
1991 if (currscreen == NULL) return;
1992 gettext(1, 1, sc_width, sc_height, currscreen);
1993 puttext(1, 1, sc_width, sc_height, whitescreen);
1995 puttext(1, 1, sc_width, sc_height, currscreen);
1998 #if MSDOS_COMPILER==WIN32C
1999 /* paint screen with an inverse color */
2002 /* leave it displayed for 100 msec. */
2005 /* restore with a redraw */
2021 putchr(CONTROL('G'));
2023 #if MSDOS_COMPILER==WIN32C
2032 * Ring the terminal bell.
2037 if (quiet == VERY_QUIET)
2050 tputs(sc_clear, sc_height, putchr);
2053 #if MSDOS_COMPILER==WIN32C
2056 _clearscreen(_GCLEARSCREEN);
2062 * Clear from the cursor to the end of the cursor's line.
2063 * {{ This must not move the cursor. }}
2069 tputs(sc_eol_clear, 1, putchr);
2071 #if MSDOS_COMPILER==MSOFTC
2074 struct rccoord tpos;
2078 * Save current state.
2080 tpos = _gettextposition();
2081 _gettextwindow(&top, &left, &bot, &right);
2083 * Set a temporary window to the current line,
2084 * from the cursor's position to the right edge of the screen.
2085 * Then clear that window.
2087 _settextwindow(tpos.row, tpos.col, tpos.row, sc_width);
2088 _clearscreen(_GWINDOW);
2092 _settextwindow(top, left, bot, right);
2093 _settextposition(tpos.row, tpos.col);
2095 #if MSDOS_COMPILER==BORLANDC || MSDOS_COMPILER==DJGPPC
2099 #if MSDOS_COMPILER==WIN32C
2102 CONSOLE_SCREEN_BUFFER_INFO scr;
2105 memset(&scr, 0, sizeof(scr));
2106 GetConsoleScreenBufferInfo(con_out, &scr);
2107 cpos.X = scr.dwCursorPosition.X;
2108 cpos.Y = scr.dwCursorPosition.Y;
2109 curr_attr = MAKEATTR(nm_fg_color, nm_bg_color);
2110 FillConsoleOutputAttribute(con_out, curr_attr,
2111 scr.dwSize.X - cpos.X, cpos, &nchars);
2112 FillConsoleOutputCharacter(con_out, ' ',
2113 scr.dwSize.X - cpos.X, cpos, &nchars);
2121 * Clear the current line.
2122 * Clear the screen if there's off-screen memory below the display.
2131 tputs(sc_eos_clear, 1, putchr);
2133 tputs(sc_eol_clear, 1, putchr);
2138 * Clear the bottom line of the display.
2139 * Leave the cursor at the beginning of the bottom line.
2145 * If we're in a non-normal attribute mode, temporarily exit
2146 * the mode while we do the clear. Some terminals fill the
2147 * cleared area with the current attribute.
2154 if (attrmode == AT_NORMAL)
2158 int saved_attrmode = attrmode;
2162 at_enter(saved_attrmode);
2169 attr = apply_at_specials(attr);
2172 /* The one with the most priority is last. */
2173 if (attr & AT_UNDERLINE)
2174 tputs(sc_u_in, 1, putchr);
2176 tputs(sc_b_in, 1, putchr);
2177 if (attr & AT_BLINK)
2178 tputs(sc_bl_in, 1, putchr);
2179 if (attr & AT_STANDOUT)
2180 tputs(sc_s_in, 1, putchr);
2183 /* The one with the most priority is first. */
2184 if (attr & AT_STANDOUT)
2186 SETCOLORS(so_fg_color, so_bg_color);
2187 } else if (attr & AT_BLINK)
2189 SETCOLORS(bl_fg_color, bl_bg_color);
2191 else if (attr & AT_BOLD)
2193 SETCOLORS(bo_fg_color, bo_bg_color);
2195 else if (attr & AT_UNDERLINE)
2197 SETCOLORS(ul_fg_color, ul_bg_color);
2208 /* Undo things in the reverse order we did them. */
2209 if (attrmode & AT_STANDOUT)
2210 tputs(sc_s_out, 1, putchr);
2211 if (attrmode & AT_BLINK)
2212 tputs(sc_bl_out, 1, putchr);
2213 if (attrmode & AT_BOLD)
2214 tputs(sc_b_out, 1, putchr);
2215 if (attrmode & AT_UNDERLINE)
2216 tputs(sc_u_out, 1, putchr);
2219 SETCOLORS(nm_fg_color, nm_bg_color);
2222 attrmode = AT_NORMAL;
2228 int new_attrmode = apply_at_specials(attr);
2229 int ignore_modes = AT_ANSI;
2231 if ((new_attrmode & ~ignore_modes) != (attrmode & ~ignore_modes))
2239 is_at_equiv(int attr1, int attr2)
2241 attr1 = apply_at_specials(attr1);
2242 attr2 = apply_at_specials(attr2);
2244 return (attr1 == attr2);
2248 apply_at_specials(int attr)
2250 if (attr & AT_BINARY)
2252 if (attr & AT_HILITE)
2253 attr |= AT_STANDOUT;
2254 attr &= ~(AT_BINARY|AT_HILITE);
2259 #if 0 /* No longer used */
2261 * Erase the character to the left of the cursor
2262 * and move the cursor left.
2269 * Erase the previous character by overstriking with a space.
2271 tputs(sc_backspace, 1, putchr);
2273 tputs(sc_backspace, 1, putchr);
2275 #if MSDOS_COMPILER==MSOFTC
2276 struct rccoord tpos;
2279 tpos = _gettextposition();
2282 _settextposition(tpos.row, tpos.col-1);
2284 _settextposition(tpos.row, tpos.col-1);
2286 #if MSDOS_COMPILER==BORLANDC || MSDOS_COMPILER==DJGPPC
2289 #if MSDOS_COMPILER==WIN32C
2292 CONSOLE_SCREEN_BUFFER_INFO scr;
2295 GetConsoleScreenBufferInfo(con_out, &scr);
2296 cpos = scr.dwCursorPosition;
2300 SetConsoleCursorPosition(con_out, cpos);
2301 FillConsoleOutputCharacter(con_out, (TCHAR)' ', 1, cpos, &cChars);
2302 SetConsoleCursorPosition(con_out, cpos);
2311 * Output a plain backspace, without erasing the previous char.
2317 tputs(sc_backspace, 1, putchr);
2323 #if MSDOS_COMPILER==MSOFTC
2324 struct rccoord tpos;
2325 tpos = _gettextposition();
2329 #if MSDOS_COMPILER==BORLANDC || MSDOS_COMPILER==DJGPPC
2333 #if MSDOS_COMPILER==WIN32C
2334 CONSOLE_SCREEN_BUFFER_INFO scr;
2335 GetConsoleScreenBufferInfo(con_out, &scr);
2336 row = scr.dwCursorPosition.Y - scr.srWindow.Top + 1;
2337 col = scr.dwCursorPosition.X - scr.srWindow.Left + 1;
2344 _settextposition(row, col-1);
2345 #endif /* MSDOS_COMPILER */
2348 #if MSDOS_COMPILER==WIN32C
2350 * Determine whether an input character is waiting to be read.
2353 win32_kbhit(HANDLE tty)
2361 currentKey.ascii = 0;
2362 currentKey.scan = 0;
2365 * Wait for a real key-down event, but
2366 * ignore SHIFT and CONTROL key events.
2370 PeekConsoleInput(tty, &ip, 1, &read);
2373 ReadConsoleInput(tty, &ip, 1, &read);
2374 } while (ip.EventType != KEY_EVENT ||
2375 ip.Event.KeyEvent.bKeyDown != TRUE ||
2376 ip.Event.KeyEvent.wVirtualScanCode == 0 ||
2377 ip.Event.KeyEvent.wVirtualKeyCode == VK_SHIFT ||
2378 ip.Event.KeyEvent.wVirtualKeyCode == VK_CONTROL ||
2379 ip.Event.KeyEvent.wVirtualKeyCode == VK_MENU);
2381 currentKey.ascii = ip.Event.KeyEvent.uChar.AsciiChar;
2382 currentKey.scan = ip.Event.KeyEvent.wVirtualScanCode;
2383 keyCount = ip.Event.KeyEvent.wRepeatCount;
2385 if (ip.Event.KeyEvent.dwControlKeyState &
2386 (LEFT_ALT_PRESSED | RIGHT_ALT_PRESSED))
2388 switch (currentKey.scan)
2390 case PCK_ALT_E: /* letter 'E' */
2391 currentKey.ascii = 0;
2394 } else if (ip.Event.KeyEvent.dwControlKeyState &
2395 (LEFT_CTRL_PRESSED | RIGHT_CTRL_PRESSED))
2397 switch (currentKey.scan)
2399 case PCK_RIGHT: /* right arrow */
2400 currentKey.scan = PCK_CTL_RIGHT;
2402 case PCK_LEFT: /* left arrow */
2403 currentKey.scan = PCK_CTL_LEFT;
2405 case PCK_DELETE: /* delete */
2406 currentKey.scan = PCK_CTL_DELETE;
2414 * Read a character from the keyboard.
2421 if (pending_scancode)
2423 pending_scancode = 0;
2424 return ((char)(currentKey.scan & 0x00FF));
2427 while (win32_kbhit((HANDLE)tty) == FALSE)
2435 ascii = currentKey.ascii;
2437 * On PC's, the extended keys return a 2 byte sequence beginning
2438 * with '00', so if the ascii code is 00, the next byte will be
2439 * the lsb of the scan code.
2441 pending_scancode = (ascii == 0x00);
2442 return ((char)ascii);
2450 WIN32setcolors(int fg, int bg)
2458 WIN32textout(char *text, int len)
2460 #if MSDOS_COMPILER==WIN32C
2462 WriteConsole(con_out, text, len, &written, NULL);