2 * Copyright (C) 1984-2002 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 about less, or for information on how to
8 * contact the author, see the README file.
13 * Routines which deal with the characteristics of the terminal.
14 * Uses termcap to be as terminal-independent as possible.
22 #if MSDOS_COMPILER==MSOFTC
25 #if MSDOS_COMPILER==BORLANDC || MSDOS_COMPILER==DJGPPC
27 #if MSDOS_COMPILER==DJGPPC
32 #if MSDOS_COMPILER==WIN32C
41 #if HAVE_TERMIOS_H && HAVE_TERMIOS_FUNCS
43 #if HAVE_SYS_IOCTL_H && !defined(TIOCGWINSZ)
44 #include <sys/ioctl.h>
55 #if HAVE_SYS_IOCTL_H && (defined(TIOCGWINSZ) || defined(TCGETA) || defined(TIOCGETP) || defined(WIOCGETD))
56 #include <sys/ioctl.h>
68 #include <sys/signal.h>
72 #include <sys/stream.h>
78 #endif /* MSDOS_COMPILER */
81 * Check for broken termios package that forces you to manually
82 * set the line discipline.
85 #define MUST_SET_LINE_DISCIPLINE 1
87 #define MUST_SET_LINE_DISCIPLINE 0
91 #define DEFAULT_TERM "ansi"
92 static char *windowid;
94 #define DEFAULT_TERM "unknown"
97 #if MSDOS_COMPILER==MSOFTC
98 static int videopages;
99 static long msec_loops;
100 static int flash_created = 0;
101 #define SETCOLORS(fg,bg) { _settextcolor(fg); _setbkcolor(bg); }
104 #if MSDOS_COMPILER==BORLANDC
105 static unsigned short *whitescreen;
106 static int flash_created = 0;
108 #if MSDOS_COMPILER==BORLANDC || MSDOS_COMPILER==DJGPPC
109 #define _settextposition(y,x) gotoxy(x,y)
110 #define _clearscreen(m) clrscr()
111 #define _outtext(s) cputs(s)
112 #define SETCOLORS(fg,bg) { textcolor(fg); textbackground(bg); }
113 extern int sc_height;
116 #if MSDOS_COMPILER==WIN32C
123 static int keyCount = 0;
124 static WORD curr_attr;
125 static int pending_scancode = 0;
126 static WORD *whitescreen;
128 static HANDLE con_out_save = INVALID_HANDLE_VALUE; /* previous console */
129 static HANDLE con_out_ours = INVALID_HANDLE_VALUE; /* our own */
130 HANDLE con_out = INVALID_HANDLE_VALUE; /* current console */
133 static void win32_init_term();
134 static void win32_deinit_term();
136 #define FG_COLORS (FOREGROUND_RED | FOREGROUND_GREEN | FOREGROUND_BLUE | FOREGROUND_INTENSITY)
137 #define BG_COLORS (BACKGROUND_RED | BACKGROUND_GREEN | BACKGROUND_BLUE | BACKGROUND_INTENSITY)
138 #define MAKEATTR(fg,bg) ((WORD)((fg)|((bg)<<4)))
139 #define SETCOLORS(fg,bg) { curr_attr = MAKEATTR(fg,bg); \
140 if (SetConsoleTextAttribute(con_out, curr_attr) == 0) \
141 error("SETCOLORS failed"); }
145 public int nm_fg_color; /* Color of normal text */
146 public int nm_bg_color;
147 public int bo_fg_color; /* Color of bold text */
148 public int bo_bg_color;
149 public int ul_fg_color; /* Color of underlined text */
150 public int ul_bg_color;
151 public int so_fg_color; /* Color of standout text */
152 public int so_bg_color;
153 public int bl_fg_color; /* Color of blinking text */
154 public int bl_bg_color;
155 static int sy_fg_color; /* Color of system text (before less) */
156 static int sy_bg_color;
161 * Strings passed to tputs() to do various terminal functions.
164 *sc_pad, /* Pad string */
165 *sc_home, /* Cursor home */
166 *sc_addline, /* Add line, scroll down following lines */
167 *sc_lower_left, /* Cursor to last line, first column */
168 *sc_move, /* General cursor positioning */
169 *sc_clear, /* Clear screen */
170 *sc_eol_clear, /* Clear to end of line */
171 *sc_eos_clear, /* Clear to end of screen */
172 *sc_s_in, /* Enter standout (highlighted) mode */
173 *sc_s_out, /* Exit standout mode */
174 *sc_u_in, /* Enter underline mode */
175 *sc_u_out, /* Exit underline mode */
176 *sc_b_in, /* Enter bold mode */
177 *sc_b_out, /* Exit bold mode */
178 *sc_bl_in, /* Enter blink mode */
179 *sc_bl_out, /* Exit blink mode */
180 *sc_visual_bell, /* Visual bell (flash screen) sequence */
181 *sc_backspace, /* Backspace cursor */
182 *sc_s_keypad, /* Start keypad mode */
183 *sc_e_keypad, /* End keypad mode */
184 *sc_init, /* Startup terminal initialization */
185 *sc_deinit; /* Exit terminal de-initialization */
188 static int init_done = 0;
190 public int auto_wrap; /* Terminal does \r\n when write past margin */
191 public int ignaw; /* Terminal ignores \n immediately after wrap */
192 public int erase_char, kill_char; /* The user's erase and line-kill chars */
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;
207 static char *cheaper();
208 static void tmodes();
212 * These two variables are sometimes defined in,
213 * and needed by, the termcap library.
215 #if MUST_DEFINE_OSPEED
216 extern short ospeed; /* Terminal output baud rate */
217 extern char PC; /* Pad character */
224 extern int quiet; /* If VERY_QUIET, use visual bell for bell */
225 extern int no_back_scroll;
228 extern int no_keypad;
231 extern int screen_trashed;
234 extern int hilite_search;
237 extern char *tgetstr();
238 extern char *tgoto();
242 * Change terminal to "raw mode", or restore to "normal" mode.
244 * 1. An outstanding read will complete on receipt of a single keystroke.
245 * 2. Input is not echoed.
246 * 3. On output, \n is mapped to \r\n.
247 * 4. \t is NOT expanded into spaces.
248 * 5. Signal-causing characters such as ctrl-C (interrupt),
249 * etc. are NOT disabled.
250 * It doesn't matter whether an input \n is mapped to \r, or vice versa.
256 static int curr_on = 0;
260 #if HAVE_TERMIOS_H && HAVE_TERMIOS_FUNCS
263 static struct termios save_term;
264 static int saved_term = 0;
269 * Get terminal modes.
274 * Save modes and set certain variables dependent on modes.
282 switch (cfgetospeed(&s))
285 case B0: ospeed = 0; break;
288 case B50: ospeed = 1; break;
291 case B75: ospeed = 2; break;
294 case B110: ospeed = 3; break;
297 case B134: ospeed = 4; break;
300 case B150: ospeed = 5; break;
303 case B200: ospeed = 6; break;
306 case B300: ospeed = 7; break;
309 case B600: ospeed = 8; break;
312 case B1200: ospeed = 9; break;
315 case B1800: ospeed = 10; break;
318 case B2400: ospeed = 11; break;
321 case B4800: ospeed = 12; break;
324 case B9600: ospeed = 13; break;
327 case EXTA: ospeed = 14; break;
330 case EXTB: ospeed = 15; break;
333 case B57600: ospeed = 16; break;
336 case B115200: ospeed = 17; break;
341 erase_char = s.c_cc[VERASE];
342 kill_char = s.c_cc[VKILL];
344 werase_char = s.c_cc[VWERASE];
346 werase_char = CONTROL('W');
350 * Set the modes to the way we want them.
412 #if MUST_SET_LINE_DISCIPLINE
414 * System's termios is broken; need to explicitly
415 * request TERMIODISC line discipline.
417 s.c_line = TERMIODISC;
422 * Restore saved modes.
429 tcsetattr(tty, TCSADRAIN, &s);
430 #if MUST_SET_LINE_DISCIPLINE
434 * Broken termios *ignores* any line discipline
435 * except TERMIODISC. A different old line discipline
436 * is therefore not restored, yet. Restore the old
437 * line discipline by hand.
439 ioctl(tty, TIOCSETD, &save_term.c_line);
447 static struct termio save_term;
448 static int saved_term = 0;
453 * Get terminal modes.
455 ioctl(tty, TCGETA, &s);
458 * Save modes and set certain variables dependent on modes.
466 ospeed = s.c_cflag & CBAUD;
468 erase_char = s.c_cc[VERASE];
469 kill_char = s.c_cc[VKILL];
471 werase_char = s.c_cc[VWERASE];
473 werase_char = CONTROL('W');
477 * Set the modes to the way we want them.
479 s.c_lflag &= ~(ICANON|ECHO|ECHOE|ECHOK|ECHONL);
480 s.c_oflag |= (OPOST|ONLCR|TAB3);
481 s.c_oflag &= ~(OCRNL|ONOCR|ONLRET);
487 * Restore saved modes.
491 ioctl(tty, TCSETAW, &s);
497 static struct sgttyb save_term;
498 static int saved_term = 0;
503 * Get terminal modes.
505 ioctl(tty, TIOCGETP, &s);
508 * Save modes and set certain variables dependent on modes.
516 ospeed = s.sg_ospeed;
518 erase_char = s.sg_erase;
519 kill_char = s.sg_kill;
520 werase_char = CONTROL('W');
523 * Set the modes to the way we want them.
525 s.sg_flags |= CBREAK;
526 s.sg_flags &= ~(ECHO|XTABS);
530 * Restore saved modes.
534 ioctl(tty, TIOCSETN, &s);
540 static struct sgbuf save_term;
541 static int saved_term = 0;
546 * Get terminal modes.
551 * Save modes and set certain variables dependent on modes.
558 erase_char = s.sg_bspch;
559 kill_char = s.sg_dlnch;
560 werase_char = CONTROL('W');
563 * Set the modes to the way we want them.
572 * Restore saved modes.
579 /* MS-DOS, Windows, or OS2 */
582 LSIGNAL(SIGINT, SIG_IGN);
585 #if MSDOS_COMPILER==DJGPPC
586 kill_char = CONTROL('U');
588 * So that when we shell out or run another program, its
589 * stdin is in cooked mode. We do not switch stdin to binary
590 * mode if fd0 is zero, since that means we were called before
591 * tty was reopened in open_getchr, in which case we would be
592 * changing the original stdin device outside less.
595 setmode(0, on ? O_BINARY : O_TEXT);
599 werase_char = CONTROL('W');
609 * Some glue to prevent calling termcap functions if tgetent() failed.
619 strcpy(name, "LESS_TERMCAP_");
620 strcat(name, capname);
621 return (lgetenv(name));
630 if ((s = ltget_env(capname)) != NULL)
631 return (*s != '\0' && *s != '0');
634 return (tgetflag(capname));
643 if ((s = ltget_env(capname)) != NULL)
647 return (tgetnum(capname));
651 ltgetstr(capname, pp)
657 if ((s = ltget_env(capname)) != NULL)
661 return (tgetstr(capname, pp));
663 #endif /* MSDOS_COMPILER */
666 * Get size of the output screen.
678 #define DEF_SC_WIDTH 80
680 #define DEF_SC_HEIGHT 25
682 #define DEF_SC_HEIGHT 24
686 sys_width = sys_height = 0;
688 #if MSDOS_COMPILER==MSOFTC
690 struct videoconfig w;
692 sys_height = w.numtextrows;
693 sys_width = w.numtextcols;
696 #if MSDOS_COMPILER==BORLANDC || MSDOS_COMPILER==DJGPPC
700 sys_height = w.screenheight;
701 sys_width = w.screenwidth;
704 #if MSDOS_COMPILER==WIN32C
706 CONSOLE_SCREEN_BUFFER_INFO scr;
707 GetConsoleScreenBufferInfo(con_out, &scr);
708 sys_height = scr.srWindow.Bottom - scr.srWindow.Top + 1;
709 sys_width = scr.srWindow.Right - scr.srWindow.Left + 1;
719 * When using terminal emulators for XFree86/OS2, the
720 * _scrsize function does not work well.
721 * Call the scrsize.exe program to get the window size.
723 windowid = getenv("WINDOWID");
724 if (windowid != NULL)
726 FILE *fd = popen("scrsize", "rt");
730 fscanf(fd, "%i %i", &w, &h);
744 if (ioctl(2, TIOCGWINSZ, &w) == 0)
747 sys_height = w.ws_row;
749 sys_width = w.ws_col;
756 if (ioctl(2, WIOCGETD, &w) == 0)
759 sys_height = w.uw_height / w.uw_vs;
761 sys_width = w.uw_width / w.uw_hs;
772 sc_height = sys_height;
773 else if ((s = lgetenv("LINES")) != NULL)
776 else if ((n = ltgetnum("li")) > 0)
780 sc_height = DEF_SC_HEIGHT;
783 sc_width = sys_width;
784 else if ((s = lgetenv("COLUMNS")) != NULL)
787 else if ((n = ltgetnum("co")) > 0)
791 sc_width = DEF_SC_WIDTH;
794 #if MSDOS_COMPILER==MSOFTC
796 * Figure out how many empty loops it takes to delay a millisecond.
804 * Get synchronized at the start of a tick.
807 while (clock() == start)
810 * Now count loops till the next tick.
814 while (clock() == start)
817 * Convert from (loops per clock) to (loops per millisecond).
819 msec_loops *= CLOCKS_PER_SEC;
824 * Delay for a specified number of milliseconds.
829 static long delay_dummy = 0;
841 for (i = 0; i < msec_loops; i++)
844 * Make it look like we're doing something here,
845 * so the optimizer doesn't remove the whole loop.
854 * Return the characters actually input by a "special" key.
860 static char tbuf[40];
862 #if MSDOS_COMPILER || OS2
863 static char k_right[] = { '\340', PCK_RIGHT, 0 };
864 static char k_left[] = { '\340', PCK_LEFT, 0 };
865 static char k_ctl_right[] = { '\340', PCK_CTL_RIGHT, 0 };
866 static char k_ctl_left[] = { '\340', PCK_CTL_LEFT, 0 };
867 static char k_insert[] = { '\340', PCK_INSERT, 0 };
868 static char k_delete[] = { '\340', PCK_DELETE, 0 };
869 static char k_ctl_delete[] = { '\340', PCK_CTL_DELETE, 0 };
870 static char k_ctl_backspace[] = { '\177', 0 };
871 static char k_home[] = { '\340', PCK_HOME, 0 };
872 static char k_end[] = { '\340', PCK_END, 0 };
873 static char k_up[] = { '\340', PCK_UP, 0 };
874 static char k_down[] = { '\340', PCK_DOWN, 0 };
875 static char k_backtab[] = { '\340', PCK_SHIFT_TAB, 0 };
876 static char k_pagedown[] = { '\340', PCK_PAGEDOWN, 0 };
877 static char k_pageup[] = { '\340', PCK_PAGEUP, 0 };
878 static char k_f1[] = { '\340', PCK_F1, 0 };
888 * If windowid is not NULL, assume less is executed in
889 * the XFree86 environment.
892 s = windowid ? ltgetstr("kr", &sp) : k_right;
895 s = windowid ? ltgetstr("kl", &sp) : k_left;
898 s = windowid ? ltgetstr("ku", &sp) : k_up;
901 s = windowid ? ltgetstr("kd", &sp) : k_down;
904 s = windowid ? ltgetstr("kP", &sp) : k_pageup;
907 s = windowid ? ltgetstr("kN", &sp) : k_pagedown;
910 s = windowid ? ltgetstr("kh", &sp) : k_home;
913 s = windowid ? ltgetstr("@7", &sp) : k_end;
918 s = ltgetstr("kD", &sp);
958 #if MSDOS_COMPILER || OS2
962 case SK_CTL_LEFT_ARROW:
965 case SK_CTL_RIGHT_ARROW:
968 case SK_CTL_BACKSPACE:
982 s = ltgetstr("kr", &sp);
985 s = ltgetstr("kl", &sp);
988 s = ltgetstr("ku", &sp);
991 s = ltgetstr("kd", &sp);
994 s = ltgetstr("kP", &sp);
997 s = ltgetstr("kN", &sp);
1000 s = ltgetstr("kh", &sp);
1003 s = ltgetstr("@7", &sp);
1006 s = ltgetstr("kD", &sp);
1016 tbuf[0] = CONTROL('K');
1027 * Get terminal capabilities via termcap.
1038 * Set up default colors.
1039 * The xx_s_width and xx_e_width vars are already initialized to 0.
1041 #if MSDOS_COMPILER==MSOFTC
1042 sy_bg_color = _getbkcolor();
1043 sy_fg_color = _gettextcolor();
1046 #if MSDOS_COMPILER==BORLANDC || MSDOS_COMPILER==DJGPPC
1050 sy_bg_color = (w.attribute >> 4) & 0x0F;
1051 sy_fg_color = (w.attribute >> 0) & 0x0F;
1054 #if MSDOS_COMPILER==WIN32C
1057 CONSOLE_SCREEN_BUFFER_INFO scr;
1059 con_out_save = con_out = GetStdHandle(STD_OUTPUT_HANDLE);
1061 * Always open stdin in binary. Note this *must* be done
1062 * before any file operations have been done on fd0.
1065 GetConsoleScreenBufferInfo(con_out, &scr);
1066 ReadConsoleOutputAttribute(con_out, &curr_attr,
1067 1, scr.dwCursorPosition, &nread);
1068 sy_bg_color = (curr_attr & BG_COLORS) >> 4; /* normalize */
1069 sy_fg_color = curr_attr & FG_COLORS;
1074 nm_fg_color = sy_fg_color;
1075 nm_bg_color = sy_bg_color;
1086 * Get size of the screen.
1092 #else /* !MSDOS_COMPILER */
1095 register char *t1, *t2;
1097 char termbuf[TERMBUF_SIZE];
1099 static char sbuf[TERMSBUF_SIZE];
1103 * Make sure the termcap database is available.
1105 sp = lgetenv("TERMCAP");
1106 if (sp == NULL || *sp == '\0')
1109 if ((sp = homefile("termcap.dat")) != NULL)
1111 termcap = (char *) ecalloc(strlen(sp)+9, sizeof(char));
1112 sprintf(termcap, "TERMCAP=%s", sp);
1119 * Find out what kind of terminal this is.
1121 if ((term = lgetenv("TERM")) == NULL)
1122 term = DEFAULT_TERM;
1124 if (tgetent(termbuf, term) <= 0)
1126 if (ltgetflag("hc"))
1130 * Get size of the screen.
1135 auto_wrap = ltgetflag("am");
1136 ignaw = ltgetflag("xn");
1137 above_mem = ltgetflag("da");
1138 below_mem = ltgetflag("db");
1139 clear_bg = ltgetflag("ut");
1142 * Assumes termcap variable "sg" is the printing width of:
1143 * the standout sequence, the end standout sequence,
1144 * the underline sequence, the end underline sequence,
1145 * the boldface sequence, and the end boldface sequence.
1147 if ((so_s_width = ltgetnum("sg")) < 0)
1149 so_e_width = so_s_width;
1151 bo_s_width = bo_e_width = so_s_width;
1152 ul_s_width = ul_e_width = so_s_width;
1153 bl_s_width = bl_e_width = so_s_width;
1156 if (so_s_width > 0 || so_e_width > 0)
1158 * Disable highlighting by default on magic cookie terminals.
1159 * Turning on highlighting might change the displayed width
1160 * of a line, causing the display to get messed up.
1161 * The user can turn it back on with -g,
1162 * but she won't like the results.
1168 * Get various string-valued capabilities.
1173 sc_pad = ltgetstr("pc", &sp);
1178 sc_s_keypad = ltgetstr("ks", &sp);
1179 if (sc_s_keypad == NULL)
1181 sc_e_keypad = ltgetstr("ke", &sp);
1182 if (sc_e_keypad == NULL)
1185 sc_init = ltgetstr("ti", &sp);
1186 if (sc_init == NULL)
1189 sc_deinit= ltgetstr("te", &sp);
1190 if (sc_deinit == NULL)
1193 sc_eol_clear = ltgetstr("ce", &sp);
1194 if (sc_eol_clear == NULL || *sc_eol_clear == '\0')
1200 sc_eos_clear = ltgetstr("cd", &sp);
1201 if (below_mem && (sc_eos_clear == NULL || *sc_eos_clear == '\0'))
1207 sc_clear = ltgetstr("cl", &sp);
1208 if (sc_clear == NULL || *sc_clear == '\0')
1214 sc_move = ltgetstr("cm", &sp);
1215 if (sc_move == NULL || *sc_move == '\0')
1218 * This is not an error here, because we don't
1219 * always need sc_move.
1220 * We need it only if we don't have home or lower-left.
1227 tmodes("so", "se", &sc_s_in, &sc_s_out, "", "", &sp);
1228 tmodes("us", "ue", &sc_u_in, &sc_u_out, sc_s_in, sc_s_out, &sp);
1229 tmodes("md", "me", &sc_b_in, &sc_b_out, sc_s_in, sc_s_out, &sp);
1230 tmodes("mb", "me", &sc_bl_in, &sc_bl_out, sc_s_in, sc_s_out, &sp);
1232 sc_visual_bell = ltgetstr("vb", &sp);
1233 if (sc_visual_bell == NULL)
1234 sc_visual_bell = "";
1236 if (ltgetflag("bs"))
1237 sc_backspace = "\b";
1240 sc_backspace = ltgetstr("bc", &sp);
1241 if (sc_backspace == NULL || *sc_backspace == '\0')
1242 sc_backspace = "\b";
1246 * Choose between using "ho" and "cm" ("home" and "cursor move")
1247 * to move the cursor to the upper left corner of the screen.
1249 t1 = ltgetstr("ho", &sp);
1252 if (*sc_move == '\0')
1256 strcpy(sp, tgoto(sc_move, 0, 0));
1258 sp += strlen(sp) + 1;
1260 sc_home = cheaper(t1, t2, "|\b^");
1263 * Choose between using "ll" and "cm" ("lower left" and "cursor move")
1264 * to move the cursor to the lower left corner of the screen.
1266 t1 = ltgetstr("ll", &sp);
1269 if (*sc_move == '\0')
1273 strcpy(sp, tgoto(sc_move, 0, sc_height-1));
1275 sp += strlen(sp) + 1;
1277 sc_lower_left = cheaper(t1, t2, "\r");
1280 * Choose between using "al" or "sr" ("add line" or "scroll reverse")
1281 * to add a line at the top of the screen.
1283 t1 = ltgetstr("al", &sp);
1286 t2 = ltgetstr("sr", &sp);
1290 if (*t1 == '\0' && *t2 == '\0')
1297 sc_addline = cheaper(t1, t2, "");
1298 if (*sc_addline == '\0')
1301 * Force repaint on any backward movement.
1305 #endif /* MSDOS_COMPILER */
1310 * Return the cost of displaying a termcap string.
1311 * We use the trick of calling tputs, but as a char printing function
1312 * we give it inc_costcount, which just increments "costcount".
1313 * This tells us how many chars would be printed by using this string.
1314 * {{ Couldn't we just use strlen? }}
1316 static int costcount;
1332 tputs(t, sc_height, inc_costcount);
1337 * Return the "best" of the two given termcap strings.
1338 * The best, if both exist, is the one with the lower
1339 * cost (see cost() function).
1342 cheaper(t1, t2, def)
1346 if (*t1 == '\0' && *t2 == '\0')
1355 if (cost(t1) < cost(t2))
1361 tmodes(incap, outcap, instr, outstr, def_instr, def_outstr, spp)
1370 *instr = ltgetstr(incap, spp);
1375 *outstr = def_outstr;
1379 *outstr = ltgetstr(outcap, spp);
1380 if (*outstr == NULL)
1381 /* No specific out capability; use "me". */
1382 *outstr = ltgetstr("me", spp);
1383 if (*outstr == NULL)
1384 /* Don't even have "me"; use a null string. */
1388 #endif /* MSDOS_COMPILER */
1392 * Below are the functions which perform all the
1393 * terminal-specific screen manipulation.
1399 #if MSDOS_COMPILER==WIN32C
1401 _settextposition(int row, int col)
1404 CONSOLE_SCREEN_BUFFER_INFO csbi;
1406 GetConsoleScreenBufferInfo(con_out, &csbi);
1407 cpos.X = csbi.srWindow.Left + (col - 1);
1408 cpos.Y = csbi.srWindow.Top + (row - 1);
1409 SetConsoleCursorPosition(con_out, cpos);
1414 * Initialize the screen to the correct color at startup.
1419 SETCOLORS(nm_fg_color, nm_bg_color);
1422 * This clears the screen at startup. This is different from
1423 * the behavior of other versions of less. Disable it for now.
1430 * Create a complete, blank screen using "normal" colors.
1432 SETCOLORS(nm_fg_color, nm_bg_color);
1433 blanks = (char *) ecalloc(width+1, sizeof(char));
1434 for (col = 0; col < sc_width; col++)
1436 blanks[sc_width] = '\0';
1437 for (row = 0; row < sc_height; row++)
1444 #if MSDOS_COMPILER==WIN32C
1447 * Termcap-like init with a private win32 console.
1452 CONSOLE_SCREEN_BUFFER_INFO scr;
1455 if (con_out_save == INVALID_HANDLE_VALUE)
1458 GetConsoleScreenBufferInfo(con_out_save, &scr);
1460 if (con_out_ours == INVALID_HANDLE_VALUE)
1463 * Create our own screen buffer, so that we
1464 * may restore the original when done.
1466 con_out_ours = CreateConsoleScreenBuffer(
1467 GENERIC_WRITE | GENERIC_READ,
1468 FILE_SHARE_WRITE | FILE_SHARE_READ,
1469 (LPSECURITY_ATTRIBUTES) NULL,
1470 CONSOLE_TEXTMODE_BUFFER,
1474 size.X = scr.srWindow.Right - scr.srWindow.Left + 1;
1475 size.Y = scr.srWindow.Bottom - scr.srWindow.Top + 1;
1476 SetConsoleScreenBufferSize(con_out_ours, size);
1477 SetConsoleActiveScreenBuffer(con_out_ours);
1478 con_out = con_out_ours;
1482 * Restore the startup console.
1487 if (con_out_save == INVALID_HANDLE_VALUE)
1490 (void) CloseHandle(con_out_ours);
1491 SetConsoleActiveScreenBuffer(con_out_save);
1492 con_out = con_out_save;
1498 * Initialize terminal
1505 tputs(sc_init, sc_height, putchr);
1507 tputs(sc_s_keypad, sc_height, putchr);
1509 #if MSDOS_COMPILER==WIN32C
1520 * Deinitialize terminal
1529 tputs(sc_e_keypad, sc_height, putchr);
1531 tputs(sc_deinit, sc_height, putchr);
1533 /* Restore system colors. */
1534 SETCOLORS(sy_fg_color, sy_bg_color);
1535 #if MSDOS_COMPILER==WIN32C
1537 win32_deinit_term();
1539 /* Need clreol to make SETCOLORS take effect. */
1547 * Home cursor (move to upper left corner of screen).
1553 tputs(sc_home, 1, putchr);
1556 _settextposition(1,1);
1561 * Add a blank line (called with cursor at home).
1562 * Should scroll the display down.
1568 tputs(sc_addline, sc_height, putchr);
1571 #if MSDOS_COMPILER==MSOFTC
1572 _scrolltextwindow(_GSCROLLDOWN);
1573 _settextposition(1,1);
1575 #if MSDOS_COMPILER==BORLANDC || MSDOS_COMPILER==DJGPPC
1576 movetext(1,1, sc_width,sc_height-1, 1,2);
1580 #if MSDOS_COMPILER==WIN32C
1583 SMALL_RECT rcSrc, rcClip;
1585 CONSOLE_SCREEN_BUFFER_INFO csbi;
1587 GetConsoleScreenBufferInfo(con_out,&csbi);
1589 /* The clip rectangle is the entire visible screen. */
1590 rcClip.Left = csbi.srWindow.Left;
1591 rcClip.Top = csbi.srWindow.Top;
1592 rcClip.Right = csbi.srWindow.Right;
1593 rcClip.Bottom = csbi.srWindow.Bottom;
1595 /* The source rectangle is the visible screen minus the last line. */
1599 /* Move the top left corner of the source window down one row. */
1600 new_org.X = rcSrc.Left;
1601 new_org.Y = rcSrc.Top + 1;
1603 /* Fill the right character and attributes. */
1604 fillchar.Char.AsciiChar = ' ';
1605 curr_attr = MAKEATTR(nm_fg_color, nm_bg_color);
1606 fillchar.Attributes = curr_attr;
1607 ScrollConsoleScreenBuffer(con_out, &rcSrc, &rcClip, new_org, &fillchar);
1608 _settextposition(1,1);
1618 * Remove the n topmost lines and scroll everything below it in the
1619 * window upward. This is needed to stop leaking the topmost line
1620 * into the scrollback buffer when we go down-one-line (in WIN32).
1626 #if MSDOS_COMPILER==WIN32C
1627 SMALL_RECT rcSrc, rcClip;
1630 CONSOLE_SCREEN_BUFFER_INFO csbi; /* to get buffer info */
1632 if (n >= sc_height - 1)
1641 GetConsoleScreenBufferInfo(con_out, &csbi);
1643 /* Get the extent of all-visible-rows-but-the-last. */
1644 rcSrc.Left = csbi.srWindow.Left;
1645 rcSrc.Top = csbi.srWindow.Top + n;
1646 rcSrc.Right = csbi.srWindow.Right;
1647 rcSrc.Bottom = csbi.srWindow.Bottom;
1649 /* Get the clip rectangle. */
1650 rcClip.Left = rcSrc.Left;
1651 rcClip.Top = csbi.srWindow.Top;
1652 rcClip.Right = rcSrc.Right;
1653 rcClip.Bottom = rcSrc.Bottom ;
1655 /* Move the source window up n rows. */
1656 new_org.X = rcSrc.Left;
1657 new_org.Y = rcSrc.Top - n;
1659 /* Fill the right character and attributes. */
1660 fillchar.Char.AsciiChar = ' ';
1661 curr_attr = MAKEATTR(nm_fg_color, nm_bg_color);
1662 fillchar.Attributes = curr_attr;
1664 ScrollConsoleScreenBuffer(con_out, &rcSrc, &rcClip, new_org, &fillchar);
1666 /* Position cursor on first blank line. */
1667 goto_line(sc_height - n - 1);
1672 #if MSDOS_COMPILER==WIN32C
1680 * This will clear only the currently visible rows of the NT
1681 * console buffer, which means none of the precious scrollback
1682 * rows are touched making for faster scrolling. Note that, if
1683 * the window has fewer columns than the console buffer (i.e.
1684 * there is a horizontal scrollbar as well), the entire width
1685 * of the visible rows will be cleared.
1690 CONSOLE_SCREEN_BUFFER_INFO csbi;
1692 /* get the number of cells in the current buffer */
1693 GetConsoleScreenBufferInfo(con_out, &csbi);
1694 winsz = csbi.dwSize.X * (csbi.srWindow.Bottom - csbi.srWindow.Top + 1);
1696 topleft.Y = csbi.srWindow.Top;
1698 curr_attr = MAKEATTR(nm_fg_color, nm_bg_color);
1699 FillConsoleOutputCharacter(con_out, ' ', winsz, topleft, &nchars);
1700 FillConsoleOutputAttribute(con_out, curr_attr, winsz, topleft, &nchars);
1704 * Remove the n topmost lines and scroll everything below it in the
1711 SMALL_RECT rcSrc, rcClip;
1717 CONSOLE_SCREEN_BUFFER_INFO csbi;
1722 if (n >= sc_height - 1)
1725 _settextposition(1,1);
1729 /* Get the extent of what will remain visible after scrolling. */
1730 GetConsoleScreenBufferInfo(con_out, &csbi);
1731 rcSrc.Left = csbi.srWindow.Left;
1732 rcSrc.Top = csbi.srWindow.Top + n;
1733 rcSrc.Right = csbi.srWindow.Right;
1734 rcSrc.Bottom = csbi.srWindow.Bottom;
1736 /* Get the clip rectangle. */
1737 rcClip.Left = rcSrc.Left;
1738 rcClip.Top = csbi.srWindow.Top;
1739 rcClip.Right = rcSrc.Right;
1740 rcClip.Bottom = rcSrc.Bottom ;
1742 /* Move the source text to the top of the screen. */
1743 new_org.X = rcSrc.Left;
1746 /* Fill the right character and attributes. */
1747 fillchar.Char.AsciiChar = ' ';
1748 fillchar.Attributes = MAKEATTR(nm_fg_color, nm_bg_color);
1750 /* Scroll the window. */
1751 SetConsoleTextAttribute(con_out, fillchar.Attributes);
1752 ScrollConsoleScreenBuffer(con_out, &rcSrc, &rcClip, new_org, &fillchar);
1754 /* Clear remaining lines at bottom. */
1755 topleft.X = csbi.dwCursorPosition.X;
1756 topleft.Y = rcSrc.Bottom - n;
1757 size = (n * csbi.dwSize.X) + (rcSrc.Right - topleft.X);
1758 FillConsoleOutputCharacter(con_out, ' ', size, topleft,
1760 FillConsoleOutputAttribute(con_out, fillchar.Attributes, size, topleft,
1762 SetConsoleTextAttribute(con_out, curr_attr);
1764 /* Move cursor n lines up from where it was. */
1765 csbi.dwCursorPosition.Y -= n;
1766 SetConsoleCursorPosition(con_out, csbi.dwCursorPosition);
1771 * Move cursor to lower left corner of screen.
1777 tputs(sc_lower_left, 1, putchr);
1780 _settextposition(sc_height, 1);
1785 * Check if the console size has changed and reset internals
1786 * (in lieu of SIGWINCH for WIN32).
1791 #if MSDOS_COMPILER==WIN32C
1792 CONSOLE_SCREEN_BUFFER_INFO scr;
1795 if (con_out == INVALID_HANDLE_VALUE)
1799 GetConsoleScreenBufferInfo(con_out, &scr);
1800 size.Y = scr.srWindow.Bottom - scr.srWindow.Top + 1;
1801 size.X = scr.srWindow.Right - scr.srWindow.Left + 1;
1802 if (size.Y != sc_height || size.X != sc_width)
1806 if (!no_init && con_out_ours == con_out)
1807 SetConsoleScreenBufferSize(con_out, size);
1809 wscroll = (sc_height + 1) / 2;
1816 * Goto a specific line on the screen.
1823 tputs(tgoto(sc_move, 0, slinenum), 1, putchr);
1826 _settextposition(slinenum+1, 1);
1830 #if MSDOS_COMPILER==MSOFTC || MSDOS_COMPILER==BORLANDC
1832 * Create an alternate screen which is all white.
1833 * This screen is used to create a "flash" effect, by displaying it
1834 * briefly and then switching back to the normal screen.
1835 * {{ Yuck! There must be a better way to get a visual bell. }}
1840 #if MSDOS_COMPILER==MSOFTC
1841 struct videoconfig w;
1845 _getvideoconfig(&w);
1846 videopages = w.numvideopages;
1855 blanks = (char *) ecalloc(w.numtextcols, sizeof(char));
1856 for (col = 0; col < w.numtextcols; col++)
1858 for (row = w.numtextrows; row > 0; row--)
1859 _outmem(blanks, w.numtextcols);
1866 #if MSDOS_COMPILER==BORLANDC
1869 whitescreen = (unsigned short *)
1870 malloc(sc_width * sc_height * sizeof(short));
1871 if (whitescreen == NULL)
1873 for (n = 0; n < sc_width * sc_height; n++)
1874 whitescreen[n] = 0x7020;
1876 #if MSDOS_COMPILER==WIN32C
1879 whitescreen = (WORD *)
1880 malloc(sc_height * sc_width * sizeof(WORD));
1881 if (whitescreen == NULL)
1883 /* Invert the standard colors. */
1884 for (n = 0; n < sc_width * sc_height; n++)
1885 whitescreen[n] = (WORD)((nm_fg_color << 4) | nm_bg_color);
1891 #endif /* MSDOS_COMPILER */
1894 * Output the "visual bell", if there is one.
1900 if (*sc_visual_bell == '\0')
1902 tputs(sc_visual_bell, sc_height, putchr);
1904 #if MSDOS_COMPILER==DJGPPC
1907 #if MSDOS_COMPILER==MSOFTC
1909 * Create a flash screen on the second video page.
1910 * Switch to that page, then switch back.
1920 #if MSDOS_COMPILER==BORLANDC
1921 unsigned short *currscreen;
1924 * Get a copy of the current screen.
1925 * Display the flash screen.
1926 * Then restore the old screen.
1930 if (whitescreen == NULL)
1932 currscreen = (unsigned short *)
1933 malloc(sc_width * sc_height * sizeof(short));
1934 if (currscreen == NULL) return;
1935 gettext(1, 1, sc_width, sc_height, currscreen);
1936 puttext(1, 1, sc_width, sc_height, whitescreen);
1938 puttext(1, 1, sc_width, sc_height, currscreen);
1941 #if MSDOS_COMPILER==WIN32C
1942 /* paint screen with an inverse color */
1945 /* leave it displayed for 100 msec. */
1948 /* restore with a redraw */
1964 putchr(CONTROL('G'));
1966 #if MSDOS_COMPILER==WIN32C
1975 * Ring the terminal bell.
1980 if (quiet == VERY_QUIET)
1993 tputs(sc_clear, sc_height, putchr);
1996 #if MSDOS_COMPILER==WIN32C
1999 _clearscreen(_GCLEARSCREEN);
2005 * Clear from the cursor to the end of the cursor's line.
2006 * {{ This must not move the cursor. }}
2012 tputs(sc_eol_clear, 1, putchr);
2014 #if MSDOS_COMPILER==MSOFTC
2017 struct rccoord tpos;
2021 * Save current state.
2023 tpos = _gettextposition();
2024 _gettextwindow(&top, &left, &bot, &right);
2026 * Set a temporary window to the current line,
2027 * from the cursor's position to the right edge of the screen.
2028 * Then clear that window.
2030 _settextwindow(tpos.row, tpos.col, tpos.row, sc_width);
2031 _clearscreen(_GWINDOW);
2035 _settextwindow(top, left, bot, right);
2036 _settextposition(tpos.row, tpos.col);
2038 #if MSDOS_COMPILER==BORLANDC || MSDOS_COMPILER==DJGPPC
2042 #if MSDOS_COMPILER==WIN32C
2045 CONSOLE_SCREEN_BUFFER_INFO scr;
2048 memset(&scr, 0, sizeof(scr));
2049 GetConsoleScreenBufferInfo(con_out, &scr);
2050 cpos.X = scr.dwCursorPosition.X;
2051 cpos.Y = scr.dwCursorPosition.Y;
2052 curr_attr = MAKEATTR(nm_fg_color, nm_bg_color);
2053 FillConsoleOutputAttribute(con_out, curr_attr,
2054 scr.dwSize.X - cpos.X, cpos, &nchars);
2055 FillConsoleOutputCharacter(con_out, ' ',
2056 scr.dwSize.X - cpos.X, cpos, &nchars);
2064 * Clear the current line.
2065 * Clear the screen if there's off-screen memory below the display.
2074 tputs(sc_eos_clear, 1, putchr);
2076 tputs(sc_eol_clear, 1, putchr);
2081 * Clear the bottom line of the display.
2082 * Leave the cursor at the beginning of the bottom line.
2088 * If we're in a non-normal attribute mode, temporarily exit
2089 * the mode while we do the clear. Some terminals fill the
2090 * cleared area with the current attribute.
2122 * Begin "standout" (bold, underline, or whatever).
2128 tputs(sc_s_in, 1, putchr);
2131 SETCOLORS(so_fg_color, so_bg_color);
2133 attrmode = AT_STANDOUT;
2143 tputs(sc_s_out, 1, putchr);
2146 SETCOLORS(nm_fg_color, nm_bg_color);
2148 attrmode = AT_NORMAL;
2152 * Begin "underline" (hopefully real underlining,
2153 * otherwise whatever the terminal provides).
2159 tputs(sc_u_in, 1, putchr);
2162 SETCOLORS(ul_fg_color, ul_bg_color);
2164 attrmode = AT_UNDERLINE;
2174 tputs(sc_u_out, 1, putchr);
2177 SETCOLORS(nm_fg_color, nm_bg_color);
2179 attrmode = AT_NORMAL;
2189 tputs(sc_b_in, 1, putchr);
2192 SETCOLORS(bo_fg_color, bo_bg_color);
2204 tputs(sc_b_out, 1, putchr);
2207 SETCOLORS(nm_fg_color, nm_bg_color);
2209 attrmode = AT_NORMAL;
2219 tputs(sc_bl_in, 1, putchr);
2222 SETCOLORS(bl_fg_color, bl_bg_color);
2224 attrmode = AT_BLINK;
2234 tputs(sc_bl_out, 1, putchr);
2237 SETCOLORS(nm_fg_color, nm_bg_color);
2239 attrmode = AT_NORMAL;
2242 #if 0 /* No longer used */
2244 * Erase the character to the left of the cursor
2245 * and move the cursor left.
2252 * Erase the previous character by overstriking with a space.
2254 tputs(sc_backspace, 1, putchr);
2256 tputs(sc_backspace, 1, putchr);
2258 #if MSDOS_COMPILER==MSOFTC
2259 struct rccoord tpos;
2262 tpos = _gettextposition();
2265 _settextposition(tpos.row, tpos.col-1);
2267 _settextposition(tpos.row, tpos.col-1);
2269 #if MSDOS_COMPILER==BORLANDC || MSDOS_COMPILER==DJGPPC
2272 #if MSDOS_COMPILER==WIN32C
2275 CONSOLE_SCREEN_BUFFER_INFO scr;
2278 GetConsoleScreenBufferInfo(con_out, &scr);
2279 cpos = scr.dwCursorPosition;
2283 SetConsoleCursorPosition(con_out, cpos);
2284 FillConsoleOutputCharacter(con_out, (TCHAR)' ', 1, cpos, &cChars);
2285 SetConsoleCursorPosition(con_out, cpos);
2294 * Output a plain backspace, without erasing the previous char.
2300 tputs(sc_backspace, 1, putchr);
2306 #if MSDOS_COMPILER==MSOFTC
2307 struct rccoord tpos;
2308 tpos = _gettextposition();
2312 #if MSDOS_COMPILER==BORLANDC || MSDOS_COMPILER==DJGPPC
2316 #if MSDOS_COMPILER==WIN32C
2317 CONSOLE_SCREEN_BUFFER_INFO scr;
2318 GetConsoleScreenBufferInfo(con_out, &scr);
2319 row = scr.dwCursorPosition.Y - scr.srWindow.Top + 1;
2320 col = scr.dwCursorPosition.X - scr.srWindow.Left + 1;
2327 _settextposition(row, col-1);
2328 #endif /* MSDOS_COMPILER */
2331 #if MSDOS_COMPILER==WIN32C
2333 * Determine whether an input character is waiting to be read.
2345 currentKey.ascii = 0;
2346 currentKey.scan = 0;
2349 * Wait for a real key-down event, but
2350 * ignore SHIFT and CONTROL key events.
2354 PeekConsoleInput(tty, &ip, 1, &read);
2357 ReadConsoleInput(tty, &ip, 1, &read);
2358 } while (ip.EventType != KEY_EVENT ||
2359 ip.Event.KeyEvent.bKeyDown != TRUE ||
2360 ip.Event.KeyEvent.wVirtualScanCode == 0 ||
2361 ip.Event.KeyEvent.wVirtualKeyCode == VK_SHIFT ||
2362 ip.Event.KeyEvent.wVirtualKeyCode == VK_CONTROL ||
2363 ip.Event.KeyEvent.wVirtualKeyCode == VK_MENU);
2365 currentKey.ascii = ip.Event.KeyEvent.uChar.AsciiChar;
2366 currentKey.scan = ip.Event.KeyEvent.wVirtualScanCode;
2367 keyCount = ip.Event.KeyEvent.wRepeatCount;
2369 if (ip.Event.KeyEvent.dwControlKeyState &
2370 (LEFT_ALT_PRESSED | RIGHT_ALT_PRESSED))
2372 switch (currentKey.scan)
2374 case PCK_ALT_E: /* letter 'E' */
2375 currentKey.ascii = 0;
2378 } else if (ip.Event.KeyEvent.dwControlKeyState &
2379 (LEFT_CTRL_PRESSED | RIGHT_CTRL_PRESSED))
2381 switch (currentKey.scan)
2383 case PCK_RIGHT: /* right arrow */
2384 currentKey.scan = PCK_CTL_RIGHT;
2386 case PCK_LEFT: /* left arrow */
2387 currentKey.scan = PCK_CTL_LEFT;
2389 case PCK_DELETE: /* delete */
2390 currentKey.scan = PCK_CTL_DELETE;
2398 * Read a character from the keyboard.
2406 if (pending_scancode)
2408 pending_scancode = 0;
2409 return ((char)(currentKey.scan & 0x00FF));
2412 while (win32_kbhit((HANDLE)tty) == FALSE)
2420 ascii = currentKey.ascii;
2422 * On PC's, the extended keys return a 2 byte sequence beginning
2423 * with '00', so if the ascii code is 00, the next byte will be
2424 * the lsb of the scan code.
2426 pending_scancode = (ascii == 0x00);
2427 return ((char)ascii);