2 * Copyright (C) 1984-2022 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
38 #ifndef FOREGROUND_BLUE
39 #define FOREGROUND_BLUE 0x0001
41 #ifndef FOREGROUND_GREEN
42 #define FOREGROUND_GREEN 0x0002
44 #ifndef FOREGROUND_RED
45 #define FOREGROUND_RED 0x0004
47 #ifndef FOREGROUND_INTENSITY
48 #define FOREGROUND_INTENSITY 0x0008
54 #include <sys/ioctl.h>
57 #if HAVE_TERMIOS_H && HAVE_TERMIOS_FUNCS
78 #include <sys/signal.h>
82 #include <sys/stream.h>
88 #endif /* MSDOS_COMPILER */
91 * Check for broken termios package that forces you to manually
92 * set the line discipline.
95 #define MUST_SET_LINE_DISCIPLINE 1
97 #define MUST_SET_LINE_DISCIPLINE 0
101 #define DEFAULT_TERM "ansi"
102 static char *windowid;
104 #define DEFAULT_TERM "unknown"
107 #if MSDOS_COMPILER==MSOFTC
108 static int videopages;
109 static long msec_loops;
110 static int flash_created = 0;
111 #define SET_FG_COLOR(fg) _settextcolor(fg)
112 #define SET_BG_COLOR(bg) _setbkcolor(bg)
113 #define SETCOLORS(fg,bg) { SET_FG_COLOR(fg); SET_BG_COLOR(bg); }
116 #if MSDOS_COMPILER==BORLANDC
117 static unsigned short *whitescreen;
118 static int flash_created = 0;
120 #if MSDOS_COMPILER==BORLANDC || MSDOS_COMPILER==DJGPPC
121 #define _settextposition(y,x) gotoxy(x,y)
122 #define _clearscreen(m) clrscr()
123 #define _outtext(s) cputs(s)
124 #define SET_FG_COLOR(fg) textcolor(fg)
125 #define SET_BG_COLOR(bg) textbackground(bg)
126 #define SETCOLORS(fg,bg) { SET_FG_COLOR(fg); SET_BG_COLOR(bg); }
127 extern int sc_height;
130 #if MSDOS_COMPILER==WIN32C
131 #define UTF8_MAX_LENGTH 4
139 static int keyCount = 0;
140 static WORD curr_attr;
141 static int pending_scancode = 0;
142 static char x11mousebuf[] = "[M???"; /* Mouse report, after ESC */
143 static int x11mousePos, x11mouseCount;
145 static HANDLE con_out_save = INVALID_HANDLE_VALUE; /* previous console */
146 static HANDLE con_out_ours = INVALID_HANDLE_VALUE; /* our own */
147 HANDLE con_out = INVALID_HANDLE_VALUE; /* current console */
151 static void win32_init_term();
152 static void win32_deinit_term();
154 #ifndef ENABLE_VIRTUAL_TERMINAL_PROCESSING
155 #define ENABLE_VIRTUAL_TERMINAL_PROCESSING 4
158 #define FG_COLORS (FOREGROUND_RED | FOREGROUND_GREEN | FOREGROUND_BLUE | FOREGROUND_INTENSITY)
159 #define BG_COLORS (BACKGROUND_RED | BACKGROUND_GREEN | BACKGROUND_BLUE | BACKGROUND_INTENSITY)
160 #define MAKEATTR(fg,bg) ((WORD)((fg)|((bg)<<4)))
161 #define APPLY_COLORS() { if (SetConsoleTextAttribute(con_out, curr_attr) == 0) \
162 error("SETCOLORS failed", NULL_PARG); }
163 #define SET_FG_COLOR(fg) { curr_attr |= (fg); APPLY_COLORS(); }
164 #define SET_BG_COLOR(bg) { curr_attr |= ((bg)<<4); APPLY_COLORS(); }
165 #define SETCOLORS(fg,bg) { curr_attr = MAKEATTR(fg,bg); APPLY_COLORS(); }
169 public int nm_fg_color; /* Color of normal text */
170 public int nm_bg_color;
171 public int bo_fg_color; /* Color of bold text */
172 public int bo_bg_color;
173 public int ul_fg_color; /* Color of underlined text */
174 public int ul_bg_color;
175 public int so_fg_color; /* Color of standout text */
176 public int so_bg_color;
177 public int bl_fg_color; /* Color of blinking text */
178 public int bl_bg_color;
179 static int sy_fg_color; /* Color of system text (before less) */
180 static int sy_bg_color;
181 public int sgr_mode; /* Honor ANSI sequences rather than using above */
182 #if MSDOS_COMPILER==WIN32C
183 static DWORD init_output_mode; /* The initial console output mode */
184 public int vt_enabled = -1; /* Is virtual terminal processing available? */
189 * Strings passed to tputs() to do various terminal functions.
192 *sc_pad, /* Pad string */
193 *sc_home, /* Cursor home */
194 *sc_addline, /* Add line, scroll down following lines */
195 *sc_lower_left, /* Cursor to last line, first column */
196 *sc_return, /* Cursor to beginning of current line */
197 *sc_move, /* General cursor positioning */
198 *sc_clear, /* Clear screen */
199 *sc_eol_clear, /* Clear to end of line */
200 *sc_eos_clear, /* Clear to end of screen */
201 *sc_s_in, /* Enter standout (highlighted) mode */
202 *sc_s_out, /* Exit standout mode */
203 *sc_u_in, /* Enter underline mode */
204 *sc_u_out, /* Exit underline mode */
205 *sc_b_in, /* Enter bold mode */
206 *sc_b_out, /* Exit bold mode */
207 *sc_bl_in, /* Enter blink mode */
208 *sc_bl_out, /* Exit blink mode */
209 *sc_visual_bell, /* Visual bell (flash screen) sequence */
210 *sc_backspace, /* Backspace cursor */
211 *sc_s_keypad, /* Start keypad mode */
212 *sc_e_keypad, /* End keypad mode */
213 *sc_s_mousecap, /* Start mouse capture mode */
214 *sc_e_mousecap, /* End mouse capture mode */
215 *sc_init, /* Startup terminal initialization */
216 *sc_deinit; /* Exit terminal de-initialization */
218 static int attrcolor = -1;
221 static int init_done = 0;
223 public int auto_wrap; /* Terminal does \r\n when write past margin */
224 public int ignaw; /* Terminal ignores \n immediately after wrap */
225 public int erase_char; /* The user's erase char */
226 public int erase2_char; /* The user's other erase char */
227 public int kill_char; /* The user's line-kill char */
228 public int werase_char; /* The user's word-erase char */
229 public int sc_width, sc_height; /* Height & width of screen */
230 public int bo_s_width, bo_e_width; /* Printing width of boldface seq */
231 public int ul_s_width, ul_e_width; /* Printing width of underline seq */
232 public int so_s_width, so_e_width; /* Printing width of standout seq */
233 public int bl_s_width, bl_e_width; /* Printing width of blink seq */
234 public int above_mem, below_mem; /* Memory retained above/below screen */
235 public int can_goto_line; /* Can move cursor to any line */
236 public int clear_bg; /* Clear fills with background color */
237 public int missing_cap = 0; /* Some capability is missing */
238 public char *kent = NULL; /* Keypad ENTER sequence */
239 public int term_init_done = FALSE;
241 static int attrmode = AT_NORMAL;
242 static int termcap_debug = -1;
244 extern int one_screen;
246 extern char *ttyin_name;
250 static char *cheaper LESSPARAMS((char *t1, char *t2, char *def));
251 static void tmodes LESSPARAMS((char *incap, char *outcap, char **instr,
252 char **outstr, char *def_instr, char *def_outstr, char **spp));
256 * These two variables are sometimes defined in,
257 * and needed by, the termcap library.
259 #if MUST_DEFINE_OSPEED
260 extern short ospeed; /* Terminal output baud rate */
261 extern char PC; /* Pad character */
268 extern int quiet; /* If VERY_QUIET, use visual bell for bell */
269 extern int no_back_scroll;
272 extern int no_keypad;
275 extern int screen_trashed;
276 extern int top_scroll;
277 extern int quit_if_one_screen;
281 extern int use_color;
283 extern int hilite_search;
285 #if MSDOS_COMPILER==WIN32C
287 extern DWORD console_mode;
288 #ifndef ENABLE_EXTENDED_FLAGS
289 #define ENABLE_EXTENDED_FLAGS 0x80
290 #define ENABLE_QUICK_EDIT_MODE 0x40
296 extern char *tgetstr();
297 extern char *tgoto();
301 * Change terminal to "raw mode", or restore to "normal" mode.
303 * 1. An outstanding read will complete on receipt of a single keystroke.
304 * 2. Input is not echoed.
305 * 3. On output, \n is mapped to \r\n.
306 * 4. \t is NOT expanded into spaces.
307 * 5. Signal-causing characters such as ctrl-C (interrupt),
308 * etc. are NOT disabled.
309 * It doesn't matter whether an input \n is mapped to \r, or vice versa.
315 static int curr_on = 0;
319 erase2_char = '\b'; /* in case OS doesn't know about erase2 */
320 #if HAVE_TERMIOS_H && HAVE_TERMIOS_FUNCS
323 static struct termios save_term;
324 static int saved_term = 0;
329 * Get terminal modes.
334 * Save modes and set certain variables dependent on modes.
342 switch (cfgetospeed(&s))
345 case B0: ospeed = 0; break;
348 case B50: ospeed = 1; break;
351 case B75: ospeed = 2; break;
354 case B110: ospeed = 3; break;
357 case B134: ospeed = 4; break;
360 case B150: ospeed = 5; break;
363 case B200: ospeed = 6; break;
366 case B300: ospeed = 7; break;
369 case B600: ospeed = 8; break;
372 case B1200: ospeed = 9; break;
375 case B1800: ospeed = 10; break;
378 case B2400: ospeed = 11; break;
381 case B4800: ospeed = 12; break;
384 case B9600: ospeed = 13; break;
387 case EXTA: ospeed = 14; break;
390 case EXTB: ospeed = 15; break;
393 case B57600: ospeed = 16; break;
396 case B115200: ospeed = 17; break;
401 erase_char = s.c_cc[VERASE];
403 erase2_char = s.c_cc[VERASE2];
405 kill_char = s.c_cc[VKILL];
407 werase_char = s.c_cc[VWERASE];
409 werase_char = CONTROL('W');
413 * Set the modes to the way we want them.
475 #if MUST_SET_LINE_DISCIPLINE
477 * System's termios is broken; need to explicitly
478 * request TERMIODISC line discipline.
480 s.c_line = TERMIODISC;
485 * Restore saved modes.
492 tcsetattr(tty, TCSADRAIN, &s);
493 #if MUST_SET_LINE_DISCIPLINE
497 * Broken termios *ignores* any line discipline
498 * except TERMIODISC. A different old line discipline
499 * is therefore not restored, yet. Restore the old
500 * line discipline by hand.
502 ioctl(tty, TIOCSETD, &save_term.c_line);
510 static struct termio save_term;
511 static int saved_term = 0;
516 * Get terminal modes.
518 ioctl(tty, TCGETA, &s);
521 * Save modes and set certain variables dependent on modes.
529 ospeed = s.c_cflag & CBAUD;
531 erase_char = s.c_cc[VERASE];
532 kill_char = s.c_cc[VKILL];
534 werase_char = s.c_cc[VWERASE];
536 werase_char = CONTROL('W');
540 * Set the modes to the way we want them.
542 s.c_lflag &= ~(ICANON|ECHO|ECHOE|ECHOK|ECHONL);
543 s.c_oflag |= (OPOST|ONLCR|TAB3);
544 s.c_oflag &= ~(OCRNL|ONOCR|ONLRET);
550 * Restore saved modes.
554 ioctl(tty, TCSETAW, &s);
560 static struct sgttyb save_term;
561 static int saved_term = 0;
566 * Get terminal modes.
568 ioctl(tty, TIOCGETP, &s);
571 * Save modes and set certain variables dependent on modes.
579 ospeed = s.sg_ospeed;
581 erase_char = s.sg_erase;
582 kill_char = s.sg_kill;
583 werase_char = CONTROL('W');
586 * Set the modes to the way we want them.
588 s.sg_flags |= CBREAK;
589 s.sg_flags &= ~(ECHO|XTABS);
593 * Restore saved modes.
597 ioctl(tty, TIOCSETN, &s);
603 static struct sgbuf save_term;
604 static int saved_term = 0;
609 * Get terminal modes.
614 * Save modes and set certain variables dependent on modes.
621 erase_char = s.sg_bspch;
622 kill_char = s.sg_dlnch;
623 werase_char = CONTROL('W');
626 * Set the modes to the way we want them.
635 * Restore saved modes.
642 /* MS-DOS, Windows, or OS2 */
645 LSIGNAL(SIGINT, SIG_IGN);
648 #if MSDOS_COMPILER==DJGPPC
649 kill_char = CONTROL('U');
651 * So that when we shell out or run another program, its
652 * stdin is in cooked mode. We do not switch stdin to binary
653 * mode if fd0 is zero, since that means we were called before
654 * tty was reopened in open_getchr, in which case we would be
655 * changing the original stdin device outside less.
658 setmode(0, on ? O_BINARY : O_TEXT);
662 werase_char = CONTROL('W');
672 * Some glue to prevent calling termcap functions if tgetent() failed.
684 struct env { struct env *next; char *name; char *value; };
685 static struct env *envs = NULL;
687 for (p = envs; p != NULL; p = p->next)
688 if (strcmp(p->name, capname) == 0)
690 p = (struct env *) ecalloc(1, sizeof(struct env));
691 p->name = save(capname);
692 p->value = (char *) ecalloc(strlen(capname)+3, sizeof(char));
693 sprintf(p->value, "<%s>", capname);
698 SNPRINTF1(name, sizeof(name), "LESS_TERMCAP_%s", capname);
699 return (lgetenv(name));
708 if ((s = ltget_env(capname)) != NULL)
709 return (*s != '\0' && *s != '0');
712 return (tgetflag(capname));
721 if ((s = ltget_env(capname)) != NULL)
725 return (tgetnum(capname));
729 ltgetstr(capname, pp)
735 if ((s = ltget_env(capname)) != NULL)
739 return (tgetstr(capname, pp));
741 #endif /* MSDOS_COMPILER */
744 * Get size of the output screen.
756 #define DEF_SC_WIDTH 80
758 #define DEF_SC_HEIGHT 25
760 #define DEF_SC_HEIGHT 24
764 sys_width = sys_height = 0;
766 #if MSDOS_COMPILER==MSOFTC
768 struct videoconfig w;
770 sys_height = w.numtextrows;
771 sys_width = w.numtextcols;
774 #if MSDOS_COMPILER==BORLANDC || MSDOS_COMPILER==DJGPPC
778 sys_height = w.screenheight;
779 sys_width = w.screenwidth;
782 #if MSDOS_COMPILER==WIN32C
784 CONSOLE_SCREEN_BUFFER_INFO scr;
785 GetConsoleScreenBufferInfo(con_out, &scr);
786 sys_height = scr.srWindow.Bottom - scr.srWindow.Top + 1;
787 sys_width = scr.srWindow.Right - scr.srWindow.Left + 1;
797 * When using terminal emulators for XFree86/OS2, the
798 * _scrsize function does not work well.
799 * Call the scrsize.exe program to get the window size.
801 windowid = getenv("WINDOWID");
802 if (windowid != NULL)
804 FILE *fd = popen("scrsize", "rt");
808 fscanf(fd, "%i %i", &w, &h);
822 if (ioctl(2, TIOCGWINSZ, &w) == 0)
825 sys_height = w.ws_row;
827 sys_width = w.ws_col;
834 if (ioctl(2, WIOCGETD, &w) == 0)
837 sys_height = w.uw_height / w.uw_vs;
839 sys_width = w.uw_width / w.uw_hs;
850 sc_height = sys_height;
851 else if ((s = lgetenv("LINES")) != NULL)
854 else if ((n = ltgetnum("li")) > 0)
858 sc_height = DEF_SC_HEIGHT;
861 sc_width = sys_width;
862 else if ((s = lgetenv("COLUMNS")) != NULL)
865 else if ((n = ltgetnum("co")) > 0)
869 sc_width = DEF_SC_WIDTH;
872 #if MSDOS_COMPILER==MSOFTC
874 * Figure out how many empty loops it takes to delay a millisecond.
877 get_clock(VOID_PARAM)
882 * Get synchronized at the start of a tick.
885 while (clock() == start)
888 * Now count loops till the next tick.
892 while (clock() == start)
895 * Convert from (loops per clock) to (loops per millisecond).
897 msec_loops *= CLOCKS_PER_SEC;
902 * Delay for a specified number of milliseconds.
912 for (i = 0; i < msec_loops; i++)
919 * Return the characters actually input by a "special" key.
925 static char tbuf[40];
927 #if MSDOS_COMPILER || OS2
928 static char k_right[] = { '\340', PCK_RIGHT, 0 };
929 static char k_left[] = { '\340', PCK_LEFT, 0 };
930 static char k_ctl_right[] = { '\340', PCK_CTL_RIGHT, 0 };
931 static char k_ctl_left[] = { '\340', PCK_CTL_LEFT, 0 };
932 static char k_insert[] = { '\340', PCK_INSERT, 0 };
933 static char k_delete[] = { '\340', PCK_DELETE, 0 };
934 static char k_ctl_delete[] = { '\340', PCK_CTL_DELETE, 0 };
935 static char k_ctl_backspace[] = { '\177', 0 };
936 static char k_backspace[] = { '\b', 0 };
937 static char k_home[] = { '\340', PCK_HOME, 0 };
938 static char k_end[] = { '\340', PCK_END, 0 };
939 static char k_up[] = { '\340', PCK_UP, 0 };
940 static char k_down[] = { '\340', PCK_DOWN, 0 };
941 static char k_backtab[] = { '\340', PCK_SHIFT_TAB, 0 };
942 static char k_pagedown[] = { '\340', PCK_PAGEDOWN, 0 };
943 static char k_pageup[] = { '\340', PCK_PAGEUP, 0 };
944 static char k_f1[] = { '\340', PCK_F1, 0 };
954 * If windowid is not NULL, assume less is executed in
955 * the XFree86 environment.
958 s = windowid ? ltgetstr("kr", &sp) : k_right;
961 s = windowid ? ltgetstr("kl", &sp) : k_left;
964 s = windowid ? ltgetstr("ku", &sp) : k_up;
967 s = windowid ? ltgetstr("kd", &sp) : k_down;
970 s = windowid ? ltgetstr("kP", &sp) : k_pageup;
973 s = windowid ? ltgetstr("kN", &sp) : k_pagedown;
976 s = windowid ? ltgetstr("kh", &sp) : k_home;
979 s = windowid ? ltgetstr("@7", &sp) : k_end;
982 s = windowid ? ltgetstr("kD", &sp) : k_delete;
1020 #if MSDOS_COMPILER || OS2
1024 case SK_CTL_LEFT_ARROW:
1027 case SK_CTL_RIGHT_ARROW:
1030 case SK_CTL_BACKSPACE:
1031 s = k_ctl_backspace;
1046 case SK_RIGHT_ARROW:
1047 s = ltgetstr("kr", &sp);
1050 s = ltgetstr("kl", &sp);
1053 s = ltgetstr("ku", &sp);
1056 s = ltgetstr("kd", &sp);
1059 s = ltgetstr("kP", &sp);
1062 s = ltgetstr("kN", &sp);
1065 s = ltgetstr("kh", &sp);
1068 s = ltgetstr("@7", &sp);
1071 s = ltgetstr("kD", &sp);
1080 s = ltgetstr("kb", &sp);
1090 tbuf[0] = CONTROL('K');
1101 * Get terminal capabilities via termcap.
1104 get_term(VOID_PARAM)
1106 termcap_debug = !isnullenv(lgetenv("LESS_TERMCAP_DEBUG"));
1113 * Set up default colors.
1114 * The xx_s_width and xx_e_width vars are already initialized to 0.
1116 #if MSDOS_COMPILER==MSOFTC
1117 sy_bg_color = _getbkcolor();
1118 sy_fg_color = _gettextcolor();
1121 #if MSDOS_COMPILER==BORLANDC || MSDOS_COMPILER==DJGPPC
1125 sy_bg_color = (w.attribute >> 4) & 0x0F;
1126 sy_fg_color = (w.attribute >> 0) & 0x0F;
1129 #if MSDOS_COMPILER==WIN32C
1131 CONSOLE_SCREEN_BUFFER_INFO scr;
1133 con_out_save = con_out = GetStdHandle(STD_OUTPUT_HANDLE);
1135 * Always open stdin in binary. Note this *must* be done
1136 * before any file operations have been done on fd0.
1139 GetConsoleMode(con_out, &init_output_mode);
1140 GetConsoleScreenBufferInfo(con_out, &scr);
1141 curr_attr = scr.wAttributes;
1142 sy_bg_color = (curr_attr & BG_COLORS) >> 4; /* normalize */
1143 sy_fg_color = curr_attr & FG_COLORS;
1148 nm_fg_color = sy_fg_color;
1149 nm_bg_color = sy_bg_color;
1161 * Get size of the screen.
1167 #else /* !MSDOS_COMPILER */
1173 * Some termcap libraries assume termbuf is static
1174 * (accessible after tgetent returns).
1176 static char termbuf[TERMBUF_SIZE];
1177 static char sbuf[TERMSBUF_SIZE];
1181 * Make sure the termcap database is available.
1183 sp = lgetenv("TERMCAP");
1187 if ((sp = homefile("termcap.dat")) != NULL)
1189 termcap = (char *) ecalloc(strlen(sp)+9, sizeof(char));
1190 sprintf(termcap, "TERMCAP=%s", sp);
1197 * Find out what kind of terminal this is.
1199 if ((term = lgetenv("TERM")) == NULL)
1200 term = DEFAULT_TERM;
1202 /* {{ Should probably just pass NULL instead of termbuf. }} */
1203 if (tgetent(termbuf, term) != TGETENT_OK)
1205 if (ltgetflag("hc"))
1209 * Get size of the screen.
1214 auto_wrap = ltgetflag("am");
1215 ignaw = ltgetflag("xn");
1216 above_mem = ltgetflag("da");
1217 below_mem = ltgetflag("db");
1218 clear_bg = ltgetflag("ut");
1221 * Assumes termcap variable "sg" is the printing width of:
1222 * the standout sequence, the end standout sequence,
1223 * the underline sequence, the end underline sequence,
1224 * the boldface sequence, and the end boldface sequence.
1226 if ((so_s_width = ltgetnum("sg")) < 0)
1228 so_e_width = so_s_width;
1230 bo_s_width = bo_e_width = so_s_width;
1231 ul_s_width = ul_e_width = so_s_width;
1232 bl_s_width = bl_e_width = so_s_width;
1235 if (so_s_width > 0 || so_e_width > 0)
1237 * Disable highlighting by default on magic cookie terminals.
1238 * Turning on highlighting might change the displayed width
1239 * of a line, causing the display to get messed up.
1240 * The user can turn it back on with -g,
1241 * but she won't like the results.
1247 * Get various string-valued capabilities.
1252 sc_pad = ltgetstr("pc", &sp);
1257 sc_s_keypad = ltgetstr("ks", &sp);
1258 if (sc_s_keypad == NULL)
1260 sc_e_keypad = ltgetstr("ke", &sp);
1261 if (sc_e_keypad == NULL)
1263 kent = ltgetstr("@8", &sp);
1265 sc_s_mousecap = ltgetstr("MOUSE_START", &sp);
1266 if (sc_s_mousecap == NULL)
1267 sc_s_mousecap = ESCS "[?1000h" ESCS "[?1006h";
1268 sc_e_mousecap = ltgetstr("MOUSE_END", &sp);
1269 if (sc_e_mousecap == NULL)
1270 sc_e_mousecap = ESCS "[?1006l" ESCS "[?1000l";
1272 sc_init = ltgetstr("ti", &sp);
1273 if (sc_init == NULL)
1276 sc_deinit= ltgetstr("te", &sp);
1277 if (sc_deinit == NULL)
1280 sc_eol_clear = ltgetstr("ce", &sp);
1281 if (sc_eol_clear == NULL || *sc_eol_clear == '\0')
1287 sc_eos_clear = ltgetstr("cd", &sp);
1288 if (below_mem && (sc_eos_clear == NULL || *sc_eos_clear == '\0'))
1294 sc_clear = ltgetstr("cl", &sp);
1295 if (sc_clear == NULL || *sc_clear == '\0')
1301 sc_move = ltgetstr("cm", &sp);
1302 if (sc_move == NULL || *sc_move == '\0')
1305 * This is not an error here, because we don't
1306 * always need sc_move.
1307 * We need it only if we don't have home or lower-left.
1314 tmodes("so", "se", &sc_s_in, &sc_s_out, "", "", &sp);
1315 tmodes("us", "ue", &sc_u_in, &sc_u_out, sc_s_in, sc_s_out, &sp);
1316 tmodes("md", "me", &sc_b_in, &sc_b_out, sc_s_in, sc_s_out, &sp);
1317 tmodes("mb", "me", &sc_bl_in, &sc_bl_out, sc_s_in, sc_s_out, &sp);
1319 sc_visual_bell = ltgetstr("vb", &sp);
1320 if (sc_visual_bell == NULL)
1321 sc_visual_bell = "";
1323 if (ltgetflag("bs"))
1324 sc_backspace = "\b";
1327 sc_backspace = ltgetstr("bc", &sp);
1328 if (sc_backspace == NULL || *sc_backspace == '\0')
1329 sc_backspace = "\b";
1333 * Choose between using "ho" and "cm" ("home" and "cursor move")
1334 * to move the cursor to the upper left corner of the screen.
1336 t1 = ltgetstr("ho", &sp);
1339 if (*sc_move == '\0')
1343 strcpy(sp, tgoto(sc_move, 0, 0));
1345 sp += strlen(sp) + 1;
1347 sc_home = cheaper(t1, t2, "|\b^");
1350 * Choose between using "ll" and "cm" ("lower left" and "cursor move")
1351 * to move the cursor to the lower left corner of the screen.
1353 t1 = ltgetstr("ll", &sp);
1356 if (*sc_move == '\0')
1360 strcpy(sp, tgoto(sc_move, 0, sc_height-1));
1362 sp += strlen(sp) + 1;
1364 sc_lower_left = cheaper(t1, t2, "\r");
1367 * Get carriage return string.
1369 sc_return = ltgetstr("cr", &sp);
1370 if (sc_return == NULL)
1374 * Choose between using "al" or "sr" ("add line" or "scroll reverse")
1375 * to add a line at the top of the screen.
1377 t1 = ltgetstr("al", &sp);
1380 t2 = ltgetstr("sr", &sp);
1384 if (*t1 == '\0' && *t2 == '\0')
1391 sc_addline = cheaper(t1, t2, "");
1392 if (*sc_addline == '\0')
1395 * Force repaint on any backward movement.
1400 #endif /* MSDOS_COMPILER */
1405 * Return the cost of displaying a termcap string.
1406 * We use the trick of calling tputs, but as a char printing function
1407 * we give it inc_costcount, which just increments "costcount".
1408 * This tells us how many chars would be printed by using this string.
1409 * {{ Couldn't we just use strlen? }}
1411 static int costcount;
1427 tputs(t, sc_height, inc_costcount);
1432 * Return the "best" of the two given termcap strings.
1433 * The best, if both exist, is the one with the lower
1434 * cost (see cost() function).
1437 cheaper(t1, t2, def)
1441 if (*t1 == '\0' && *t2 == '\0')
1450 if (cost(t1) < cost(t2))
1456 tmodes(incap, outcap, instr, outstr, def_instr, def_outstr, spp)
1465 *instr = ltgetstr(incap, spp);
1470 *outstr = def_outstr;
1474 *outstr = ltgetstr(outcap, spp);
1475 if (*outstr == NULL)
1476 /* No specific out capability; use "me". */
1477 *outstr = ltgetstr("me", spp);
1478 if (*outstr == NULL)
1479 /* Don't even have "me"; use a null string. */
1483 #endif /* MSDOS_COMPILER */
1487 * Below are the functions which perform all the
1488 * terminal-specific screen manipulation.
1494 #if MSDOS_COMPILER==WIN32C
1496 _settextposition(int row, int col)
1499 CONSOLE_SCREEN_BUFFER_INFO csbi;
1501 GetConsoleScreenBufferInfo(con_out, &csbi);
1502 cpos.X = csbi.srWindow.Left + (col - 1);
1503 cpos.Y = csbi.srWindow.Top + (row - 1);
1504 SetConsoleCursorPosition(con_out, cpos);
1509 * Initialize the screen to the correct color at startup.
1512 initcolor(VOID_PARAM)
1514 #if MSDOS_COMPILER==BORLANDC || MSDOS_COMPILER==DJGPPC
1517 SETCOLORS(nm_fg_color, nm_bg_color);
1520 * This clears the screen at startup. This is different from
1521 * the behavior of other versions of less. Disable it for now.
1528 * Create a complete, blank screen using "normal" colors.
1530 SETCOLORS(nm_fg_color, nm_bg_color);
1531 blanks = (char *) ecalloc(width+1, sizeof(char));
1532 for (col = 0; col < sc_width; col++)
1534 blanks[sc_width] = '\0';
1535 for (row = 0; row < sc_height; row++)
1542 #if MSDOS_COMPILER==WIN32C
1545 * Enable virtual terminal processing, if available.
1548 win32_init_vt_term(VOID_PARAM)
1552 if (vt_enabled == 0 || (vt_enabled == 1 && con_out == con_out_ours))
1555 GetConsoleMode(con_out, &output_mode);
1556 vt_enabled = SetConsoleMode(con_out,
1557 output_mode | ENABLE_VIRTUAL_TERMINAL_PROCESSING);
1566 win32_deinit_vt_term(VOID_PARAM)
1568 if (vt_enabled == 1 && con_out == con_out_save)
1569 SetConsoleMode(con_out, init_output_mode);
1573 * Termcap-like init with a private win32 console.
1576 win32_init_term(VOID_PARAM)
1578 CONSOLE_SCREEN_BUFFER_INFO scr;
1581 if (con_out_save == INVALID_HANDLE_VALUE)
1584 GetConsoleScreenBufferInfo(con_out_save, &scr);
1586 if (con_out_ours == INVALID_HANDLE_VALUE)
1589 * Create our own screen buffer, so that we
1590 * may restore the original when done.
1592 con_out_ours = CreateConsoleScreenBuffer(
1593 GENERIC_WRITE | GENERIC_READ,
1594 FILE_SHARE_WRITE | FILE_SHARE_READ,
1595 (LPSECURITY_ATTRIBUTES) NULL,
1596 CONSOLE_TEXTMODE_BUFFER,
1600 size.X = scr.srWindow.Right - scr.srWindow.Left + 1;
1601 size.Y = scr.srWindow.Bottom - scr.srWindow.Top + 1;
1602 SetConsoleScreenBufferSize(con_out_ours, size);
1603 SetConsoleActiveScreenBuffer(con_out_ours);
1604 con_out = con_out_ours;
1608 * Restore the startup console.
1611 win32_deinit_term(VOID_PARAM)
1613 if (con_out_save == INVALID_HANDLE_VALUE)
1616 (void) CloseHandle(con_out_ours);
1617 SetConsoleActiveScreenBuffer(con_out_save);
1618 con_out = con_out_save;
1625 do_tputs(str, affcnt, f_putc)
1631 if (ttyin_name != NULL)
1635 tputs(str, affcnt, f_putc);
1639 * Like tputs but we handle $<...> delay strings here because
1640 * some implementations of tputs don't perform delays correctly.
1643 ltputs(str, affcnt, f_putc)
1648 while (str != NULL && *str != '\0')
1651 char *obrac = strstr(str, "$<");
1655 int slen = obrac - str;
1656 if (slen < sizeof(str2))
1659 /* Output first part of string (before "$<"). */
1660 memcpy(str2, str, slen);
1662 do_tputs(str2, affcnt, f_putc);
1664 /* Perform the delay. */
1665 delay = lstrtoi(str, &str);
1670 /* Skip past closing ">" at end of delay string. */
1671 str = strstr(str, ">");
1678 /* Pass the rest of the string to tputs and we're done. */
1679 do_tputs(str, affcnt, f_putc);
1683 #endif /* MSDOS_COMPILER */
1686 * Configure the termimal so mouse clicks and wheel moves
1687 * produce input to less.
1690 init_mouse(VOID_PARAM)
1693 ltputs(sc_s_mousecap, sc_height, putchr);
1695 #if MSDOS_COMPILER==WIN32C
1696 SetConsoleMode(tty, ENABLE_PROCESSED_INPUT | ENABLE_MOUSE_INPUT
1697 | ENABLE_EXTENDED_FLAGS /* disable quick edit */);
1704 * Configure the terminal so mouse clicks and wheel moves
1705 * are handled by the system (so text can be selected, etc).
1708 deinit_mouse(VOID_PARAM)
1711 ltputs(sc_e_mousecap, sc_height, putchr);
1713 #if MSDOS_COMPILER==WIN32C
1714 SetConsoleMode(tty, ENABLE_PROCESSED_INPUT | ENABLE_EXTENDED_FLAGS
1715 | (console_mode & ENABLE_QUICK_EDIT_MODE));
1721 * Initialize terminal
1726 clear_bot_if_needed();
1728 if (!(quit_if_one_screen && one_screen))
1732 ltputs(sc_init, sc_height, putchr);
1736 ltputs(sc_s_keypad, sc_height, putchr);
1746 * This is nice to terminals with no alternate screen,
1747 * but with saved scrolled-off-the-top lines. This way,
1748 * no previous line is lost, but we start with a whole
1749 * screen to ourself.
1751 for (i = 1; i < sc_height; i++)
1756 #if MSDOS_COMPILER==WIN32C
1757 if (!(quit_if_one_screen && one_screen))
1768 win32_init_vt_term();
1777 * Deinitialize terminal
1785 if (!(quit_if_one_screen && one_screen))
1790 ltputs(sc_e_keypad, sc_height, putchr);
1792 ltputs(sc_deinit, sc_height, putchr);
1795 /* Restore system colors. */
1796 SETCOLORS(sy_fg_color, sy_bg_color);
1797 #if MSDOS_COMPILER==WIN32C
1798 win32_deinit_vt_term();
1799 if (!(quit_if_one_screen && one_screen))
1804 win32_deinit_term();
1807 /* Need clreol to make SETCOLORS take effect. */
1815 * Are we interactive (ie. writing to an initialized tty)?
1818 interactive(VOID_PARAM)
1820 return (is_tty && init_done);
1824 assert_interactive(VOID_PARAM)
1826 if (interactive()) return;
1831 * Home cursor (move to upper left corner of screen).
1836 assert_interactive();
1838 ltputs(sc_home, 1, putchr);
1841 _settextposition(1,1);
1846 * Add a blank line (called with cursor at home).
1847 * Should scroll the display down.
1850 add_line(VOID_PARAM)
1852 assert_interactive();
1854 ltputs(sc_addline, sc_height, putchr);
1857 #if MSDOS_COMPILER==MSOFTC
1858 _scrolltextwindow(_GSCROLLDOWN);
1859 _settextposition(1,1);
1861 #if MSDOS_COMPILER==BORLANDC || MSDOS_COMPILER==DJGPPC
1862 movetext(1,1, sc_width,sc_height-1, 1,2);
1866 #if MSDOS_COMPILER==WIN32C
1869 SMALL_RECT rcSrc, rcClip;
1871 CONSOLE_SCREEN_BUFFER_INFO csbi;
1873 GetConsoleScreenBufferInfo(con_out,&csbi);
1875 /* The clip rectangle is the entire visible screen. */
1876 rcClip.Left = csbi.srWindow.Left;
1877 rcClip.Top = csbi.srWindow.Top;
1878 rcClip.Right = csbi.srWindow.Right;
1879 rcClip.Bottom = csbi.srWindow.Bottom;
1881 /* The source rectangle is the visible screen minus the last line. */
1885 /* Move the top left corner of the source window down one row. */
1886 new_org.X = rcSrc.Left;
1887 new_org.Y = rcSrc.Top + 1;
1889 /* Fill the right character and attributes. */
1890 fillchar.Char.AsciiChar = ' ';
1891 curr_attr = MAKEATTR(nm_fg_color, nm_bg_color);
1892 fillchar.Attributes = curr_attr;
1893 ScrollConsoleScreenBuffer(con_out, &rcSrc, &rcClip, new_org, &fillchar);
1894 _settextposition(1,1);
1904 * Remove the n topmost lines and scroll everything below it in the
1905 * window upward. This is needed to stop leaking the topmost line
1906 * into the scrollback buffer when we go down-one-line (in WIN32).
1912 #if MSDOS_COMPILER==WIN32C
1913 SMALL_RECT rcSrc, rcClip;
1916 CONSOLE_SCREEN_BUFFER_INFO csbi; /* to get buffer info */
1918 if (n >= sc_height - 1)
1927 GetConsoleScreenBufferInfo(con_out, &csbi);
1929 /* Get the extent of all-visible-rows-but-the-last. */
1930 rcSrc.Left = csbi.srWindow.Left;
1931 rcSrc.Top = csbi.srWindow.Top + n;
1932 rcSrc.Right = csbi.srWindow.Right;
1933 rcSrc.Bottom = csbi.srWindow.Bottom;
1935 /* Get the clip rectangle. */
1936 rcClip.Left = rcSrc.Left;
1937 rcClip.Top = csbi.srWindow.Top;
1938 rcClip.Right = rcSrc.Right;
1939 rcClip.Bottom = rcSrc.Bottom ;
1941 /* Move the source window up n rows. */
1942 new_org.X = rcSrc.Left;
1943 new_org.Y = rcSrc.Top - n;
1945 /* Fill the right character and attributes. */
1946 fillchar.Char.AsciiChar = ' ';
1947 curr_attr = MAKEATTR(nm_fg_color, nm_bg_color);
1948 fillchar.Attributes = curr_attr;
1950 ScrollConsoleScreenBuffer(con_out, &rcSrc, &rcClip, new_org, &fillchar);
1952 /* Position cursor on first blank line. */
1953 goto_line(sc_height - n - 1);
1958 #if MSDOS_COMPILER==WIN32C
1963 win32_clear(VOID_PARAM)
1966 * This will clear only the currently visible rows of the NT
1967 * console buffer, which means none of the precious scrollback
1968 * rows are touched making for faster scrolling. Note that, if
1969 * the window has fewer columns than the console buffer (i.e.
1970 * there is a horizontal scrollbar as well), the entire width
1971 * of the visible rows will be cleared.
1976 CONSOLE_SCREEN_BUFFER_INFO csbi;
1978 /* get the number of cells in the current buffer */
1979 GetConsoleScreenBufferInfo(con_out, &csbi);
1980 winsz = csbi.dwSize.X * (csbi.srWindow.Bottom - csbi.srWindow.Top + 1);
1982 topleft.Y = csbi.srWindow.Top;
1984 curr_attr = MAKEATTR(nm_fg_color, nm_bg_color);
1985 FillConsoleOutputCharacter(con_out, ' ', winsz, topleft, &nchars);
1986 FillConsoleOutputAttribute(con_out, curr_attr, winsz, topleft, &nchars);
1990 * Remove the n topmost lines and scroll everything below it in the
1997 SMALL_RECT rcSrc, rcClip;
2003 CONSOLE_SCREEN_BUFFER_INFO csbi;
2008 if (n >= sc_height - 1)
2011 _settextposition(1,1);
2015 /* Get the extent of what will remain visible after scrolling. */
2016 GetConsoleScreenBufferInfo(con_out, &csbi);
2017 rcSrc.Left = csbi.srWindow.Left;
2018 rcSrc.Top = csbi.srWindow.Top + n;
2019 rcSrc.Right = csbi.srWindow.Right;
2020 rcSrc.Bottom = csbi.srWindow.Bottom;
2022 /* Get the clip rectangle. */
2023 rcClip.Left = rcSrc.Left;
2024 rcClip.Top = csbi.srWindow.Top;
2025 rcClip.Right = rcSrc.Right;
2026 rcClip.Bottom = rcSrc.Bottom ;
2028 /* Move the source text to the top of the screen. */
2029 new_org.X = rcSrc.Left;
2030 new_org.Y = rcClip.Top;
2032 /* Fill the right character and attributes. */
2033 fillchar.Char.AsciiChar = ' ';
2034 fillchar.Attributes = MAKEATTR(nm_fg_color, nm_bg_color);
2036 /* Scroll the window. */
2037 SetConsoleTextAttribute(con_out, fillchar.Attributes);
2038 ScrollConsoleScreenBuffer(con_out, &rcSrc, &rcClip, new_org, &fillchar);
2040 /* Clear remaining lines at bottom. */
2041 topleft.X = csbi.dwCursorPosition.X;
2042 topleft.Y = rcSrc.Bottom - n;
2043 size = (n * csbi.dwSize.X) + (rcSrc.Right - topleft.X);
2044 FillConsoleOutputCharacter(con_out, ' ', size, topleft,
2046 FillConsoleOutputAttribute(con_out, fillchar.Attributes, size, topleft,
2048 SetConsoleTextAttribute(con_out, curr_attr);
2050 /* Move cursor n lines up from where it was. */
2051 csbi.dwCursorPosition.Y -= n;
2052 SetConsoleCursorPosition(con_out, csbi.dwCursorPosition);
2057 * Move cursor to lower left corner of screen.
2060 lower_left(VOID_PARAM)
2062 assert_interactive();
2064 ltputs(sc_lower_left, 1, putchr);
2067 _settextposition(sc_height, 1);
2072 * Move cursor to left position of current line.
2075 line_left(VOID_PARAM)
2077 assert_interactive();
2079 ltputs(sc_return, 1, putchr);
2084 #if MSDOS_COMPILER==WIN32C
2086 CONSOLE_SCREEN_BUFFER_INFO scr;
2087 GetConsoleScreenBufferInfo(con_out, &scr);
2088 row = scr.dwCursorPosition.Y - scr.srWindow.Top + 1;
2091 #if MSDOS_COMPILER==BORLANDC || MSDOS_COMPILER==DJGPPC
2095 struct rccoord tpos = _gettextposition();
2100 _settextposition(row, 1);
2106 * Check if the console size has changed and reset internals
2107 * (in lieu of SIGWINCH for WIN32).
2110 check_winch(VOID_PARAM)
2112 #if MSDOS_COMPILER==WIN32C
2113 CONSOLE_SCREEN_BUFFER_INFO scr;
2116 if (con_out == INVALID_HANDLE_VALUE)
2120 GetConsoleScreenBufferInfo(con_out, &scr);
2121 size.Y = scr.srWindow.Bottom - scr.srWindow.Top + 1;
2122 size.X = scr.srWindow.Right - scr.srWindow.Left + 1;
2123 if (size.Y != sc_height || size.X != sc_width)
2127 if (!no_init && con_out_ours == con_out)
2128 SetConsoleScreenBufferSize(con_out, size);
2130 wscroll = (sc_height + 1) / 2;
2137 * Goto a specific line on the screen.
2143 assert_interactive();
2145 ltputs(tgoto(sc_move, 0, sindex), 1, putchr);
2148 _settextposition(sindex+1, 1);
2152 #if MSDOS_COMPILER==MSOFTC || MSDOS_COMPILER==BORLANDC
2154 * Create an alternate screen which is all white.
2155 * This screen is used to create a "flash" effect, by displaying it
2156 * briefly and then switching back to the normal screen.
2157 * {{ Yuck! There must be a better way to get a visual bell. }}
2160 create_flash(VOID_PARAM)
2162 #if MSDOS_COMPILER==MSOFTC
2163 struct videoconfig w;
2167 _getvideoconfig(&w);
2168 videopages = w.numvideopages;
2171 at_enter(AT_STANDOUT);
2176 at_enter(AT_STANDOUT);
2177 blanks = (char *) ecalloc(w.numtextcols, sizeof(char));
2178 for (col = 0; col < w.numtextcols; col++)
2180 for (row = w.numtextrows; row > 0; row--)
2181 _outmem(blanks, w.numtextcols);
2188 #if MSDOS_COMPILER==BORLANDC
2191 whitescreen = (unsigned short *)
2192 malloc(sc_width * sc_height * sizeof(short));
2193 if (whitescreen == NULL)
2195 for (n = 0; n < sc_width * sc_height; n++)
2196 whitescreen[n] = 0x7020;
2201 #endif /* MSDOS_COMPILER */
2204 * Output the "visual bell", if there is one.
2210 if (*sc_visual_bell == '\0')
2212 ltputs(sc_visual_bell, sc_height, putchr);
2214 #if MSDOS_COMPILER==DJGPPC
2217 #if MSDOS_COMPILER==MSOFTC
2219 * Create a flash screen on the second video page.
2220 * Switch to that page, then switch back.
2230 #if MSDOS_COMPILER==BORLANDC
2231 unsigned short *currscreen;
2234 * Get a copy of the current screen.
2235 * Display the flash screen.
2236 * Then restore the old screen.
2240 if (whitescreen == NULL)
2242 currscreen = (unsigned short *)
2243 malloc(sc_width * sc_height * sizeof(short));
2244 if (currscreen == NULL) return;
2245 gettext(1, 1, sc_width, sc_height, currscreen);
2246 puttext(1, 1, sc_width, sc_height, whitescreen);
2248 puttext(1, 1, sc_width, sc_height, currscreen);
2251 #if MSDOS_COMPILER==WIN32C
2252 /* paint screen with an inverse color */
2255 /* leave it displayed for 100 msec. */
2258 /* restore with a redraw */
2274 putchr(CONTROL('G'));
2276 #if MSDOS_COMPILER==WIN32C
2285 * Ring the terminal bell.
2290 if (quiet == VERY_QUIET)
2302 assert_interactive();
2304 ltputs(sc_clear, sc_height, putchr);
2307 #if MSDOS_COMPILER==WIN32C
2310 _clearscreen(_GCLEARSCREEN);
2316 * Clear from the cursor to the end of the cursor's line.
2317 * {{ This must not move the cursor. }}
2320 clear_eol(VOID_PARAM)
2322 /* assert_interactive();*/
2324 ltputs(sc_eol_clear, 1, putchr);
2326 #if MSDOS_COMPILER==MSOFTC
2329 struct rccoord tpos;
2333 * Save current state.
2335 tpos = _gettextposition();
2336 _gettextwindow(&top, &left, &bot, &right);
2338 * Set a temporary window to the current line,
2339 * from the cursor's position to the right edge of the screen.
2340 * Then clear that window.
2342 _settextwindow(tpos.row, tpos.col, tpos.row, sc_width);
2343 _clearscreen(_GWINDOW);
2347 _settextwindow(top, left, bot, right);
2348 _settextposition(tpos.row, tpos.col);
2350 #if MSDOS_COMPILER==BORLANDC || MSDOS_COMPILER==DJGPPC
2354 #if MSDOS_COMPILER==WIN32C
2357 CONSOLE_SCREEN_BUFFER_INFO scr;
2360 memset(&scr, 0, sizeof(scr));
2361 GetConsoleScreenBufferInfo(con_out, &scr);
2362 cpos.X = scr.dwCursorPosition.X;
2363 cpos.Y = scr.dwCursorPosition.Y;
2364 curr_attr = MAKEATTR(nm_fg_color, nm_bg_color);
2365 FillConsoleOutputAttribute(con_out, curr_attr,
2366 scr.dwSize.X - cpos.X, cpos, &nchars);
2367 FillConsoleOutputCharacter(con_out, ' ',
2368 scr.dwSize.X - cpos.X, cpos, &nchars);
2376 * Clear the current line.
2377 * Clear the screen if there's off-screen memory below the display.
2380 clear_eol_bot(VOID_PARAM)
2382 assert_interactive();
2387 ltputs(sc_eos_clear, 1, putchr);
2389 ltputs(sc_eol_clear, 1, putchr);
2394 * Clear the bottom line of the display.
2395 * Leave the cursor at the beginning of the bottom line.
2398 clear_bot(VOID_PARAM)
2401 * If we're in a non-normal attribute mode, temporarily exit
2402 * the mode while we do the clear. Some terminals fill the
2403 * cleared area with the current attribute.
2410 if (attrmode == AT_NORMAL)
2414 int saved_attrmode = attrmode;
2418 at_enter(saved_attrmode);
2423 * Color string may be "x[y]" where x and y are 4-bit color chars,
2424 * or "N[.M]" where N and M are decimal integers>
2425 * Any of x,y,N,M may also be "-" to mean "unchanged".
2429 * Parse a 4-bit color char.
2438 case 'r': return CV_RED;
2439 case 'g': return CV_GREEN;
2440 case 'y': return CV_RED|CV_GREEN;
2441 case 'b': return CV_BLUE;
2442 case 'm': return CV_RED|CV_BLUE;
2443 case 'c': return CV_GREEN|CV_BLUE;
2444 case 'w': return CV_RED|CV_GREEN|CV_BLUE;
2445 case 'K': return 0|CV_BRIGHT;
2446 case 'R': return CV_RED|CV_BRIGHT;
2447 case 'G': return CV_GREEN|CV_BRIGHT;
2448 case 'Y': return CV_RED|CV_GREEN|CV_BRIGHT;
2449 case 'B': return CV_BLUE|CV_BRIGHT;
2450 case 'M': return CV_RED|CV_BLUE|CV_BRIGHT;
2451 case 'C': return CV_GREEN|CV_BLUE|CV_BRIGHT;
2452 case 'W': return CV_RED|CV_GREEN|CV_BLUE|CV_BRIGHT;
2453 case '-': return CV_NOCHANGE;
2454 default: return CV_ERROR;
2459 * Parse a color as a decimal integer.
2472 int color = lstrtoi(ops, ps);
2480 * Parse a color pair and return the foreground/background values.
2481 * Return type of color specifier:
2482 * CV_4BIT: fg/bg values are OR of CV_{RGB} bits.
2483 * CV_6BIT: fg/bg values are integers entered by user.
2486 parse_color(str, p_fg, p_bg)
2493 COLOR_TYPE type = CT_NULL;
2495 if (str == NULL || *str == '\0')
2498 str++; /* ignore leading + */
2500 fg = parse_color4(str[0]);
2501 bg = parse_color4((strlen(str) < 2) ? '-' : str[1]);
2502 if (fg != CV_ERROR && bg != CV_ERROR)
2506 fg = parse_color6(&str);
2507 bg = (fg != CV_ERROR && *str++ == '.') ? parse_color6(&str) : CV_NOCHANGE;
2508 if (fg != CV_ERROR && bg != CV_ERROR)
2511 if (p_fg != NULL) *p_fg = fg;
2512 if (p_bg != NULL) *p_bg = bg;
2525 case CV_RED: return 31;
2526 case CV_GREEN: return 32;
2527 case CV_RED|CV_GREEN: return 33;
2528 case CV_BLUE: return 34;
2529 case CV_RED|CV_BLUE: return 35;
2530 case CV_GREEN|CV_BLUE: return 36;
2531 case CV_RED|CV_GREEN|CV_BLUE: return 37;
2533 case CV_BRIGHT: return 90;
2534 case CV_RED|CV_BRIGHT: return 91;
2535 case CV_GREEN|CV_BRIGHT: return 92;
2536 case CV_RED|CV_GREEN|CV_BRIGHT: return 93;
2537 case CV_BLUE|CV_BRIGHT: return 94;
2538 case CV_RED|CV_BLUE|CV_BRIGHT: return 95;
2539 case CV_GREEN|CV_BLUE|CV_BRIGHT: return 96;
2540 case CV_RED|CV_GREEN|CV_BLUE|CV_BRIGHT: return 97;
2542 default: return color;
2547 tput_fmt(fmt, color, f_putc)
2552 char buf[INT_STRLEN_BOUND(int)+16];
2553 if (color == attrcolor)
2555 SNPRINTF1(buf, sizeof(buf), fmt, color);
2556 ltputs(buf, 1, f_putc);
2561 tput_color(str, f_putc)
2568 if (str != NULL && strcmp(str, "*") == 0)
2570 /* Special case: reset to normal */
2571 tput_fmt(ESCS"[m", -1, f_putc);
2574 switch (parse_color(str, &fg, &bg))
2578 tput_fmt(ESCS"[%dm", sgr_color(fg), f_putc);
2580 tput_fmt(ESCS"[%dm", sgr_color(bg)+10, f_putc);
2584 tput_fmt(ESCS"[38;5;%dm", fg, f_putc);
2586 tput_fmt(ESCS"[48;5;%dm", bg, f_putc);
2594 tput_inmode(mode_str, attr, attr_bit, f_putc)
2601 if ((attr & attr_bit) == 0)
2603 color_str = get_color_map(attr_bit);
2604 if (color_str == NULL || *color_str == '\0' || *color_str == '+')
2606 ltputs(mode_str, 1, f_putc);
2607 if (color_str == NULL || *color_str++ != '+')
2610 /* Color overrides mode string */
2611 tput_color(color_str, f_putc);
2615 tput_outmode(mode_str, attr_bit, f_putc)
2620 if ((attrmode & attr_bit) == 0)
2622 ltputs(mode_str, 1, f_putc);
2625 #else /* MSDOS_COMPILER */
2627 #if MSDOS_COMPILER==WIN32C
2629 WIN32put_fmt(fmt, color)
2633 char buf[INT_STRLEN_BOUND(int)+16];
2634 int len = SNPRINTF1(buf, sizeof(buf), fmt, color);
2635 WIN32textout(buf, len);
2647 char *str = get_color_map(attr);
2648 if (str == NULL || str[0] == '\0')
2650 switch (parse_color(str, &fg, &bg))
2653 if (fg >= 0 && bg >= 0)
2667 #if MSDOS_COMPILER==WIN32C
2672 out = WIN32put_fmt(ESCS"[38;5;%dm", fg);
2674 out = WIN32put_fmt(ESCS"[48;5;%dm", bg);
2684 #endif /* MSDOS_COMPILER */
2690 attr = apply_at_specials(attr);
2692 /* The one with the most priority is last. */
2693 tput_inmode(sc_u_in, attr, AT_UNDERLINE, putchr);
2694 tput_inmode(sc_b_in, attr, AT_BOLD, putchr);
2695 tput_inmode(sc_bl_in, attr, AT_BLINK, putchr);
2696 /* Don't use standout and color at the same time. */
2697 if (use_color && (attr & AT_COLOR))
2698 tput_color(get_color_map(attr), putchr);
2700 tput_inmode(sc_s_in, attr, AT_STANDOUT, putchr);
2703 /* The one with the most priority is first. */
2704 if ((attr & AT_COLOR) && use_color)
2706 win_set_color(attr);
2707 } else if (attr & AT_STANDOUT)
2709 SETCOLORS(so_fg_color, so_bg_color);
2710 } else if (attr & AT_BLINK)
2712 SETCOLORS(bl_fg_color, bl_bg_color);
2713 } else if (attr & AT_BOLD)
2715 SETCOLORS(bo_fg_color, bo_bg_color);
2716 } else if (attr & AT_UNDERLINE)
2718 SETCOLORS(ul_fg_color, ul_bg_color);
2728 /* Undo things in the reverse order we did them. */
2729 tput_color("*", putchr);
2730 tput_outmode(sc_s_out, AT_STANDOUT, putchr);
2731 tput_outmode(sc_bl_out, AT_BLINK, putchr);
2732 tput_outmode(sc_b_out, AT_BOLD, putchr);
2733 tput_outmode(sc_u_out, AT_UNDERLINE, putchr);
2736 SETCOLORS(nm_fg_color, nm_bg_color);
2738 attrmode = AT_NORMAL;
2745 int new_attrmode = apply_at_specials(attr);
2746 int ignore_modes = AT_ANSI;
2748 if ((new_attrmode & ~ignore_modes) != (attrmode & ~ignore_modes))
2756 is_at_equiv(attr1, attr2)
2760 attr1 = apply_at_specials(attr1);
2761 attr2 = apply_at_specials(attr2);
2763 return (attr1 == attr2);
2767 apply_at_specials(attr)
2770 if (attr & AT_BINARY)
2772 if (attr & AT_HILITE)
2773 attr |= AT_STANDOUT;
2774 attr &= ~(AT_BINARY|AT_HILITE);
2780 * Output a plain backspace, without erasing the previous char.
2790 ltputs(sc_backspace, 1, putchr);
2796 #if MSDOS_COMPILER==MSOFTC
2797 struct rccoord tpos;
2798 tpos = _gettextposition();
2802 #if MSDOS_COMPILER==BORLANDC || MSDOS_COMPILER==DJGPPC
2806 #if MSDOS_COMPILER==WIN32C
2807 CONSOLE_SCREEN_BUFFER_INFO scr;
2808 GetConsoleScreenBufferInfo(con_out, &scr);
2809 row = scr.dwCursorPosition.Y - scr.srWindow.Top + 1;
2810 col = scr.dwCursorPosition.X - scr.srWindow.Left + 1;
2817 _settextposition(row, col-1);
2818 #endif /* MSDOS_COMPILER */
2822 #if MSDOS_COMPILER==WIN32C
2824 * Determine whether an input character is waiting to be read.
2827 win32_kbhit(VOID_PARAM)
2835 currentKey.ascii = 0;
2836 currentKey.scan = 0;
2838 if (x11mouseCount > 0)
2840 currentKey.ascii = x11mousebuf[x11mousePos++];
2847 * Wait for a real key-down event, but
2848 * ignore SHIFT and CONTROL key events.
2852 PeekConsoleInputW(tty, &ip, 1, &read);
2855 ReadConsoleInputW(tty, &ip, 1, &read);
2856 /* generate an X11 mouse sequence from the mouse event */
2857 if (mousecap && ip.EventType == MOUSE_EVENT &&
2858 ip.Event.MouseEvent.dwEventFlags != MOUSE_MOVED)
2860 x11mousebuf[3] = X11MOUSE_OFFSET + ip.Event.MouseEvent.dwMousePosition.X + 1;
2861 x11mousebuf[4] = X11MOUSE_OFFSET + ip.Event.MouseEvent.dwMousePosition.Y + 1;
2862 switch (ip.Event.MouseEvent.dwEventFlags)
2864 case 0: /* press or release */
2865 if (ip.Event.MouseEvent.dwButtonState == 0)
2866 x11mousebuf[2] = X11MOUSE_OFFSET + X11MOUSE_BUTTON_REL;
2867 else if (ip.Event.MouseEvent.dwButtonState & (FROM_LEFT_3RD_BUTTON_PRESSED | FROM_LEFT_4TH_BUTTON_PRESSED))
2870 x11mousebuf[2] = X11MOUSE_OFFSET + X11MOUSE_BUTTON1 + ((int)ip.Event.MouseEvent.dwButtonState << 1);
2873 x11mousebuf[2] = X11MOUSE_OFFSET + (((int)ip.Event.MouseEvent.dwButtonState < 0) ? X11MOUSE_WHEEL_DOWN : X11MOUSE_WHEEL_UP);
2880 currentKey.ascii = ESC;
2884 } while (ip.EventType != KEY_EVENT ||
2885 ip.Event.KeyEvent.bKeyDown != TRUE ||
2886 (ip.Event.KeyEvent.wVirtualScanCode == 0 && ip.Event.KeyEvent.uChar.UnicodeChar == 0) ||
2887 ip.Event.KeyEvent.wVirtualKeyCode == VK_KANJI ||
2888 ip.Event.KeyEvent.wVirtualKeyCode == VK_SHIFT ||
2889 ip.Event.KeyEvent.wVirtualKeyCode == VK_CONTROL ||
2890 ip.Event.KeyEvent.wVirtualKeyCode == VK_MENU);
2892 currentKey.unicode = ip.Event.KeyEvent.uChar.UnicodeChar;
2893 currentKey.ascii = ip.Event.KeyEvent.uChar.AsciiChar;
2894 currentKey.scan = ip.Event.KeyEvent.wVirtualScanCode;
2895 keyCount = ip.Event.KeyEvent.wRepeatCount;
2897 if (ip.Event.KeyEvent.dwControlKeyState &
2898 (LEFT_ALT_PRESSED | RIGHT_ALT_PRESSED))
2900 switch (currentKey.scan)
2902 case PCK_ALT_E: /* letter 'E' */
2903 currentKey.ascii = 0;
2906 } else if (ip.Event.KeyEvent.dwControlKeyState &
2907 (LEFT_CTRL_PRESSED | RIGHT_CTRL_PRESSED))
2909 switch (currentKey.scan)
2911 case PCK_RIGHT: /* right arrow */
2912 currentKey.scan = PCK_CTL_RIGHT;
2914 case PCK_LEFT: /* left arrow */
2915 currentKey.scan = PCK_CTL_LEFT;
2917 case PCK_DELETE: /* delete */
2918 currentKey.scan = PCK_CTL_DELETE;
2921 } else if (ip.Event.KeyEvent.dwControlKeyState & SHIFT_PRESSED)
2923 switch (currentKey.scan)
2925 case PCK_SHIFT_TAB: /* tab */
2926 currentKey.ascii = 0;
2935 * Read a character from the keyboard.
2938 WIN32getch(VOID_PARAM)
2941 static unsigned char utf8[UTF8_MAX_LENGTH];
2942 static int utf8_size = 0;
2943 static int utf8_next_byte = 0;
2945 // Return the rest of multibyte character from the prior call
2946 if (utf8_next_byte < utf8_size)
2948 ascii = utf8[utf8_next_byte++];
2953 if (pending_scancode)
2955 pending_scancode = 0;
2956 return ((char)(currentKey.scan & 0x00FF));
2960 while (win32_kbhit() == FALSE)
2968 // If multibyte character, return its first byte
2969 if (currentKey.ascii != currentKey.unicode)
2971 utf8_size = WideCharToMultiByte(CP_UTF8, 0, ¤tKey.unicode, 1, &utf8, sizeof(utf8), NULL, NULL);
2972 if (utf8_size == 0 )
2977 ascii = currentKey.ascii;
2979 * On PC's, the extended keys return a 2 byte sequence beginning
2980 * with '00', so if the ascii code is 00, the next byte will be
2981 * the lsb of the scan code.
2983 pending_scancode = (ascii == 0x00);
2984 } while (pending_scancode &&
2985 (currentKey.scan == PCK_CAPS_LOCK || currentKey.scan == PCK_NUM_LOCK));
2995 WIN32setcolors(fg, bg)
3005 WIN32textout(text, len)
3009 #if MSDOS_COMPILER==WIN32C
3014 * We've got UTF-8 text in a non-UTF-8 console. Convert it to
3015 * wide and use WriteConsoleW.
3018 len = MultiByteToWideChar(CP_UTF8, 0, text, len, wtext,
3019 sizeof(wtext)/sizeof(*wtext));
3020 WriteConsoleW(con_out, wtext, len, &written, NULL);
3022 WriteConsole(con_out, text, len, &written, NULL);