2 * Copyright (C) 1984-2016 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;
154 public int sgr_mode; /* Honor ANSI sequences rather than using above */
159 * Strings passed to tputs() to do various terminal functions.
162 *sc_pad, /* Pad string */
163 *sc_home, /* Cursor home */
164 *sc_addline, /* Add line, scroll down following lines */
165 *sc_lower_left, /* Cursor to last line, first column */
166 *sc_return, /* Cursor to beginning of current line */
167 *sc_move, /* General cursor positioning */
168 *sc_clear, /* Clear screen */
169 *sc_eol_clear, /* Clear to end of line */
170 *sc_eos_clear, /* Clear to end of screen */
171 *sc_s_in, /* Enter standout (highlighted) mode */
172 *sc_s_out, /* Exit standout mode */
173 *sc_u_in, /* Enter underline mode */
174 *sc_u_out, /* Exit underline mode */
175 *sc_b_in, /* Enter bold mode */
176 *sc_b_out, /* Exit bold mode */
177 *sc_bl_in, /* Enter blink mode */
178 *sc_bl_out, /* Exit blink mode */
179 *sc_visual_bell, /* Visual bell (flash screen) sequence */
180 *sc_backspace, /* Backspace cursor */
181 *sc_s_keypad, /* Start keypad mode */
182 *sc_e_keypad, /* End keypad mode */
183 *sc_init, /* Startup terminal initialization */
184 *sc_deinit; /* Exit terminal de-initialization */
187 static int init_done = 0;
189 public int auto_wrap; /* Terminal does \r\n when write past margin */
190 public int ignaw; /* Terminal ignores \n immediately after wrap */
191 public int erase_char; /* The user's erase char */
192 public int erase2_char; /* The user's other erase char */
193 public int kill_char; /* The user's line-kill char */
194 public int werase_char; /* The user's word-erase char */
195 public int sc_width, sc_height; /* Height & width of screen */
196 public int bo_s_width, bo_e_width; /* Printing width of boldface seq */
197 public int ul_s_width, ul_e_width; /* Printing width of underline seq */
198 public int so_s_width, so_e_width; /* Printing width of standout seq */
199 public int bl_s_width, bl_e_width; /* Printing width of blink seq */
200 public int above_mem, below_mem; /* Memory retained above/below screen */
201 public int can_goto_line; /* Can move cursor to any line */
202 public int clear_bg; /* Clear fills with background color */
203 public int missing_cap = 0; /* Some capability is missing */
205 static int attrmode = AT_NORMAL;
209 static char *cheaper();
210 static void tmodes();
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.
260 static int curr_on = 0;
264 erase2_char = '\b'; /* in case OS doesn't know about erase2 */
265 #if HAVE_TERMIOS_H && HAVE_TERMIOS_FUNCS
268 static struct termios save_term;
269 static int saved_term = 0;
274 * Get terminal modes.
279 * Save modes and set certain variables dependent on modes.
287 switch (cfgetospeed(&s))
290 case B0: ospeed = 0; break;
293 case B50: ospeed = 1; break;
296 case B75: ospeed = 2; break;
299 case B110: ospeed = 3; break;
302 case B134: ospeed = 4; break;
305 case B150: ospeed = 5; break;
308 case B200: ospeed = 6; break;
311 case B300: ospeed = 7; break;
314 case B600: ospeed = 8; break;
317 case B1200: ospeed = 9; break;
320 case B1800: ospeed = 10; break;
323 case B2400: ospeed = 11; break;
326 case B4800: ospeed = 12; break;
329 case B9600: ospeed = 13; break;
332 case EXTA: ospeed = 14; break;
335 case EXTB: ospeed = 15; break;
338 case B57600: ospeed = 16; break;
341 case B115200: ospeed = 17; break;
346 erase_char = s.c_cc[VERASE];
348 erase2_char = s.c_cc[VERASE2];
350 kill_char = s.c_cc[VKILL];
352 werase_char = s.c_cc[VWERASE];
354 werase_char = CONTROL('W');
358 * Set the modes to the way we want them.
420 #if MUST_SET_LINE_DISCIPLINE
422 * System's termios is broken; need to explicitly
423 * request TERMIODISC line discipline.
425 s.c_line = TERMIODISC;
430 * Restore saved modes.
437 tcsetattr(tty, TCSADRAIN, &s);
438 #if MUST_SET_LINE_DISCIPLINE
442 * Broken termios *ignores* any line discipline
443 * except TERMIODISC. A different old line discipline
444 * is therefore not restored, yet. Restore the old
445 * line discipline by hand.
447 ioctl(tty, TIOCSETD, &save_term.c_line);
455 static struct termio save_term;
456 static int saved_term = 0;
461 * Get terminal modes.
463 ioctl(tty, TCGETA, &s);
466 * Save modes and set certain variables dependent on modes.
474 ospeed = s.c_cflag & CBAUD;
476 erase_char = s.c_cc[VERASE];
477 kill_char = s.c_cc[VKILL];
479 werase_char = s.c_cc[VWERASE];
481 werase_char = CONTROL('W');
485 * Set the modes to the way we want them.
487 s.c_lflag &= ~(ICANON|ECHO|ECHOE|ECHOK|ECHONL);
488 s.c_oflag |= (OPOST|ONLCR|TAB3);
489 s.c_oflag &= ~(OCRNL|ONOCR|ONLRET);
495 * Restore saved modes.
499 ioctl(tty, TCSETAW, &s);
505 static struct sgttyb save_term;
506 static int saved_term = 0;
511 * Get terminal modes.
513 ioctl(tty, TIOCGETP, &s);
516 * Save modes and set certain variables dependent on modes.
524 ospeed = s.sg_ospeed;
526 erase_char = s.sg_erase;
527 kill_char = s.sg_kill;
528 werase_char = CONTROL('W');
531 * Set the modes to the way we want them.
533 s.sg_flags |= CBREAK;
534 s.sg_flags &= ~(ECHO|XTABS);
538 * Restore saved modes.
542 ioctl(tty, TIOCSETN, &s);
548 static struct sgbuf save_term;
549 static int saved_term = 0;
554 * Get terminal modes.
559 * Save modes and set certain variables dependent on modes.
566 erase_char = s.sg_bspch;
567 kill_char = s.sg_dlnch;
568 werase_char = CONTROL('W');
571 * Set the modes to the way we want them.
580 * Restore saved modes.
587 /* MS-DOS, Windows, or OS2 */
590 LSIGNAL(SIGINT, SIG_IGN);
593 #if MSDOS_COMPILER==DJGPPC
594 kill_char = CONTROL('U');
596 * So that when we shell out or run another program, its
597 * stdin is in cooked mode. We do not switch stdin to binary
598 * mode if fd0 is zero, since that means we were called before
599 * tty was reopened in open_getchr, in which case we would be
600 * changing the original stdin device outside less.
603 setmode(0, on ? O_BINARY : O_TEXT);
607 werase_char = CONTROL('W');
617 * Some glue to prevent calling termcap functions if tgetent() failed.
628 s = lgetenv("LESS_TERMCAP_DEBUG");
629 if (s != NULL && *s != '\0')
631 struct env { struct env *next; char *name; char *value; };
632 static struct env *envs = NULL;
634 for (p = envs; p != NULL; p = p->next)
635 if (strcmp(p->name, capname) == 0)
637 p = (struct env *) ecalloc(1, sizeof(struct env));
638 p->name = save(capname);
639 p->value = (char *) ecalloc(strlen(capname)+3, sizeof(char));
640 sprintf(p->value, "<%s>", capname);
645 strcpy(name, "LESS_TERMCAP_");
646 strcat(name, capname);
647 return (lgetenv(name));
656 if ((s = ltget_env(capname)) != NULL)
657 return (*s != '\0' && *s != '0');
660 return (tgetflag(capname));
669 if ((s = ltget_env(capname)) != NULL)
673 return (tgetnum(capname));
677 ltgetstr(capname, pp)
683 if ((s = ltget_env(capname)) != NULL)
687 return (tgetstr(capname, pp));
689 #endif /* MSDOS_COMPILER */
692 * Get size of the output screen.
704 #define DEF_SC_WIDTH 80
706 #define DEF_SC_HEIGHT 25
708 #define DEF_SC_HEIGHT 24
712 sys_width = sys_height = 0;
714 #if MSDOS_COMPILER==MSOFTC
716 struct videoconfig w;
718 sys_height = w.numtextrows;
719 sys_width = w.numtextcols;
722 #if MSDOS_COMPILER==BORLANDC || MSDOS_COMPILER==DJGPPC
726 sys_height = w.screenheight;
727 sys_width = w.screenwidth;
730 #if MSDOS_COMPILER==WIN32C
732 CONSOLE_SCREEN_BUFFER_INFO scr;
733 GetConsoleScreenBufferInfo(con_out, &scr);
734 sys_height = scr.srWindow.Bottom - scr.srWindow.Top + 1;
735 sys_width = scr.srWindow.Right - scr.srWindow.Left + 1;
745 * When using terminal emulators for XFree86/OS2, the
746 * _scrsize function does not work well.
747 * Call the scrsize.exe program to get the window size.
749 windowid = getenv("WINDOWID");
750 if (windowid != NULL)
752 FILE *fd = popen("scrsize", "rt");
756 fscanf(fd, "%i %i", &w, &h);
770 if (ioctl(2, TIOCGWINSZ, &w) == 0)
773 sys_height = w.ws_row;
775 sys_width = w.ws_col;
782 if (ioctl(2, WIOCGETD, &w) == 0)
785 sys_height = w.uw_height / w.uw_vs;
787 sys_width = w.uw_width / w.uw_hs;
798 sc_height = sys_height;
799 else if ((s = lgetenv("LINES")) != NULL)
802 else if ((n = ltgetnum("li")) > 0)
806 sc_height = DEF_SC_HEIGHT;
809 sc_width = sys_width;
810 else if ((s = lgetenv("COLUMNS")) != NULL)
813 else if ((n = ltgetnum("co")) > 0)
817 sc_width = DEF_SC_WIDTH;
820 #if MSDOS_COMPILER==MSOFTC
822 * Figure out how many empty loops it takes to delay a millisecond.
830 * Get synchronized at the start of a tick.
833 while (clock() == start)
836 * Now count loops till the next tick.
840 while (clock() == start)
843 * Convert from (loops per clock) to (loops per millisecond).
845 msec_loops *= CLOCKS_PER_SEC;
850 * Delay for a specified number of milliseconds.
855 static long delay_dummy = 0;
867 for (i = 0; i < msec_loops; i++)
870 * Make it look like we're doing something here,
871 * so the optimizer doesn't remove the whole loop.
880 * Return the characters actually input by a "special" key.
886 static char tbuf[40];
888 #if MSDOS_COMPILER || OS2
889 static char k_right[] = { '\340', PCK_RIGHT, 0 };
890 static char k_left[] = { '\340', PCK_LEFT, 0 };
891 static char k_ctl_right[] = { '\340', PCK_CTL_RIGHT, 0 };
892 static char k_ctl_left[] = { '\340', PCK_CTL_LEFT, 0 };
893 static char k_insert[] = { '\340', PCK_INSERT, 0 };
894 static char k_delete[] = { '\340', PCK_DELETE, 0 };
895 static char k_ctl_delete[] = { '\340', PCK_CTL_DELETE, 0 };
896 static char k_ctl_backspace[] = { '\177', 0 };
897 static char k_home[] = { '\340', PCK_HOME, 0 };
898 static char k_end[] = { '\340', PCK_END, 0 };
899 static char k_up[] = { '\340', PCK_UP, 0 };
900 static char k_down[] = { '\340', PCK_DOWN, 0 };
901 static char k_backtab[] = { '\340', PCK_SHIFT_TAB, 0 };
902 static char k_pagedown[] = { '\340', PCK_PAGEDOWN, 0 };
903 static char k_pageup[] = { '\340', PCK_PAGEUP, 0 };
904 static char k_f1[] = { '\340', PCK_F1, 0 };
914 * If windowid is not NULL, assume less is executed in
915 * the XFree86 environment.
918 s = windowid ? ltgetstr("kr", &sp) : k_right;
921 s = windowid ? ltgetstr("kl", &sp) : k_left;
924 s = windowid ? ltgetstr("ku", &sp) : k_up;
927 s = windowid ? ltgetstr("kd", &sp) : k_down;
930 s = windowid ? ltgetstr("kP", &sp) : k_pageup;
933 s = windowid ? ltgetstr("kN", &sp) : k_pagedown;
936 s = windowid ? ltgetstr("kh", &sp) : k_home;
939 s = windowid ? ltgetstr("@7", &sp) : k_end;
944 s = ltgetstr("kD", &sp);
984 #if MSDOS_COMPILER || OS2
988 case SK_CTL_LEFT_ARROW:
991 case SK_CTL_RIGHT_ARROW:
994 case SK_CTL_BACKSPACE:
1007 case SK_RIGHT_ARROW:
1008 s = ltgetstr("kr", &sp);
1011 s = ltgetstr("kl", &sp);
1014 s = ltgetstr("ku", &sp);
1017 s = ltgetstr("kd", &sp);
1020 s = ltgetstr("kP", &sp);
1023 s = ltgetstr("kN", &sp);
1026 s = ltgetstr("kh", &sp);
1029 s = ltgetstr("@7", &sp);
1032 s = ltgetstr("kD", &sp);
1042 tbuf[0] = CONTROL('K');
1053 * Get terminal capabilities via termcap.
1064 * Set up default colors.
1065 * The xx_s_width and xx_e_width vars are already initialized to 0.
1067 #if MSDOS_COMPILER==MSOFTC
1068 sy_bg_color = _getbkcolor();
1069 sy_fg_color = _gettextcolor();
1072 #if MSDOS_COMPILER==BORLANDC || MSDOS_COMPILER==DJGPPC
1076 sy_bg_color = (w.attribute >> 4) & 0x0F;
1077 sy_fg_color = (w.attribute >> 0) & 0x0F;
1080 #if MSDOS_COMPILER==WIN32C
1083 CONSOLE_SCREEN_BUFFER_INFO scr;
1085 con_out_save = con_out = GetStdHandle(STD_OUTPUT_HANDLE);
1087 * Always open stdin in binary. Note this *must* be done
1088 * before any file operations have been done on fd0.
1091 GetConsoleScreenBufferInfo(con_out, &scr);
1092 ReadConsoleOutputAttribute(con_out, &curr_attr,
1093 1, scr.dwCursorPosition, &nread);
1094 sy_bg_color = (curr_attr & BG_COLORS) >> 4; /* normalize */
1095 sy_fg_color = curr_attr & FG_COLORS;
1100 nm_fg_color = sy_fg_color;
1101 nm_bg_color = sy_bg_color;
1113 * Get size of the screen.
1119 #else /* !MSDOS_COMPILER */
1122 register char *t1, *t2;
1124 char termbuf[TERMBUF_SIZE];
1126 static char sbuf[TERMSBUF_SIZE];
1130 * Make sure the termcap database is available.
1132 sp = lgetenv("TERMCAP");
1133 if (sp == NULL || *sp == '\0')
1136 if ((sp = homefile("termcap.dat")) != NULL)
1138 termcap = (char *) ecalloc(strlen(sp)+9, sizeof(char));
1139 sprintf(termcap, "TERMCAP=%s", sp);
1146 * Find out what kind of terminal this is.
1148 if ((term = lgetenv("TERM")) == NULL)
1149 term = DEFAULT_TERM;
1151 if (tgetent(termbuf, term) != TGETENT_OK)
1153 if (ltgetflag("hc"))
1157 * Get size of the screen.
1162 auto_wrap = ltgetflag("am");
1163 ignaw = ltgetflag("xn");
1164 above_mem = ltgetflag("da");
1165 below_mem = ltgetflag("db");
1166 clear_bg = ltgetflag("ut");
1169 * Assumes termcap variable "sg" is the printing width of:
1170 * the standout sequence, the end standout sequence,
1171 * the underline sequence, the end underline sequence,
1172 * the boldface sequence, and the end boldface sequence.
1174 if ((so_s_width = ltgetnum("sg")) < 0)
1176 so_e_width = so_s_width;
1178 bo_s_width = bo_e_width = so_s_width;
1179 ul_s_width = ul_e_width = so_s_width;
1180 bl_s_width = bl_e_width = so_s_width;
1183 if (so_s_width > 0 || so_e_width > 0)
1185 * Disable highlighting by default on magic cookie terminals.
1186 * Turning on highlighting might change the displayed width
1187 * of a line, causing the display to get messed up.
1188 * The user can turn it back on with -g,
1189 * but she won't like the results.
1195 * Get various string-valued capabilities.
1200 sc_pad = ltgetstr("pc", &sp);
1205 sc_s_keypad = ltgetstr("ks", &sp);
1206 if (sc_s_keypad == NULL)
1208 sc_e_keypad = ltgetstr("ke", &sp);
1209 if (sc_e_keypad == NULL)
1212 sc_init = ltgetstr("ti", &sp);
1213 if (sc_init == NULL)
1216 sc_deinit= ltgetstr("te", &sp);
1217 if (sc_deinit == NULL)
1220 sc_eol_clear = ltgetstr("ce", &sp);
1221 if (sc_eol_clear == NULL || *sc_eol_clear == '\0')
1227 sc_eos_clear = ltgetstr("cd", &sp);
1228 if (below_mem && (sc_eos_clear == NULL || *sc_eos_clear == '\0'))
1234 sc_clear = ltgetstr("cl", &sp);
1235 if (sc_clear == NULL || *sc_clear == '\0')
1241 sc_move = ltgetstr("cm", &sp);
1242 if (sc_move == NULL || *sc_move == '\0')
1245 * This is not an error here, because we don't
1246 * always need sc_move.
1247 * We need it only if we don't have home or lower-left.
1254 tmodes("so", "se", &sc_s_in, &sc_s_out, "", "", &sp);
1255 tmodes("us", "ue", &sc_u_in, &sc_u_out, sc_s_in, sc_s_out, &sp);
1256 tmodes("md", "me", &sc_b_in, &sc_b_out, sc_s_in, sc_s_out, &sp);
1257 tmodes("mb", "me", &sc_bl_in, &sc_bl_out, sc_s_in, sc_s_out, &sp);
1259 sc_visual_bell = ltgetstr("vb", &sp);
1260 if (sc_visual_bell == NULL)
1261 sc_visual_bell = "";
1263 if (ltgetflag("bs"))
1264 sc_backspace = "\b";
1267 sc_backspace = ltgetstr("bc", &sp);
1268 if (sc_backspace == NULL || *sc_backspace == '\0')
1269 sc_backspace = "\b";
1273 * Choose between using "ho" and "cm" ("home" and "cursor move")
1274 * to move the cursor to the upper left corner of the screen.
1276 t1 = ltgetstr("ho", &sp);
1279 if (*sc_move == '\0')
1283 strcpy(sp, tgoto(sc_move, 0, 0));
1285 sp += strlen(sp) + 1;
1287 sc_home = cheaper(t1, t2, "|\b^");
1290 * Choose between using "ll" and "cm" ("lower left" and "cursor move")
1291 * to move the cursor to the lower left corner of the screen.
1293 t1 = ltgetstr("ll", &sp);
1296 if (*sc_move == '\0')
1300 strcpy(sp, tgoto(sc_move, 0, sc_height-1));
1302 sp += strlen(sp) + 1;
1304 sc_lower_left = cheaper(t1, t2, "\r");
1307 * Get carriage return string.
1309 sc_return = ltgetstr("cr", &sp);
1310 if (sc_return == NULL)
1314 * Choose between using "al" or "sr" ("add line" or "scroll reverse")
1315 * to add a line at the top of the screen.
1317 t1 = ltgetstr("al", &sp);
1320 t2 = ltgetstr("sr", &sp);
1324 if (*t1 == '\0' && *t2 == '\0')
1331 sc_addline = cheaper(t1, t2, "");
1332 if (*sc_addline == '\0')
1335 * Force repaint on any backward movement.
1339 #endif /* MSDOS_COMPILER */
1344 * Return the cost of displaying a termcap string.
1345 * We use the trick of calling tputs, but as a char printing function
1346 * we give it inc_costcount, which just increments "costcount".
1347 * This tells us how many chars would be printed by using this string.
1348 * {{ Couldn't we just use strlen? }}
1350 static int costcount;
1366 tputs(t, sc_height, inc_costcount);
1371 * Return the "best" of the two given termcap strings.
1372 * The best, if both exist, is the one with the lower
1373 * cost (see cost() function).
1376 cheaper(t1, t2, def)
1380 if (*t1 == '\0' && *t2 == '\0')
1389 if (cost(t1) < cost(t2))
1395 tmodes(incap, outcap, instr, outstr, def_instr, def_outstr, spp)
1404 *instr = ltgetstr(incap, spp);
1409 *outstr = def_outstr;
1413 *outstr = ltgetstr(outcap, spp);
1414 if (*outstr == NULL)
1415 /* No specific out capability; use "me". */
1416 *outstr = ltgetstr("me", spp);
1417 if (*outstr == NULL)
1418 /* Don't even have "me"; use a null string. */
1422 #endif /* MSDOS_COMPILER */
1426 * Below are the functions which perform all the
1427 * terminal-specific screen manipulation.
1433 #if MSDOS_COMPILER==WIN32C
1435 _settextposition(int row, int col)
1438 CONSOLE_SCREEN_BUFFER_INFO csbi;
1440 GetConsoleScreenBufferInfo(con_out, &csbi);
1441 cpos.X = csbi.srWindow.Left + (col - 1);
1442 cpos.Y = csbi.srWindow.Top + (row - 1);
1443 SetConsoleCursorPosition(con_out, cpos);
1448 * Initialize the screen to the correct color at startup.
1453 #if MSDOS_COMPILER==BORLANDC || MSDOS_COMPILER==DJGPPC
1456 SETCOLORS(nm_fg_color, nm_bg_color);
1459 * This clears the screen at startup. This is different from
1460 * the behavior of other versions of less. Disable it for now.
1467 * Create a complete, blank screen using "normal" colors.
1469 SETCOLORS(nm_fg_color, nm_bg_color);
1470 blanks = (char *) ecalloc(width+1, sizeof(char));
1471 for (col = 0; col < sc_width; col++)
1473 blanks[sc_width] = '\0';
1474 for (row = 0; row < sc_height; row++)
1481 #if MSDOS_COMPILER==WIN32C
1484 * Termcap-like init with a private win32 console.
1489 CONSOLE_SCREEN_BUFFER_INFO scr;
1492 if (con_out_save == INVALID_HANDLE_VALUE)
1495 GetConsoleScreenBufferInfo(con_out_save, &scr);
1497 if (con_out_ours == INVALID_HANDLE_VALUE)
1500 * Create our own screen buffer, so that we
1501 * may restore the original when done.
1503 con_out_ours = CreateConsoleScreenBuffer(
1504 GENERIC_WRITE | GENERIC_READ,
1505 FILE_SHARE_WRITE | FILE_SHARE_READ,
1506 (LPSECURITY_ATTRIBUTES) NULL,
1507 CONSOLE_TEXTMODE_BUFFER,
1511 size.X = scr.srWindow.Right - scr.srWindow.Left + 1;
1512 size.Y = scr.srWindow.Bottom - scr.srWindow.Top + 1;
1513 SetConsoleScreenBufferSize(con_out_ours, size);
1514 SetConsoleActiveScreenBuffer(con_out_ours);
1515 con_out = con_out_ours;
1519 * Restore the startup console.
1524 if (con_out_save == INVALID_HANDLE_VALUE)
1527 (void) CloseHandle(con_out_ours);
1528 SetConsoleActiveScreenBuffer(con_out_save);
1529 con_out = con_out_save;
1535 * Initialize terminal
1542 tputs(sc_init, sc_height, putchr);
1544 tputs(sc_s_keypad, sc_height, putchr);
1550 * This is nice to terminals with no alternate screen,
1551 * but with saved scrolled-off-the-top lines. This way,
1552 * no previous line is lost, but we start with a whole
1553 * screen to ourself.
1555 for (i = 1; i < sc_height; i++)
1560 #if MSDOS_COMPILER==WIN32C
1571 * Deinitialize terminal
1580 tputs(sc_e_keypad, sc_height, putchr);
1582 tputs(sc_deinit, sc_height, putchr);
1584 /* Restore system colors. */
1585 SETCOLORS(sy_fg_color, sy_bg_color);
1586 #if MSDOS_COMPILER==WIN32C
1588 win32_deinit_term();
1590 /* Need clreol to make SETCOLORS take effect. */
1598 * Home cursor (move to upper left corner of screen).
1604 tputs(sc_home, 1, putchr);
1607 _settextposition(1,1);
1612 * Add a blank line (called with cursor at home).
1613 * Should scroll the display down.
1619 tputs(sc_addline, sc_height, putchr);
1622 #if MSDOS_COMPILER==MSOFTC
1623 _scrolltextwindow(_GSCROLLDOWN);
1624 _settextposition(1,1);
1626 #if MSDOS_COMPILER==BORLANDC || MSDOS_COMPILER==DJGPPC
1627 movetext(1,1, sc_width,sc_height-1, 1,2);
1631 #if MSDOS_COMPILER==WIN32C
1634 SMALL_RECT rcSrc, rcClip;
1636 CONSOLE_SCREEN_BUFFER_INFO csbi;
1638 GetConsoleScreenBufferInfo(con_out,&csbi);
1640 /* The clip rectangle is the entire visible screen. */
1641 rcClip.Left = csbi.srWindow.Left;
1642 rcClip.Top = csbi.srWindow.Top;
1643 rcClip.Right = csbi.srWindow.Right;
1644 rcClip.Bottom = csbi.srWindow.Bottom;
1646 /* The source rectangle is the visible screen minus the last line. */
1650 /* Move the top left corner of the source window down one row. */
1651 new_org.X = rcSrc.Left;
1652 new_org.Y = rcSrc.Top + 1;
1654 /* Fill the right character and attributes. */
1655 fillchar.Char.AsciiChar = ' ';
1656 curr_attr = MAKEATTR(nm_fg_color, nm_bg_color);
1657 fillchar.Attributes = curr_attr;
1658 ScrollConsoleScreenBuffer(con_out, &rcSrc, &rcClip, new_org, &fillchar);
1659 _settextposition(1,1);
1669 * Remove the n topmost lines and scroll everything below it in the
1670 * window upward. This is needed to stop leaking the topmost line
1671 * into the scrollback buffer when we go down-one-line (in WIN32).
1677 #if MSDOS_COMPILER==WIN32C
1678 SMALL_RECT rcSrc, rcClip;
1681 CONSOLE_SCREEN_BUFFER_INFO csbi; /* to get buffer info */
1683 if (n >= sc_height - 1)
1692 GetConsoleScreenBufferInfo(con_out, &csbi);
1694 /* Get the extent of all-visible-rows-but-the-last. */
1695 rcSrc.Left = csbi.srWindow.Left;
1696 rcSrc.Top = csbi.srWindow.Top + n;
1697 rcSrc.Right = csbi.srWindow.Right;
1698 rcSrc.Bottom = csbi.srWindow.Bottom;
1700 /* Get the clip rectangle. */
1701 rcClip.Left = rcSrc.Left;
1702 rcClip.Top = csbi.srWindow.Top;
1703 rcClip.Right = rcSrc.Right;
1704 rcClip.Bottom = rcSrc.Bottom ;
1706 /* Move the source window up n rows. */
1707 new_org.X = rcSrc.Left;
1708 new_org.Y = rcSrc.Top - n;
1710 /* Fill the right character and attributes. */
1711 fillchar.Char.AsciiChar = ' ';
1712 curr_attr = MAKEATTR(nm_fg_color, nm_bg_color);
1713 fillchar.Attributes = curr_attr;
1715 ScrollConsoleScreenBuffer(con_out, &rcSrc, &rcClip, new_org, &fillchar);
1717 /* Position cursor on first blank line. */
1718 goto_line(sc_height - n - 1);
1723 #if MSDOS_COMPILER==WIN32C
1731 * This will clear only the currently visible rows of the NT
1732 * console buffer, which means none of the precious scrollback
1733 * rows are touched making for faster scrolling. Note that, if
1734 * the window has fewer columns than the console buffer (i.e.
1735 * there is a horizontal scrollbar as well), the entire width
1736 * of the visible rows will be cleared.
1741 CONSOLE_SCREEN_BUFFER_INFO csbi;
1743 /* get the number of cells in the current buffer */
1744 GetConsoleScreenBufferInfo(con_out, &csbi);
1745 winsz = csbi.dwSize.X * (csbi.srWindow.Bottom - csbi.srWindow.Top + 1);
1747 topleft.Y = csbi.srWindow.Top;
1749 curr_attr = MAKEATTR(nm_fg_color, nm_bg_color);
1750 FillConsoleOutputCharacter(con_out, ' ', winsz, topleft, &nchars);
1751 FillConsoleOutputAttribute(con_out, curr_attr, winsz, topleft, &nchars);
1755 * Remove the n topmost lines and scroll everything below it in the
1762 SMALL_RECT rcSrc, rcClip;
1768 CONSOLE_SCREEN_BUFFER_INFO csbi;
1773 if (n >= sc_height - 1)
1776 _settextposition(1,1);
1780 /* Get the extent of what will remain visible after scrolling. */
1781 GetConsoleScreenBufferInfo(con_out, &csbi);
1782 rcSrc.Left = csbi.srWindow.Left;
1783 rcSrc.Top = csbi.srWindow.Top + n;
1784 rcSrc.Right = csbi.srWindow.Right;
1785 rcSrc.Bottom = csbi.srWindow.Bottom;
1787 /* Get the clip rectangle. */
1788 rcClip.Left = rcSrc.Left;
1789 rcClip.Top = csbi.srWindow.Top;
1790 rcClip.Right = rcSrc.Right;
1791 rcClip.Bottom = rcSrc.Bottom ;
1793 /* Move the source text to the top of the screen. */
1794 new_org.X = rcSrc.Left;
1795 new_org.Y = rcClip.Top;
1797 /* Fill the right character and attributes. */
1798 fillchar.Char.AsciiChar = ' ';
1799 fillchar.Attributes = MAKEATTR(nm_fg_color, nm_bg_color);
1801 /* Scroll the window. */
1802 SetConsoleTextAttribute(con_out, fillchar.Attributes);
1803 ScrollConsoleScreenBuffer(con_out, &rcSrc, &rcClip, new_org, &fillchar);
1805 /* Clear remaining lines at bottom. */
1806 topleft.X = csbi.dwCursorPosition.X;
1807 topleft.Y = rcSrc.Bottom - n;
1808 size = (n * csbi.dwSize.X) + (rcSrc.Right - topleft.X);
1809 FillConsoleOutputCharacter(con_out, ' ', size, topleft,
1811 FillConsoleOutputAttribute(con_out, fillchar.Attributes, size, topleft,
1813 SetConsoleTextAttribute(con_out, curr_attr);
1815 /* Move cursor n lines up from where it was. */
1816 csbi.dwCursorPosition.Y -= n;
1817 SetConsoleCursorPosition(con_out, csbi.dwCursorPosition);
1822 * Move cursor to lower left corner of screen.
1828 tputs(sc_lower_left, 1, putchr);
1831 _settextposition(sc_height, 1);
1836 * Move cursor to left position of current line.
1842 tputs(sc_return, 1, putchr);
1846 #if MSDOS_COMPILER==WIN32C
1848 CONSOLE_SCREEN_BUFFER_INFO scr;
1849 GetConsoleScreenBufferInfo(con_out, &scr);
1850 row = scr.dwCursorPosition.Y - scr.srWindow.Top + 1;
1853 #if MSDOS_COMPILER==BORLANDC || MSDOS_COMPILER==DJGPPC
1857 struct rccoord tpos = _gettextposition();
1862 _settextposition(row, 1);
1867 * Check if the console size has changed and reset internals
1868 * (in lieu of SIGWINCH for WIN32).
1873 #if MSDOS_COMPILER==WIN32C
1874 CONSOLE_SCREEN_BUFFER_INFO scr;
1877 if (con_out == INVALID_HANDLE_VALUE)
1881 GetConsoleScreenBufferInfo(con_out, &scr);
1882 size.Y = scr.srWindow.Bottom - scr.srWindow.Top + 1;
1883 size.X = scr.srWindow.Right - scr.srWindow.Left + 1;
1884 if (size.Y != sc_height || size.X != sc_width)
1888 if (!no_init && con_out_ours == con_out)
1889 SetConsoleScreenBufferSize(con_out, size);
1891 wscroll = (sc_height + 1) / 2;
1898 * Goto a specific line on the screen.
1905 tputs(tgoto(sc_move, 0, slinenum), 1, putchr);
1908 _settextposition(slinenum+1, 1);
1912 #if MSDOS_COMPILER==MSOFTC || MSDOS_COMPILER==BORLANDC
1914 * Create an alternate screen which is all white.
1915 * This screen is used to create a "flash" effect, by displaying it
1916 * briefly and then switching back to the normal screen.
1917 * {{ Yuck! There must be a better way to get a visual bell. }}
1922 #if MSDOS_COMPILER==MSOFTC
1923 struct videoconfig w;
1927 _getvideoconfig(&w);
1928 videopages = w.numvideopages;
1931 at_enter(AT_STANDOUT);
1936 at_enter(AT_STANDOUT);
1937 blanks = (char *) ecalloc(w.numtextcols, sizeof(char));
1938 for (col = 0; col < w.numtextcols; col++)
1940 for (row = w.numtextrows; row > 0; row--)
1941 _outmem(blanks, w.numtextcols);
1948 #if MSDOS_COMPILER==BORLANDC
1951 whitescreen = (unsigned short *)
1952 malloc(sc_width * sc_height * sizeof(short));
1953 if (whitescreen == NULL)
1955 for (n = 0; n < sc_width * sc_height; n++)
1956 whitescreen[n] = 0x7020;
1958 #if MSDOS_COMPILER==WIN32C
1961 whitescreen = (WORD *)
1962 malloc(sc_height * sc_width * sizeof(WORD));
1963 if (whitescreen == NULL)
1965 /* Invert the standard colors. */
1966 for (n = 0; n < sc_width * sc_height; n++)
1967 whitescreen[n] = (WORD)((nm_fg_color << 4) | nm_bg_color);
1973 #endif /* MSDOS_COMPILER */
1976 * Output the "visual bell", if there is one.
1982 if (*sc_visual_bell == '\0')
1984 tputs(sc_visual_bell, sc_height, putchr);
1986 #if MSDOS_COMPILER==DJGPPC
1989 #if MSDOS_COMPILER==MSOFTC
1991 * Create a flash screen on the second video page.
1992 * Switch to that page, then switch back.
2002 #if MSDOS_COMPILER==BORLANDC
2003 unsigned short *currscreen;
2006 * Get a copy of the current screen.
2007 * Display the flash screen.
2008 * Then restore the old screen.
2012 if (whitescreen == NULL)
2014 currscreen = (unsigned short *)
2015 malloc(sc_width * sc_height * sizeof(short));
2016 if (currscreen == NULL) return;
2017 gettext(1, 1, sc_width, sc_height, currscreen);
2018 puttext(1, 1, sc_width, sc_height, whitescreen);
2020 puttext(1, 1, sc_width, sc_height, currscreen);
2023 #if MSDOS_COMPILER==WIN32C
2024 /* paint screen with an inverse color */
2027 /* leave it displayed for 100 msec. */
2030 /* restore with a redraw */
2046 putchr(CONTROL('G'));
2048 #if MSDOS_COMPILER==WIN32C
2057 * Ring the terminal bell.
2062 if (quiet == VERY_QUIET)
2075 tputs(sc_clear, sc_height, putchr);
2078 #if MSDOS_COMPILER==WIN32C
2081 _clearscreen(_GCLEARSCREEN);
2087 * Clear from the cursor to the end of the cursor's line.
2088 * {{ This must not move the cursor. }}
2094 tputs(sc_eol_clear, 1, putchr);
2096 #if MSDOS_COMPILER==MSOFTC
2099 struct rccoord tpos;
2103 * Save current state.
2105 tpos = _gettextposition();
2106 _gettextwindow(&top, &left, &bot, &right);
2108 * Set a temporary window to the current line,
2109 * from the cursor's position to the right edge of the screen.
2110 * Then clear that window.
2112 _settextwindow(tpos.row, tpos.col, tpos.row, sc_width);
2113 _clearscreen(_GWINDOW);
2117 _settextwindow(top, left, bot, right);
2118 _settextposition(tpos.row, tpos.col);
2120 #if MSDOS_COMPILER==BORLANDC || MSDOS_COMPILER==DJGPPC
2124 #if MSDOS_COMPILER==WIN32C
2127 CONSOLE_SCREEN_BUFFER_INFO scr;
2130 memset(&scr, 0, sizeof(scr));
2131 GetConsoleScreenBufferInfo(con_out, &scr);
2132 cpos.X = scr.dwCursorPosition.X;
2133 cpos.Y = scr.dwCursorPosition.Y;
2134 curr_attr = MAKEATTR(nm_fg_color, nm_bg_color);
2135 FillConsoleOutputAttribute(con_out, curr_attr,
2136 scr.dwSize.X - cpos.X, cpos, &nchars);
2137 FillConsoleOutputCharacter(con_out, ' ',
2138 scr.dwSize.X - cpos.X, cpos, &nchars);
2146 * Clear the current line.
2147 * Clear the screen if there's off-screen memory below the display.
2156 tputs(sc_eos_clear, 1, putchr);
2158 tputs(sc_eol_clear, 1, putchr);
2163 * Clear the bottom line of the display.
2164 * Leave the cursor at the beginning of the bottom line.
2170 * If we're in a non-normal attribute mode, temporarily exit
2171 * the mode while we do the clear. Some terminals fill the
2172 * cleared area with the current attribute.
2179 if (attrmode == AT_NORMAL)
2183 int saved_attrmode = attrmode;
2187 at_enter(saved_attrmode);
2195 attr = apply_at_specials(attr);
2198 /* The one with the most priority is last. */
2199 if (attr & AT_UNDERLINE)
2200 tputs(sc_u_in, 1, putchr);
2202 tputs(sc_b_in, 1, putchr);
2203 if (attr & AT_BLINK)
2204 tputs(sc_bl_in, 1, putchr);
2205 if (attr & AT_STANDOUT)
2206 tputs(sc_s_in, 1, putchr);
2209 /* The one with the most priority is first. */
2210 if (attr & AT_STANDOUT)
2212 SETCOLORS(so_fg_color, so_bg_color);
2213 } else if (attr & AT_BLINK)
2215 SETCOLORS(bl_fg_color, bl_bg_color);
2217 else if (attr & AT_BOLD)
2219 SETCOLORS(bo_fg_color, bo_bg_color);
2221 else if (attr & AT_UNDERLINE)
2223 SETCOLORS(ul_fg_color, ul_bg_color);
2234 /* Undo things in the reverse order we did them. */
2235 if (attrmode & AT_STANDOUT)
2236 tputs(sc_s_out, 1, putchr);
2237 if (attrmode & AT_BLINK)
2238 tputs(sc_bl_out, 1, putchr);
2239 if (attrmode & AT_BOLD)
2240 tputs(sc_b_out, 1, putchr);
2241 if (attrmode & AT_UNDERLINE)
2242 tputs(sc_u_out, 1, putchr);
2245 SETCOLORS(nm_fg_color, nm_bg_color);
2248 attrmode = AT_NORMAL;
2255 int new_attrmode = apply_at_specials(attr);
2256 int ignore_modes = AT_ANSI;
2258 if ((new_attrmode & ~ignore_modes) != (attrmode & ~ignore_modes))
2266 is_at_equiv(attr1, attr2)
2270 attr1 = apply_at_specials(attr1);
2271 attr2 = apply_at_specials(attr2);
2273 return (attr1 == attr2);
2277 apply_at_specials(attr)
2280 if (attr & AT_BINARY)
2282 if (attr & AT_HILITE)
2283 attr |= AT_STANDOUT;
2284 attr &= ~(AT_BINARY|AT_HILITE);
2289 #if 0 /* No longer used */
2291 * Erase the character to the left of the cursor
2292 * and move the cursor left.
2299 * Erase the previous character by overstriking with a space.
2301 tputs(sc_backspace, 1, putchr);
2303 tputs(sc_backspace, 1, putchr);
2305 #if MSDOS_COMPILER==MSOFTC
2306 struct rccoord tpos;
2309 tpos = _gettextposition();
2312 _settextposition(tpos.row, tpos.col-1);
2314 _settextposition(tpos.row, tpos.col-1);
2316 #if MSDOS_COMPILER==BORLANDC || MSDOS_COMPILER==DJGPPC
2319 #if MSDOS_COMPILER==WIN32C
2322 CONSOLE_SCREEN_BUFFER_INFO scr;
2325 GetConsoleScreenBufferInfo(con_out, &scr);
2326 cpos = scr.dwCursorPosition;
2330 SetConsoleCursorPosition(con_out, cpos);
2331 FillConsoleOutputCharacter(con_out, (TCHAR)' ', 1, cpos, &cChars);
2332 SetConsoleCursorPosition(con_out, cpos);
2341 * Output a plain backspace, without erasing the previous char.
2347 tputs(sc_backspace, 1, putchr);
2353 #if MSDOS_COMPILER==MSOFTC
2354 struct rccoord tpos;
2355 tpos = _gettextposition();
2359 #if MSDOS_COMPILER==BORLANDC || MSDOS_COMPILER==DJGPPC
2363 #if MSDOS_COMPILER==WIN32C
2364 CONSOLE_SCREEN_BUFFER_INFO scr;
2365 GetConsoleScreenBufferInfo(con_out, &scr);
2366 row = scr.dwCursorPosition.Y - scr.srWindow.Top + 1;
2367 col = scr.dwCursorPosition.X - scr.srWindow.Left + 1;
2374 _settextposition(row, col-1);
2375 #endif /* MSDOS_COMPILER */
2378 #if MSDOS_COMPILER==WIN32C
2380 * Determine whether an input character is waiting to be read.
2392 currentKey.ascii = 0;
2393 currentKey.scan = 0;
2396 * Wait for a real key-down event, but
2397 * ignore SHIFT and CONTROL key events.
2401 PeekConsoleInput(tty, &ip, 1, &read);
2404 ReadConsoleInput(tty, &ip, 1, &read);
2405 } while (ip.EventType != KEY_EVENT ||
2406 ip.Event.KeyEvent.bKeyDown != TRUE ||
2407 ip.Event.KeyEvent.wVirtualScanCode == 0 ||
2408 ip.Event.KeyEvent.wVirtualKeyCode == VK_SHIFT ||
2409 ip.Event.KeyEvent.wVirtualKeyCode == VK_CONTROL ||
2410 ip.Event.KeyEvent.wVirtualKeyCode == VK_MENU);
2412 currentKey.ascii = ip.Event.KeyEvent.uChar.AsciiChar;
2413 currentKey.scan = ip.Event.KeyEvent.wVirtualScanCode;
2414 keyCount = ip.Event.KeyEvent.wRepeatCount;
2416 if (ip.Event.KeyEvent.dwControlKeyState &
2417 (LEFT_ALT_PRESSED | RIGHT_ALT_PRESSED))
2419 switch (currentKey.scan)
2421 case PCK_ALT_E: /* letter 'E' */
2422 currentKey.ascii = 0;
2425 } else if (ip.Event.KeyEvent.dwControlKeyState &
2426 (LEFT_CTRL_PRESSED | RIGHT_CTRL_PRESSED))
2428 switch (currentKey.scan)
2430 case PCK_RIGHT: /* right arrow */
2431 currentKey.scan = PCK_CTL_RIGHT;
2433 case PCK_LEFT: /* left arrow */
2434 currentKey.scan = PCK_CTL_LEFT;
2436 case PCK_DELETE: /* delete */
2437 currentKey.scan = PCK_CTL_DELETE;
2440 } else if (ip.Event.KeyEvent.dwControlKeyState & SHIFT_PRESSED)
2442 switch (currentKey.scan)
2444 case PCK_SHIFT_TAB: /* tab */
2445 currentKey.ascii = 0;
2454 * Read a character from the keyboard.
2462 if (pending_scancode)
2464 pending_scancode = 0;
2465 return ((char)(currentKey.scan & 0x00FF));
2468 while (win32_kbhit((HANDLE)tty) == FALSE)
2476 ascii = currentKey.ascii;
2478 * On PC's, the extended keys return a 2 byte sequence beginning
2479 * with '00', so if the ascii code is 00, the next byte will be
2480 * the lsb of the scan code.
2482 pending_scancode = (ascii == 0x00);
2483 return ((char)ascii);
2491 WIN32setcolors(fg, bg)
2501 WIN32textout(text, len)
2505 #if MSDOS_COMPILER==WIN32C
2507 WriteConsole(con_out, text, len, &written, NULL);