2 * Copyright (C) 1984-2017 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;
207 extern int line_count;
210 static char *cheaper();
211 static void tmodes();
215 * These two variables are sometimes defined in,
216 * and needed by, the termcap library.
218 #if MUST_DEFINE_OSPEED
219 extern short ospeed; /* Terminal output baud rate */
220 extern char PC; /* Pad character */
227 extern int quiet; /* If VERY_QUIET, use visual bell for bell */
228 extern int no_back_scroll;
231 extern int no_keypad;
234 extern int screen_trashed;
236 extern int top_scroll;
237 extern int quit_if_one_screen;
240 extern int hilite_search;
243 extern char *tgetstr();
244 extern char *tgoto();
248 * Change terminal to "raw mode", or restore to "normal" mode.
250 * 1. An outstanding read will complete on receipt of a single keystroke.
251 * 2. Input is not echoed.
252 * 3. On output, \n is mapped to \r\n.
253 * 4. \t is NOT expanded into spaces.
254 * 5. Signal-causing characters such as ctrl-C (interrupt),
255 * etc. are NOT disabled.
256 * It doesn't matter whether an input \n is mapped to \r, or vice versa.
262 static int curr_on = 0;
266 erase2_char = '\b'; /* in case OS doesn't know about erase2 */
267 #if HAVE_TERMIOS_H && HAVE_TERMIOS_FUNCS
270 static struct termios save_term;
271 static int saved_term = 0;
276 * Get terminal modes.
281 * Save modes and set certain variables dependent on modes.
289 switch (cfgetospeed(&s))
292 case B0: ospeed = 0; break;
295 case B50: ospeed = 1; break;
298 case B75: ospeed = 2; break;
301 case B110: ospeed = 3; break;
304 case B134: ospeed = 4; break;
307 case B150: ospeed = 5; break;
310 case B200: ospeed = 6; break;
313 case B300: ospeed = 7; break;
316 case B600: ospeed = 8; break;
319 case B1200: ospeed = 9; break;
322 case B1800: ospeed = 10; break;
325 case B2400: ospeed = 11; break;
328 case B4800: ospeed = 12; break;
331 case B9600: ospeed = 13; break;
334 case EXTA: ospeed = 14; break;
337 case EXTB: ospeed = 15; break;
340 case B57600: ospeed = 16; break;
343 case B115200: ospeed = 17; break;
348 erase_char = s.c_cc[VERASE];
350 erase2_char = s.c_cc[VERASE2];
352 kill_char = s.c_cc[VKILL];
354 werase_char = s.c_cc[VWERASE];
356 werase_char = CONTROL('W');
360 * Set the modes to the way we want them.
422 #if MUST_SET_LINE_DISCIPLINE
424 * System's termios is broken; need to explicitly
425 * request TERMIODISC line discipline.
427 s.c_line = TERMIODISC;
432 * Restore saved modes.
439 tcsetattr(tty, TCSADRAIN, &s);
440 #if MUST_SET_LINE_DISCIPLINE
444 * Broken termios *ignores* any line discipline
445 * except TERMIODISC. A different old line discipline
446 * is therefore not restored, yet. Restore the old
447 * line discipline by hand.
449 ioctl(tty, TIOCSETD, &save_term.c_line);
457 static struct termio save_term;
458 static int saved_term = 0;
463 * Get terminal modes.
465 ioctl(tty, TCGETA, &s);
468 * Save modes and set certain variables dependent on modes.
476 ospeed = s.c_cflag & CBAUD;
478 erase_char = s.c_cc[VERASE];
479 kill_char = s.c_cc[VKILL];
481 werase_char = s.c_cc[VWERASE];
483 werase_char = CONTROL('W');
487 * Set the modes to the way we want them.
489 s.c_lflag &= ~(ICANON|ECHO|ECHOE|ECHOK|ECHONL);
490 s.c_oflag |= (OPOST|ONLCR|TAB3);
491 s.c_oflag &= ~(OCRNL|ONOCR|ONLRET);
497 * Restore saved modes.
501 ioctl(tty, TCSETAW, &s);
507 static struct sgttyb save_term;
508 static int saved_term = 0;
513 * Get terminal modes.
515 ioctl(tty, TIOCGETP, &s);
518 * Save modes and set certain variables dependent on modes.
526 ospeed = s.sg_ospeed;
528 erase_char = s.sg_erase;
529 kill_char = s.sg_kill;
530 werase_char = CONTROL('W');
533 * Set the modes to the way we want them.
535 s.sg_flags |= CBREAK;
536 s.sg_flags &= ~(ECHO|XTABS);
540 * Restore saved modes.
544 ioctl(tty, TIOCSETN, &s);
550 static struct sgbuf save_term;
551 static int saved_term = 0;
556 * Get terminal modes.
561 * Save modes and set certain variables dependent on modes.
568 erase_char = s.sg_bspch;
569 kill_char = s.sg_dlnch;
570 werase_char = CONTROL('W');
573 * Set the modes to the way we want them.
582 * Restore saved modes.
589 /* MS-DOS, Windows, or OS2 */
592 LSIGNAL(SIGINT, SIG_IGN);
595 #if MSDOS_COMPILER==DJGPPC
596 kill_char = CONTROL('U');
598 * So that when we shell out or run another program, its
599 * stdin is in cooked mode. We do not switch stdin to binary
600 * mode if fd0 is zero, since that means we were called before
601 * tty was reopened in open_getchr, in which case we would be
602 * changing the original stdin device outside less.
605 setmode(0, on ? O_BINARY : O_TEXT);
609 werase_char = CONTROL('W');
619 * Some glue to prevent calling termcap functions if tgetent() failed.
630 s = lgetenv("LESS_TERMCAP_DEBUG");
631 if (s != NULL && *s != '\0')
633 struct env { struct env *next; char *name; char *value; };
634 static struct env *envs = NULL;
636 for (p = envs; p != NULL; p = p->next)
637 if (strcmp(p->name, capname) == 0)
639 p = (struct env *) ecalloc(1, sizeof(struct env));
640 p->name = save(capname);
641 p->value = (char *) ecalloc(strlen(capname)+3, sizeof(char));
642 sprintf(p->value, "<%s>", capname);
647 strcpy(name, "LESS_TERMCAP_");
648 strcat(name, capname);
649 return (lgetenv(name));
658 if ((s = ltget_env(capname)) != NULL)
659 return (*s != '\0' && *s != '0');
662 return (tgetflag(capname));
671 if ((s = ltget_env(capname)) != NULL)
675 return (tgetnum(capname));
679 ltgetstr(capname, pp)
685 if ((s = ltget_env(capname)) != NULL)
689 return (tgetstr(capname, pp));
691 #endif /* MSDOS_COMPILER */
694 * Get size of the output screen.
706 #define DEF_SC_WIDTH 80
708 #define DEF_SC_HEIGHT 25
710 #define DEF_SC_HEIGHT 24
714 sys_width = sys_height = 0;
716 #if MSDOS_COMPILER==MSOFTC
718 struct videoconfig w;
720 sys_height = w.numtextrows;
721 sys_width = w.numtextcols;
724 #if MSDOS_COMPILER==BORLANDC || MSDOS_COMPILER==DJGPPC
728 sys_height = w.screenheight;
729 sys_width = w.screenwidth;
732 #if MSDOS_COMPILER==WIN32C
734 CONSOLE_SCREEN_BUFFER_INFO scr;
735 GetConsoleScreenBufferInfo(con_out, &scr);
736 sys_height = scr.srWindow.Bottom - scr.srWindow.Top + 1;
737 sys_width = scr.srWindow.Right - scr.srWindow.Left + 1;
747 * When using terminal emulators for XFree86/OS2, the
748 * _scrsize function does not work well.
749 * Call the scrsize.exe program to get the window size.
751 windowid = getenv("WINDOWID");
752 if (windowid != NULL)
754 FILE *fd = popen("scrsize", "rt");
758 fscanf(fd, "%i %i", &w, &h);
772 if (ioctl(2, TIOCGWINSZ, &w) == 0)
775 sys_height = w.ws_row;
777 sys_width = w.ws_col;
784 if (ioctl(2, WIOCGETD, &w) == 0)
787 sys_height = w.uw_height / w.uw_vs;
789 sys_width = w.uw_width / w.uw_hs;
800 sc_height = sys_height;
801 else if ((s = lgetenv("LINES")) != NULL)
804 else if ((n = ltgetnum("li")) > 0)
808 sc_height = DEF_SC_HEIGHT;
811 sc_width = sys_width;
812 else if ((s = lgetenv("COLUMNS")) != NULL)
815 else if ((n = ltgetnum("co")) > 0)
819 sc_width = DEF_SC_WIDTH;
822 #if MSDOS_COMPILER==MSOFTC
824 * Figure out how many empty loops it takes to delay a millisecond.
832 * Get synchronized at the start of a tick.
835 while (clock() == start)
838 * Now count loops till the next tick.
842 while (clock() == start)
845 * Convert from (loops per clock) to (loops per millisecond).
847 msec_loops *= CLOCKS_PER_SEC;
852 * Delay for a specified number of milliseconds.
857 static long delay_dummy = 0;
869 for (i = 0; i < msec_loops; i++)
872 * Make it look like we're doing something here,
873 * so the optimizer doesn't remove the whole loop.
882 * Return the characters actually input by a "special" key.
888 static char tbuf[40];
890 #if MSDOS_COMPILER || OS2
891 static char k_right[] = { '\340', PCK_RIGHT, 0 };
892 static char k_left[] = { '\340', PCK_LEFT, 0 };
893 static char k_ctl_right[] = { '\340', PCK_CTL_RIGHT, 0 };
894 static char k_ctl_left[] = { '\340', PCK_CTL_LEFT, 0 };
895 static char k_insert[] = { '\340', PCK_INSERT, 0 };
896 static char k_delete[] = { '\340', PCK_DELETE, 0 };
897 static char k_ctl_delete[] = { '\340', PCK_CTL_DELETE, 0 };
898 static char k_ctl_backspace[] = { '\177', 0 };
899 static char k_home[] = { '\340', PCK_HOME, 0 };
900 static char k_end[] = { '\340', PCK_END, 0 };
901 static char k_up[] = { '\340', PCK_UP, 0 };
902 static char k_down[] = { '\340', PCK_DOWN, 0 };
903 static char k_backtab[] = { '\340', PCK_SHIFT_TAB, 0 };
904 static char k_pagedown[] = { '\340', PCK_PAGEDOWN, 0 };
905 static char k_pageup[] = { '\340', PCK_PAGEUP, 0 };
906 static char k_f1[] = { '\340', PCK_F1, 0 };
916 * If windowid is not NULL, assume less is executed in
917 * the XFree86 environment.
920 s = windowid ? ltgetstr("kr", &sp) : k_right;
923 s = windowid ? ltgetstr("kl", &sp) : k_left;
926 s = windowid ? ltgetstr("ku", &sp) : k_up;
929 s = windowid ? ltgetstr("kd", &sp) : k_down;
932 s = windowid ? ltgetstr("kP", &sp) : k_pageup;
935 s = windowid ? ltgetstr("kN", &sp) : k_pagedown;
938 s = windowid ? ltgetstr("kh", &sp) : k_home;
941 s = windowid ? ltgetstr("@7", &sp) : k_end;
946 s = ltgetstr("kD", &sp);
986 #if MSDOS_COMPILER || OS2
990 case SK_CTL_LEFT_ARROW:
993 case SK_CTL_RIGHT_ARROW:
996 case SK_CTL_BACKSPACE:
1009 case SK_RIGHT_ARROW:
1010 s = ltgetstr("kr", &sp);
1013 s = ltgetstr("kl", &sp);
1016 s = ltgetstr("ku", &sp);
1019 s = ltgetstr("kd", &sp);
1022 s = ltgetstr("kP", &sp);
1025 s = ltgetstr("kN", &sp);
1028 s = ltgetstr("kh", &sp);
1031 s = ltgetstr("@7", &sp);
1034 s = ltgetstr("kD", &sp);
1044 tbuf[0] = CONTROL('K');
1055 * Get terminal capabilities via termcap.
1066 * Set up default colors.
1067 * The xx_s_width and xx_e_width vars are already initialized to 0.
1069 #if MSDOS_COMPILER==MSOFTC
1070 sy_bg_color = _getbkcolor();
1071 sy_fg_color = _gettextcolor();
1074 #if MSDOS_COMPILER==BORLANDC || MSDOS_COMPILER==DJGPPC
1078 sy_bg_color = (w.attribute >> 4) & 0x0F;
1079 sy_fg_color = (w.attribute >> 0) & 0x0F;
1082 #if MSDOS_COMPILER==WIN32C
1085 CONSOLE_SCREEN_BUFFER_INFO scr;
1087 con_out_save = con_out = GetStdHandle(STD_OUTPUT_HANDLE);
1089 * Always open stdin in binary. Note this *must* be done
1090 * before any file operations have been done on fd0.
1093 GetConsoleScreenBufferInfo(con_out, &scr);
1094 ReadConsoleOutputAttribute(con_out, &curr_attr,
1095 1, scr.dwCursorPosition, &nread);
1096 sy_bg_color = (curr_attr & BG_COLORS) >> 4; /* normalize */
1097 sy_fg_color = curr_attr & FG_COLORS;
1102 nm_fg_color = sy_fg_color;
1103 nm_bg_color = sy_bg_color;
1115 * Get size of the screen.
1121 #else /* !MSDOS_COMPILER */
1126 char termbuf[TERMBUF_SIZE];
1128 static char sbuf[TERMSBUF_SIZE];
1132 * Make sure the termcap database is available.
1134 sp = lgetenv("TERMCAP");
1135 if (sp == NULL || *sp == '\0')
1138 if ((sp = homefile("termcap.dat")) != NULL)
1140 termcap = (char *) ecalloc(strlen(sp)+9, sizeof(char));
1141 sprintf(termcap, "TERMCAP=%s", sp);
1148 * Find out what kind of terminal this is.
1150 if ((term = lgetenv("TERM")) == NULL)
1151 term = DEFAULT_TERM;
1153 if (tgetent(termbuf, term) != TGETENT_OK)
1155 if (ltgetflag("hc"))
1159 * Get size of the screen.
1164 auto_wrap = ltgetflag("am");
1165 ignaw = ltgetflag("xn");
1166 above_mem = ltgetflag("da");
1167 below_mem = ltgetflag("db");
1168 clear_bg = ltgetflag("ut");
1171 * Assumes termcap variable "sg" is the printing width of:
1172 * the standout sequence, the end standout sequence,
1173 * the underline sequence, the end underline sequence,
1174 * the boldface sequence, and the end boldface sequence.
1176 if ((so_s_width = ltgetnum("sg")) < 0)
1178 so_e_width = so_s_width;
1180 bo_s_width = bo_e_width = so_s_width;
1181 ul_s_width = ul_e_width = so_s_width;
1182 bl_s_width = bl_e_width = so_s_width;
1185 if (so_s_width > 0 || so_e_width > 0)
1187 * Disable highlighting by default on magic cookie terminals.
1188 * Turning on highlighting might change the displayed width
1189 * of a line, causing the display to get messed up.
1190 * The user can turn it back on with -g,
1191 * but she won't like the results.
1197 * Get various string-valued capabilities.
1202 sc_pad = ltgetstr("pc", &sp);
1207 sc_s_keypad = ltgetstr("ks", &sp);
1208 if (sc_s_keypad == NULL)
1210 sc_e_keypad = ltgetstr("ke", &sp);
1211 if (sc_e_keypad == NULL)
1214 sc_init = ltgetstr("ti", &sp);
1215 if (sc_init == NULL)
1218 sc_deinit= ltgetstr("te", &sp);
1219 if (sc_deinit == NULL)
1222 sc_eol_clear = ltgetstr("ce", &sp);
1223 if (sc_eol_clear == NULL || *sc_eol_clear == '\0')
1229 sc_eos_clear = ltgetstr("cd", &sp);
1230 if (below_mem && (sc_eos_clear == NULL || *sc_eos_clear == '\0'))
1236 sc_clear = ltgetstr("cl", &sp);
1237 if (sc_clear == NULL || *sc_clear == '\0')
1243 sc_move = ltgetstr("cm", &sp);
1244 if (sc_move == NULL || *sc_move == '\0')
1247 * This is not an error here, because we don't
1248 * always need sc_move.
1249 * We need it only if we don't have home or lower-left.
1256 tmodes("so", "se", &sc_s_in, &sc_s_out, "", "", &sp);
1257 tmodes("us", "ue", &sc_u_in, &sc_u_out, sc_s_in, sc_s_out, &sp);
1258 tmodes("md", "me", &sc_b_in, &sc_b_out, sc_s_in, sc_s_out, &sp);
1259 tmodes("mb", "me", &sc_bl_in, &sc_bl_out, sc_s_in, sc_s_out, &sp);
1261 sc_visual_bell = ltgetstr("vb", &sp);
1262 if (sc_visual_bell == NULL)
1263 sc_visual_bell = "";
1265 if (ltgetflag("bs"))
1266 sc_backspace = "\b";
1269 sc_backspace = ltgetstr("bc", &sp);
1270 if (sc_backspace == NULL || *sc_backspace == '\0')
1271 sc_backspace = "\b";
1275 * Choose between using "ho" and "cm" ("home" and "cursor move")
1276 * to move the cursor to the upper left corner of the screen.
1278 t1 = ltgetstr("ho", &sp);
1281 if (*sc_move == '\0')
1285 strcpy(sp, tgoto(sc_move, 0, 0));
1287 sp += strlen(sp) + 1;
1289 sc_home = cheaper(t1, t2, "|\b^");
1292 * Choose between using "ll" and "cm" ("lower left" and "cursor move")
1293 * to move the cursor to the lower left corner of the screen.
1295 t1 = ltgetstr("ll", &sp);
1298 if (*sc_move == '\0')
1302 strcpy(sp, tgoto(sc_move, 0, sc_height-1));
1304 sp += strlen(sp) + 1;
1306 sc_lower_left = cheaper(t1, t2, "\r");
1309 * Get carriage return string.
1311 sc_return = ltgetstr("cr", &sp);
1312 if (sc_return == NULL)
1316 * Choose between using "al" or "sr" ("add line" or "scroll reverse")
1317 * to add a line at the top of the screen.
1319 t1 = ltgetstr("al", &sp);
1322 t2 = ltgetstr("sr", &sp);
1326 if (*t1 == '\0' && *t2 == '\0')
1333 sc_addline = cheaper(t1, t2, "");
1334 if (*sc_addline == '\0')
1337 * Force repaint on any backward movement.
1341 #endif /* MSDOS_COMPILER */
1346 * Return the cost of displaying a termcap string.
1347 * We use the trick of calling tputs, but as a char printing function
1348 * we give it inc_costcount, which just increments "costcount".
1349 * This tells us how many chars would be printed by using this string.
1350 * {{ Couldn't we just use strlen? }}
1352 static int costcount;
1368 tputs(t, sc_height, inc_costcount);
1373 * Return the "best" of the two given termcap strings.
1374 * The best, if both exist, is the one with the lower
1375 * cost (see cost() function).
1378 cheaper(t1, t2, def)
1382 if (*t1 == '\0' && *t2 == '\0')
1391 if (cost(t1) < cost(t2))
1397 tmodes(incap, outcap, instr, outstr, def_instr, def_outstr, spp)
1406 *instr = ltgetstr(incap, spp);
1411 *outstr = def_outstr;
1415 *outstr = ltgetstr(outcap, spp);
1416 if (*outstr == NULL)
1417 /* No specific out capability; use "me". */
1418 *outstr = ltgetstr("me", spp);
1419 if (*outstr == NULL)
1420 /* Don't even have "me"; use a null string. */
1424 #endif /* MSDOS_COMPILER */
1428 * Below are the functions which perform all the
1429 * terminal-specific screen manipulation.
1435 #if MSDOS_COMPILER==WIN32C
1437 _settextposition(int row, int col)
1440 CONSOLE_SCREEN_BUFFER_INFO csbi;
1442 GetConsoleScreenBufferInfo(con_out, &csbi);
1443 cpos.X = csbi.srWindow.Left + (col - 1);
1444 cpos.Y = csbi.srWindow.Top + (row - 1);
1445 SetConsoleCursorPosition(con_out, cpos);
1450 * Initialize the screen to the correct color at startup.
1455 #if MSDOS_COMPILER==BORLANDC || MSDOS_COMPILER==DJGPPC
1458 SETCOLORS(nm_fg_color, nm_bg_color);
1461 * This clears the screen at startup. This is different from
1462 * the behavior of other versions of less. Disable it for now.
1469 * Create a complete, blank screen using "normal" colors.
1471 SETCOLORS(nm_fg_color, nm_bg_color);
1472 blanks = (char *) ecalloc(width+1, sizeof(char));
1473 for (col = 0; col < sc_width; col++)
1475 blanks[sc_width] = '\0';
1476 for (row = 0; row < sc_height; row++)
1483 #if MSDOS_COMPILER==WIN32C
1486 * Termcap-like init with a private win32 console.
1491 CONSOLE_SCREEN_BUFFER_INFO scr;
1494 if (con_out_save == INVALID_HANDLE_VALUE)
1497 GetConsoleScreenBufferInfo(con_out_save, &scr);
1499 if (con_out_ours == INVALID_HANDLE_VALUE)
1502 * Create our own screen buffer, so that we
1503 * may restore the original when done.
1505 con_out_ours = CreateConsoleScreenBuffer(
1506 GENERIC_WRITE | GENERIC_READ,
1507 FILE_SHARE_WRITE | FILE_SHARE_READ,
1508 (LPSECURITY_ATTRIBUTES) NULL,
1509 CONSOLE_TEXTMODE_BUFFER,
1513 size.X = scr.srWindow.Right - scr.srWindow.Left + 1;
1514 size.Y = scr.srWindow.Bottom - scr.srWindow.Top + 1;
1515 SetConsoleScreenBufferSize(con_out_ours, size);
1516 SetConsoleActiveScreenBuffer(con_out_ours);
1517 con_out = con_out_ours;
1521 * Restore the startup console.
1526 if (con_out_save == INVALID_HANDLE_VALUE)
1529 (void) CloseHandle(con_out_ours);
1530 SetConsoleActiveScreenBuffer(con_out_save);
1531 con_out = con_out_save;
1537 * Initialize terminal
1543 if (quit_if_one_screen && line_count >= sc_height)
1544 quit_if_one_screen = FALSE;
1545 if (!no_init && !quit_if_one_screen)
1546 tputs(sc_init, sc_height, putchr);
1548 tputs(sc_s_keypad, sc_height, putchr);
1554 * This is nice to terminals with no alternate screen,
1555 * but with saved scrolled-off-the-top lines. This way,
1556 * no previous line is lost, but we start with a whole
1557 * screen to ourself.
1559 for (i = 1; i < sc_height; i++)
1564 #if MSDOS_COMPILER==WIN32C
1575 * Deinitialize terminal
1584 tputs(sc_e_keypad, sc_height, putchr);
1585 if (!no_init && !quit_if_one_screen)
1586 tputs(sc_deinit, sc_height, putchr);
1588 /* Restore system colors. */
1589 SETCOLORS(sy_fg_color, sy_bg_color);
1590 #if MSDOS_COMPILER==WIN32C
1592 win32_deinit_term();
1594 /* Need clreol to make SETCOLORS take effect. */
1602 * Home cursor (move to upper left corner of screen).
1608 tputs(sc_home, 1, putchr);
1611 _settextposition(1,1);
1616 * Add a blank line (called with cursor at home).
1617 * Should scroll the display down.
1623 tputs(sc_addline, sc_height, putchr);
1626 #if MSDOS_COMPILER==MSOFTC
1627 _scrolltextwindow(_GSCROLLDOWN);
1628 _settextposition(1,1);
1630 #if MSDOS_COMPILER==BORLANDC || MSDOS_COMPILER==DJGPPC
1631 movetext(1,1, sc_width,sc_height-1, 1,2);
1635 #if MSDOS_COMPILER==WIN32C
1638 SMALL_RECT rcSrc, rcClip;
1640 CONSOLE_SCREEN_BUFFER_INFO csbi;
1642 GetConsoleScreenBufferInfo(con_out,&csbi);
1644 /* The clip rectangle is the entire visible screen. */
1645 rcClip.Left = csbi.srWindow.Left;
1646 rcClip.Top = csbi.srWindow.Top;
1647 rcClip.Right = csbi.srWindow.Right;
1648 rcClip.Bottom = csbi.srWindow.Bottom;
1650 /* The source rectangle is the visible screen minus the last line. */
1654 /* Move the top left corner of the source window down one row. */
1655 new_org.X = rcSrc.Left;
1656 new_org.Y = rcSrc.Top + 1;
1658 /* Fill the right character and attributes. */
1659 fillchar.Char.AsciiChar = ' ';
1660 curr_attr = MAKEATTR(nm_fg_color, nm_bg_color);
1661 fillchar.Attributes = curr_attr;
1662 ScrollConsoleScreenBuffer(con_out, &rcSrc, &rcClip, new_org, &fillchar);
1663 _settextposition(1,1);
1673 * Remove the n topmost lines and scroll everything below it in the
1674 * window upward. This is needed to stop leaking the topmost line
1675 * into the scrollback buffer when we go down-one-line (in WIN32).
1681 #if MSDOS_COMPILER==WIN32C
1682 SMALL_RECT rcSrc, rcClip;
1685 CONSOLE_SCREEN_BUFFER_INFO csbi; /* to get buffer info */
1687 if (n >= sc_height - 1)
1696 GetConsoleScreenBufferInfo(con_out, &csbi);
1698 /* Get the extent of all-visible-rows-but-the-last. */
1699 rcSrc.Left = csbi.srWindow.Left;
1700 rcSrc.Top = csbi.srWindow.Top + n;
1701 rcSrc.Right = csbi.srWindow.Right;
1702 rcSrc.Bottom = csbi.srWindow.Bottom;
1704 /* Get the clip rectangle. */
1705 rcClip.Left = rcSrc.Left;
1706 rcClip.Top = csbi.srWindow.Top;
1707 rcClip.Right = rcSrc.Right;
1708 rcClip.Bottom = rcSrc.Bottom ;
1710 /* Move the source window up n rows. */
1711 new_org.X = rcSrc.Left;
1712 new_org.Y = rcSrc.Top - n;
1714 /* Fill the right character and attributes. */
1715 fillchar.Char.AsciiChar = ' ';
1716 curr_attr = MAKEATTR(nm_fg_color, nm_bg_color);
1717 fillchar.Attributes = curr_attr;
1719 ScrollConsoleScreenBuffer(con_out, &rcSrc, &rcClip, new_org, &fillchar);
1721 /* Position cursor on first blank line. */
1722 goto_line(sc_height - n - 1);
1727 #if MSDOS_COMPILER==WIN32C
1735 * This will clear only the currently visible rows of the NT
1736 * console buffer, which means none of the precious scrollback
1737 * rows are touched making for faster scrolling. Note that, if
1738 * the window has fewer columns than the console buffer (i.e.
1739 * there is a horizontal scrollbar as well), the entire width
1740 * of the visible rows will be cleared.
1745 CONSOLE_SCREEN_BUFFER_INFO csbi;
1747 /* get the number of cells in the current buffer */
1748 GetConsoleScreenBufferInfo(con_out, &csbi);
1749 winsz = csbi.dwSize.X * (csbi.srWindow.Bottom - csbi.srWindow.Top + 1);
1751 topleft.Y = csbi.srWindow.Top;
1753 curr_attr = MAKEATTR(nm_fg_color, nm_bg_color);
1754 FillConsoleOutputCharacter(con_out, ' ', winsz, topleft, &nchars);
1755 FillConsoleOutputAttribute(con_out, curr_attr, winsz, topleft, &nchars);
1759 * Remove the n topmost lines and scroll everything below it in the
1766 SMALL_RECT rcSrc, rcClip;
1772 CONSOLE_SCREEN_BUFFER_INFO csbi;
1777 if (n >= sc_height - 1)
1780 _settextposition(1,1);
1784 /* Get the extent of what will remain visible after scrolling. */
1785 GetConsoleScreenBufferInfo(con_out, &csbi);
1786 rcSrc.Left = csbi.srWindow.Left;
1787 rcSrc.Top = csbi.srWindow.Top + n;
1788 rcSrc.Right = csbi.srWindow.Right;
1789 rcSrc.Bottom = csbi.srWindow.Bottom;
1791 /* Get the clip rectangle. */
1792 rcClip.Left = rcSrc.Left;
1793 rcClip.Top = csbi.srWindow.Top;
1794 rcClip.Right = rcSrc.Right;
1795 rcClip.Bottom = rcSrc.Bottom ;
1797 /* Move the source text to the top of the screen. */
1798 new_org.X = rcSrc.Left;
1799 new_org.Y = rcClip.Top;
1801 /* Fill the right character and attributes. */
1802 fillchar.Char.AsciiChar = ' ';
1803 fillchar.Attributes = MAKEATTR(nm_fg_color, nm_bg_color);
1805 /* Scroll the window. */
1806 SetConsoleTextAttribute(con_out, fillchar.Attributes);
1807 ScrollConsoleScreenBuffer(con_out, &rcSrc, &rcClip, new_org, &fillchar);
1809 /* Clear remaining lines at bottom. */
1810 topleft.X = csbi.dwCursorPosition.X;
1811 topleft.Y = rcSrc.Bottom - n;
1812 size = (n * csbi.dwSize.X) + (rcSrc.Right - topleft.X);
1813 FillConsoleOutputCharacter(con_out, ' ', size, topleft,
1815 FillConsoleOutputAttribute(con_out, fillchar.Attributes, size, topleft,
1817 SetConsoleTextAttribute(con_out, curr_attr);
1819 /* Move cursor n lines up from where it was. */
1820 csbi.dwCursorPosition.Y -= n;
1821 SetConsoleCursorPosition(con_out, csbi.dwCursorPosition);
1826 * Move cursor to lower left corner of screen.
1832 tputs(sc_lower_left, 1, putchr);
1835 _settextposition(sc_height, 1);
1840 * Move cursor to left position of current line.
1846 tputs(sc_return, 1, putchr);
1850 #if MSDOS_COMPILER==WIN32C
1852 CONSOLE_SCREEN_BUFFER_INFO scr;
1853 GetConsoleScreenBufferInfo(con_out, &scr);
1854 row = scr.dwCursorPosition.Y - scr.srWindow.Top + 1;
1857 #if MSDOS_COMPILER==BORLANDC || MSDOS_COMPILER==DJGPPC
1861 struct rccoord tpos = _gettextposition();
1866 _settextposition(row, 1);
1871 * Check if the console size has changed and reset internals
1872 * (in lieu of SIGWINCH for WIN32).
1877 #if MSDOS_COMPILER==WIN32C
1878 CONSOLE_SCREEN_BUFFER_INFO scr;
1881 if (con_out == INVALID_HANDLE_VALUE)
1885 GetConsoleScreenBufferInfo(con_out, &scr);
1886 size.Y = scr.srWindow.Bottom - scr.srWindow.Top + 1;
1887 size.X = scr.srWindow.Right - scr.srWindow.Left + 1;
1888 if (size.Y != sc_height || size.X != sc_width)
1892 if (!no_init && con_out_ours == con_out)
1893 SetConsoleScreenBufferSize(con_out, size);
1895 wscroll = (sc_height + 1) / 2;
1902 * Goto a specific line on the screen.
1909 tputs(tgoto(sc_move, 0, slinenum), 1, putchr);
1912 _settextposition(slinenum+1, 1);
1916 #if MSDOS_COMPILER==MSOFTC || MSDOS_COMPILER==BORLANDC
1918 * Create an alternate screen which is all white.
1919 * This screen is used to create a "flash" effect, by displaying it
1920 * briefly and then switching back to the normal screen.
1921 * {{ Yuck! There must be a better way to get a visual bell. }}
1926 #if MSDOS_COMPILER==MSOFTC
1927 struct videoconfig w;
1931 _getvideoconfig(&w);
1932 videopages = w.numvideopages;
1935 at_enter(AT_STANDOUT);
1940 at_enter(AT_STANDOUT);
1941 blanks = (char *) ecalloc(w.numtextcols, sizeof(char));
1942 for (col = 0; col < w.numtextcols; col++)
1944 for (row = w.numtextrows; row > 0; row--)
1945 _outmem(blanks, w.numtextcols);
1952 #if MSDOS_COMPILER==BORLANDC
1955 whitescreen = (unsigned short *)
1956 malloc(sc_width * sc_height * sizeof(short));
1957 if (whitescreen == NULL)
1959 for (n = 0; n < sc_width * sc_height; n++)
1960 whitescreen[n] = 0x7020;
1962 #if MSDOS_COMPILER==WIN32C
1965 whitescreen = (WORD *)
1966 malloc(sc_height * sc_width * sizeof(WORD));
1967 if (whitescreen == NULL)
1969 /* Invert the standard colors. */
1970 for (n = 0; n < sc_width * sc_height; n++)
1971 whitescreen[n] = (WORD)((nm_fg_color << 4) | nm_bg_color);
1977 #endif /* MSDOS_COMPILER */
1980 * Output the "visual bell", if there is one.
1986 if (*sc_visual_bell == '\0')
1988 tputs(sc_visual_bell, sc_height, putchr);
1990 #if MSDOS_COMPILER==DJGPPC
1993 #if MSDOS_COMPILER==MSOFTC
1995 * Create a flash screen on the second video page.
1996 * Switch to that page, then switch back.
2006 #if MSDOS_COMPILER==BORLANDC
2007 unsigned short *currscreen;
2010 * Get a copy of the current screen.
2011 * Display the flash screen.
2012 * Then restore the old screen.
2016 if (whitescreen == NULL)
2018 currscreen = (unsigned short *)
2019 malloc(sc_width * sc_height * sizeof(short));
2020 if (currscreen == NULL) return;
2021 gettext(1, 1, sc_width, sc_height, currscreen);
2022 puttext(1, 1, sc_width, sc_height, whitescreen);
2024 puttext(1, 1, sc_width, sc_height, currscreen);
2027 #if MSDOS_COMPILER==WIN32C
2028 /* paint screen with an inverse color */
2031 /* leave it displayed for 100 msec. */
2034 /* restore with a redraw */
2050 putchr(CONTROL('G'));
2052 #if MSDOS_COMPILER==WIN32C
2061 * Ring the terminal bell.
2066 if (quiet == VERY_QUIET)
2079 tputs(sc_clear, sc_height, putchr);
2082 #if MSDOS_COMPILER==WIN32C
2085 _clearscreen(_GCLEARSCREEN);
2091 * Clear from the cursor to the end of the cursor's line.
2092 * {{ This must not move the cursor. }}
2098 tputs(sc_eol_clear, 1, putchr);
2100 #if MSDOS_COMPILER==MSOFTC
2103 struct rccoord tpos;
2107 * Save current state.
2109 tpos = _gettextposition();
2110 _gettextwindow(&top, &left, &bot, &right);
2112 * Set a temporary window to the current line,
2113 * from the cursor's position to the right edge of the screen.
2114 * Then clear that window.
2116 _settextwindow(tpos.row, tpos.col, tpos.row, sc_width);
2117 _clearscreen(_GWINDOW);
2121 _settextwindow(top, left, bot, right);
2122 _settextposition(tpos.row, tpos.col);
2124 #if MSDOS_COMPILER==BORLANDC || MSDOS_COMPILER==DJGPPC
2128 #if MSDOS_COMPILER==WIN32C
2131 CONSOLE_SCREEN_BUFFER_INFO scr;
2134 memset(&scr, 0, sizeof(scr));
2135 GetConsoleScreenBufferInfo(con_out, &scr);
2136 cpos.X = scr.dwCursorPosition.X;
2137 cpos.Y = scr.dwCursorPosition.Y;
2138 curr_attr = MAKEATTR(nm_fg_color, nm_bg_color);
2139 FillConsoleOutputAttribute(con_out, curr_attr,
2140 scr.dwSize.X - cpos.X, cpos, &nchars);
2141 FillConsoleOutputCharacter(con_out, ' ',
2142 scr.dwSize.X - cpos.X, cpos, &nchars);
2150 * Clear the current line.
2151 * Clear the screen if there's off-screen memory below the display.
2160 tputs(sc_eos_clear, 1, putchr);
2162 tputs(sc_eol_clear, 1, putchr);
2167 * Clear the bottom line of the display.
2168 * Leave the cursor at the beginning of the bottom line.
2174 * If we're in a non-normal attribute mode, temporarily exit
2175 * the mode while we do the clear. Some terminals fill the
2176 * cleared area with the current attribute.
2183 if (attrmode == AT_NORMAL)
2187 int saved_attrmode = attrmode;
2191 at_enter(saved_attrmode);
2199 attr = apply_at_specials(attr);
2202 /* The one with the most priority is last. */
2203 if (attr & AT_UNDERLINE)
2204 tputs(sc_u_in, 1, putchr);
2206 tputs(sc_b_in, 1, putchr);
2207 if (attr & AT_BLINK)
2208 tputs(sc_bl_in, 1, putchr);
2209 if (attr & AT_STANDOUT)
2210 tputs(sc_s_in, 1, putchr);
2213 /* The one with the most priority is first. */
2214 if (attr & AT_STANDOUT)
2216 SETCOLORS(so_fg_color, so_bg_color);
2217 } else if (attr & AT_BLINK)
2219 SETCOLORS(bl_fg_color, bl_bg_color);
2221 else if (attr & AT_BOLD)
2223 SETCOLORS(bo_fg_color, bo_bg_color);
2225 else if (attr & AT_UNDERLINE)
2227 SETCOLORS(ul_fg_color, ul_bg_color);
2238 /* Undo things in the reverse order we did them. */
2239 if (attrmode & AT_STANDOUT)
2240 tputs(sc_s_out, 1, putchr);
2241 if (attrmode & AT_BLINK)
2242 tputs(sc_bl_out, 1, putchr);
2243 if (attrmode & AT_BOLD)
2244 tputs(sc_b_out, 1, putchr);
2245 if (attrmode & AT_UNDERLINE)
2246 tputs(sc_u_out, 1, putchr);
2249 SETCOLORS(nm_fg_color, nm_bg_color);
2252 attrmode = AT_NORMAL;
2259 int new_attrmode = apply_at_specials(attr);
2260 int ignore_modes = AT_ANSI;
2262 if ((new_attrmode & ~ignore_modes) != (attrmode & ~ignore_modes))
2270 is_at_equiv(attr1, attr2)
2274 attr1 = apply_at_specials(attr1);
2275 attr2 = apply_at_specials(attr2);
2277 return (attr1 == attr2);
2281 apply_at_specials(attr)
2284 if (attr & AT_BINARY)
2286 if (attr & AT_HILITE)
2287 attr |= AT_STANDOUT;
2288 attr &= ~(AT_BINARY|AT_HILITE);
2293 #if 0 /* No longer used */
2295 * Erase the character to the left of the cursor
2296 * and move the cursor left.
2303 * Erase the previous character by overstriking with a space.
2305 tputs(sc_backspace, 1, putchr);
2307 tputs(sc_backspace, 1, putchr);
2309 #if MSDOS_COMPILER==MSOFTC
2310 struct rccoord tpos;
2313 tpos = _gettextposition();
2316 _settextposition(tpos.row, tpos.col-1);
2318 _settextposition(tpos.row, tpos.col-1);
2320 #if MSDOS_COMPILER==BORLANDC || MSDOS_COMPILER==DJGPPC
2323 #if MSDOS_COMPILER==WIN32C
2326 CONSOLE_SCREEN_BUFFER_INFO scr;
2329 GetConsoleScreenBufferInfo(con_out, &scr);
2330 cpos = scr.dwCursorPosition;
2334 SetConsoleCursorPosition(con_out, cpos);
2335 FillConsoleOutputCharacter(con_out, (TCHAR)' ', 1, cpos, &cChars);
2336 SetConsoleCursorPosition(con_out, cpos);
2345 * Output a plain backspace, without erasing the previous char.
2351 tputs(sc_backspace, 1, putchr);
2357 #if MSDOS_COMPILER==MSOFTC
2358 struct rccoord tpos;
2359 tpos = _gettextposition();
2363 #if MSDOS_COMPILER==BORLANDC || MSDOS_COMPILER==DJGPPC
2367 #if MSDOS_COMPILER==WIN32C
2368 CONSOLE_SCREEN_BUFFER_INFO scr;
2369 GetConsoleScreenBufferInfo(con_out, &scr);
2370 row = scr.dwCursorPosition.Y - scr.srWindow.Top + 1;
2371 col = scr.dwCursorPosition.X - scr.srWindow.Left + 1;
2378 _settextposition(row, col-1);
2379 #endif /* MSDOS_COMPILER */
2382 #if MSDOS_COMPILER==WIN32C
2384 * Determine whether an input character is waiting to be read.
2396 currentKey.ascii = 0;
2397 currentKey.scan = 0;
2400 * Wait for a real key-down event, but
2401 * ignore SHIFT and CONTROL key events.
2405 PeekConsoleInput(tty, &ip, 1, &read);
2408 ReadConsoleInput(tty, &ip, 1, &read);
2409 } while (ip.EventType != KEY_EVENT ||
2410 ip.Event.KeyEvent.bKeyDown != TRUE ||
2411 ip.Event.KeyEvent.wVirtualScanCode == 0 ||
2412 ip.Event.KeyEvent.wVirtualKeyCode == VK_SHIFT ||
2413 ip.Event.KeyEvent.wVirtualKeyCode == VK_CONTROL ||
2414 ip.Event.KeyEvent.wVirtualKeyCode == VK_MENU);
2416 currentKey.ascii = ip.Event.KeyEvent.uChar.AsciiChar;
2417 currentKey.scan = ip.Event.KeyEvent.wVirtualScanCode;
2418 keyCount = ip.Event.KeyEvent.wRepeatCount;
2420 if (ip.Event.KeyEvent.dwControlKeyState &
2421 (LEFT_ALT_PRESSED | RIGHT_ALT_PRESSED))
2423 switch (currentKey.scan)
2425 case PCK_ALT_E: /* letter 'E' */
2426 currentKey.ascii = 0;
2429 } else if (ip.Event.KeyEvent.dwControlKeyState &
2430 (LEFT_CTRL_PRESSED | RIGHT_CTRL_PRESSED))
2432 switch (currentKey.scan)
2434 case PCK_RIGHT: /* right arrow */
2435 currentKey.scan = PCK_CTL_RIGHT;
2437 case PCK_LEFT: /* left arrow */
2438 currentKey.scan = PCK_CTL_LEFT;
2440 case PCK_DELETE: /* delete */
2441 currentKey.scan = PCK_CTL_DELETE;
2444 } else if (ip.Event.KeyEvent.dwControlKeyState & SHIFT_PRESSED)
2446 switch (currentKey.scan)
2448 case PCK_SHIFT_TAB: /* tab */
2449 currentKey.ascii = 0;
2458 * Read a character from the keyboard.
2466 if (pending_scancode)
2468 pending_scancode = 0;
2469 return ((char)(currentKey.scan & 0x00FF));
2472 while (win32_kbhit((HANDLE)tty) == FALSE)
2480 ascii = currentKey.ascii;
2482 * On PC's, the extended keys return a 2 byte sequence beginning
2483 * with '00', so if the ascii code is 00, the next byte will be
2484 * the lsb of the scan code.
2486 pending_scancode = (ascii == 0x00);
2487 return ((char)ascii);
2495 WIN32setcolors(fg, bg)
2505 WIN32textout(text, len)
2509 #if MSDOS_COMPILER==WIN32C
2511 WriteConsole(con_out, text, len, &written, NULL);