2 * Copyright (C) 1984-2021 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
137 static int keyCount = 0;
138 static WORD curr_attr;
139 static int pending_scancode = 0;
140 static char x11mousebuf[] = "[M???"; /* Mouse report, after ESC */
141 static int x11mousePos, x11mouseCount;
143 static HANDLE con_out_save = INVALID_HANDLE_VALUE; /* previous console */
144 static HANDLE con_out_ours = INVALID_HANDLE_VALUE; /* our own */
145 HANDLE con_out = INVALID_HANDLE_VALUE; /* current console */
149 static void win32_init_term();
150 static void win32_deinit_term();
152 #ifndef ENABLE_VIRTUAL_TERMINAL_PROCESSING
153 #define ENABLE_VIRTUAL_TERMINAL_PROCESSING 4
156 #define FG_COLORS (FOREGROUND_RED | FOREGROUND_GREEN | FOREGROUND_BLUE | FOREGROUND_INTENSITY)
157 #define BG_COLORS (BACKGROUND_RED | BACKGROUND_GREEN | BACKGROUND_BLUE | BACKGROUND_INTENSITY)
158 #define MAKEATTR(fg,bg) ((WORD)((fg)|((bg)<<4)))
159 #define APPLY_COLORS() { if (SetConsoleTextAttribute(con_out, curr_attr) == 0) \
160 error("SETCOLORS failed", NULL_PARG); }
161 #define SET_FG_COLOR(fg) { curr_attr |= (fg); APPLY_COLORS(); }
162 #define SET_BG_COLOR(bg) { curr_attr |= ((bg)<<4); APPLY_COLORS(); }
163 #define SETCOLORS(fg,bg) { curr_attr = MAKEATTR(fg,bg); APPLY_COLORS(); }
167 public int nm_fg_color; /* Color of normal text */
168 public int nm_bg_color;
169 public int bo_fg_color; /* Color of bold text */
170 public int bo_bg_color;
171 public int ul_fg_color; /* Color of underlined text */
172 public int ul_bg_color;
173 public int so_fg_color; /* Color of standout text */
174 public int so_bg_color;
175 public int bl_fg_color; /* Color of blinking text */
176 public int bl_bg_color;
177 static int sy_fg_color; /* Color of system text (before less) */
178 static int sy_bg_color;
179 public int sgr_mode; /* Honor ANSI sequences rather than using above */
180 #if MSDOS_COMPILER==WIN32C
181 static DWORD init_output_mode; /* The initial console output mode */
182 public int vt_enabled = -1; /* Is virtual terminal processing available? */
187 * Strings passed to tputs() to do various terminal functions.
190 *sc_pad, /* Pad string */
191 *sc_home, /* Cursor home */
192 *sc_addline, /* Add line, scroll down following lines */
193 *sc_lower_left, /* Cursor to last line, first column */
194 *sc_return, /* Cursor to beginning of current line */
195 *sc_move, /* General cursor positioning */
196 *sc_clear, /* Clear screen */
197 *sc_eol_clear, /* Clear to end of line */
198 *sc_eos_clear, /* Clear to end of screen */
199 *sc_s_in, /* Enter standout (highlighted) mode */
200 *sc_s_out, /* Exit standout mode */
201 *sc_u_in, /* Enter underline mode */
202 *sc_u_out, /* Exit underline mode */
203 *sc_b_in, /* Enter bold mode */
204 *sc_b_out, /* Exit bold mode */
205 *sc_bl_in, /* Enter blink mode */
206 *sc_bl_out, /* Exit blink mode */
207 *sc_visual_bell, /* Visual bell (flash screen) sequence */
208 *sc_backspace, /* Backspace cursor */
209 *sc_s_keypad, /* Start keypad mode */
210 *sc_e_keypad, /* End keypad mode */
211 *sc_s_mousecap, /* Start mouse capture mode */
212 *sc_e_mousecap, /* End mouse capture mode */
213 *sc_init, /* Startup terminal initialization */
214 *sc_deinit; /* Exit terminal de-initialization */
216 static int attrcolor = -1;
219 static int init_done = 0;
221 public int auto_wrap; /* Terminal does \r\n when write past margin */
222 public int ignaw; /* Terminal ignores \n immediately after wrap */
223 public int erase_char; /* The user's erase char */
224 public int erase2_char; /* The user's other erase char */
225 public int kill_char; /* The user's line-kill char */
226 public int werase_char; /* The user's word-erase char */
227 public int sc_width, sc_height; /* Height & width of screen */
228 public int bo_s_width, bo_e_width; /* Printing width of boldface seq */
229 public int ul_s_width, ul_e_width; /* Printing width of underline seq */
230 public int so_s_width, so_e_width; /* Printing width of standout seq */
231 public int bl_s_width, bl_e_width; /* Printing width of blink seq */
232 public int above_mem, below_mem; /* Memory retained above/below screen */
233 public int can_goto_line; /* Can move cursor to any line */
234 public int clear_bg; /* Clear fills with background color */
235 public int missing_cap = 0; /* Some capability is missing */
236 public char *kent = NULL; /* Keypad ENTER sequence */
238 static int attrmode = AT_NORMAL;
239 static int termcap_debug = -1;
241 extern int one_screen;
243 extern char *ttyin_name;
247 static char *cheaper LESSPARAMS((char *t1, char *t2, char *def));
248 static void tmodes LESSPARAMS((char *incap, char *outcap, char **instr,
249 char **outstr, char *def_instr, char *def_outstr, char **spp));
253 * These two variables are sometimes defined in,
254 * and needed by, the termcap library.
256 #if MUST_DEFINE_OSPEED
257 extern short ospeed; /* Terminal output baud rate */
258 extern char PC; /* Pad character */
265 extern int quiet; /* If VERY_QUIET, use visual bell for bell */
266 extern int no_back_scroll;
269 extern int no_keypad;
272 extern int screen_trashed;
273 extern int top_scroll;
274 extern int quit_if_one_screen;
278 extern int use_color;
280 extern int hilite_search;
282 #if MSDOS_COMPILER==WIN32C
284 extern DWORD console_mode;
285 #ifndef ENABLE_EXTENDED_FLAGS
286 #define ENABLE_EXTENDED_FLAGS 0x80
287 #define ENABLE_QUICK_EDIT_MODE 0x40
293 extern char *tgetstr();
294 extern char *tgoto();
298 * Change terminal to "raw mode", or restore to "normal" mode.
300 * 1. An outstanding read will complete on receipt of a single keystroke.
301 * 2. Input is not echoed.
302 * 3. On output, \n is mapped to \r\n.
303 * 4. \t is NOT expanded into spaces.
304 * 5. Signal-causing characters such as ctrl-C (interrupt),
305 * etc. are NOT disabled.
306 * It doesn't matter whether an input \n is mapped to \r, or vice versa.
312 static int curr_on = 0;
316 erase2_char = '\b'; /* in case OS doesn't know about erase2 */
317 #if HAVE_TERMIOS_H && HAVE_TERMIOS_FUNCS
320 static struct termios save_term;
321 static int saved_term = 0;
326 * Get terminal modes.
331 * Save modes and set certain variables dependent on modes.
339 switch (cfgetospeed(&s))
342 case B0: ospeed = 0; break;
345 case B50: ospeed = 1; break;
348 case B75: ospeed = 2; break;
351 case B110: ospeed = 3; break;
354 case B134: ospeed = 4; break;
357 case B150: ospeed = 5; break;
360 case B200: ospeed = 6; break;
363 case B300: ospeed = 7; break;
366 case B600: ospeed = 8; break;
369 case B1200: ospeed = 9; break;
372 case B1800: ospeed = 10; break;
375 case B2400: ospeed = 11; break;
378 case B4800: ospeed = 12; break;
381 case B9600: ospeed = 13; break;
384 case EXTA: ospeed = 14; break;
387 case EXTB: ospeed = 15; break;
390 case B57600: ospeed = 16; break;
393 case B115200: ospeed = 17; break;
398 erase_char = s.c_cc[VERASE];
400 erase2_char = s.c_cc[VERASE2];
402 kill_char = s.c_cc[VKILL];
404 werase_char = s.c_cc[VWERASE];
406 werase_char = CONTROL('W');
410 * Set the modes to the way we want them.
472 #if MUST_SET_LINE_DISCIPLINE
474 * System's termios is broken; need to explicitly
475 * request TERMIODISC line discipline.
477 s.c_line = TERMIODISC;
482 * Restore saved modes.
489 tcsetattr(tty, TCSADRAIN, &s);
490 #if MUST_SET_LINE_DISCIPLINE
494 * Broken termios *ignores* any line discipline
495 * except TERMIODISC. A different old line discipline
496 * is therefore not restored, yet. Restore the old
497 * line discipline by hand.
499 ioctl(tty, TIOCSETD, &save_term.c_line);
507 static struct termio save_term;
508 static int saved_term = 0;
513 * Get terminal modes.
515 ioctl(tty, TCGETA, &s);
518 * Save modes and set certain variables dependent on modes.
526 ospeed = s.c_cflag & CBAUD;
528 erase_char = s.c_cc[VERASE];
529 kill_char = s.c_cc[VKILL];
531 werase_char = s.c_cc[VWERASE];
533 werase_char = CONTROL('W');
537 * Set the modes to the way we want them.
539 s.c_lflag &= ~(ICANON|ECHO|ECHOE|ECHOK|ECHONL);
540 s.c_oflag |= (OPOST|ONLCR|TAB3);
541 s.c_oflag &= ~(OCRNL|ONOCR|ONLRET);
547 * Restore saved modes.
551 ioctl(tty, TCSETAW, &s);
557 static struct sgttyb save_term;
558 static int saved_term = 0;
563 * Get terminal modes.
565 ioctl(tty, TIOCGETP, &s);
568 * Save modes and set certain variables dependent on modes.
576 ospeed = s.sg_ospeed;
578 erase_char = s.sg_erase;
579 kill_char = s.sg_kill;
580 werase_char = CONTROL('W');
583 * Set the modes to the way we want them.
585 s.sg_flags |= CBREAK;
586 s.sg_flags &= ~(ECHO|XTABS);
590 * Restore saved modes.
594 ioctl(tty, TIOCSETN, &s);
600 static struct sgbuf save_term;
601 static int saved_term = 0;
606 * Get terminal modes.
611 * Save modes and set certain variables dependent on modes.
618 erase_char = s.sg_bspch;
619 kill_char = s.sg_dlnch;
620 werase_char = CONTROL('W');
623 * Set the modes to the way we want them.
632 * Restore saved modes.
639 /* MS-DOS, Windows, or OS2 */
642 LSIGNAL(SIGINT, SIG_IGN);
645 #if MSDOS_COMPILER==DJGPPC
646 kill_char = CONTROL('U');
648 * So that when we shell out or run another program, its
649 * stdin is in cooked mode. We do not switch stdin to binary
650 * mode if fd0 is zero, since that means we were called before
651 * tty was reopened in open_getchr, in which case we would be
652 * changing the original stdin device outside less.
655 setmode(0, on ? O_BINARY : O_TEXT);
659 werase_char = CONTROL('W');
669 * Some glue to prevent calling termcap functions if tgetent() failed.
681 struct env { struct env *next; char *name; char *value; };
682 static struct env *envs = NULL;
684 for (p = envs; p != NULL; p = p->next)
685 if (strcmp(p->name, capname) == 0)
687 p = (struct env *) ecalloc(1, sizeof(struct env));
688 p->name = save(capname);
689 p->value = (char *) ecalloc(strlen(capname)+3, sizeof(char));
690 sprintf(p->value, "<%s>", capname);
695 SNPRINTF1(name, sizeof(name), "LESS_TERMCAP_%s", capname);
696 return (lgetenv(name));
705 if ((s = ltget_env(capname)) != NULL)
706 return (*s != '\0' && *s != '0');
709 return (tgetflag(capname));
718 if ((s = ltget_env(capname)) != NULL)
722 return (tgetnum(capname));
726 ltgetstr(capname, pp)
732 if ((s = ltget_env(capname)) != NULL)
736 return (tgetstr(capname, pp));
738 #endif /* MSDOS_COMPILER */
741 * Get size of the output screen.
753 #define DEF_SC_WIDTH 80
755 #define DEF_SC_HEIGHT 25
757 #define DEF_SC_HEIGHT 24
761 sys_width = sys_height = 0;
763 #if MSDOS_COMPILER==MSOFTC
765 struct videoconfig w;
767 sys_height = w.numtextrows;
768 sys_width = w.numtextcols;
771 #if MSDOS_COMPILER==BORLANDC || MSDOS_COMPILER==DJGPPC
775 sys_height = w.screenheight;
776 sys_width = w.screenwidth;
779 #if MSDOS_COMPILER==WIN32C
781 CONSOLE_SCREEN_BUFFER_INFO scr;
782 GetConsoleScreenBufferInfo(con_out, &scr);
783 sys_height = scr.srWindow.Bottom - scr.srWindow.Top + 1;
784 sys_width = scr.srWindow.Right - scr.srWindow.Left + 1;
794 * When using terminal emulators for XFree86/OS2, the
795 * _scrsize function does not work well.
796 * Call the scrsize.exe program to get the window size.
798 windowid = getenv("WINDOWID");
799 if (windowid != NULL)
801 FILE *fd = popen("scrsize", "rt");
805 fscanf(fd, "%i %i", &w, &h);
819 if (ioctl(2, TIOCGWINSZ, &w) == 0)
822 sys_height = w.ws_row;
824 sys_width = w.ws_col;
831 if (ioctl(2, WIOCGETD, &w) == 0)
834 sys_height = w.uw_height / w.uw_vs;
836 sys_width = w.uw_width / w.uw_hs;
847 sc_height = sys_height;
848 else if ((s = lgetenv("LINES")) != NULL)
851 else if ((n = ltgetnum("li")) > 0)
855 sc_height = DEF_SC_HEIGHT;
858 sc_width = sys_width;
859 else if ((s = lgetenv("COLUMNS")) != NULL)
862 else if ((n = ltgetnum("co")) > 0)
866 sc_width = DEF_SC_WIDTH;
869 #if MSDOS_COMPILER==MSOFTC
871 * Figure out how many empty loops it takes to delay a millisecond.
874 get_clock(VOID_PARAM)
879 * Get synchronized at the start of a tick.
882 while (clock() == start)
885 * Now count loops till the next tick.
889 while (clock() == start)
892 * Convert from (loops per clock) to (loops per millisecond).
894 msec_loops *= CLOCKS_PER_SEC;
899 * Delay for a specified number of milliseconds.
909 for (i = 0; i < msec_loops; i++)
916 * Return the characters actually input by a "special" key.
922 static char tbuf[40];
924 #if MSDOS_COMPILER || OS2
925 static char k_right[] = { '\340', PCK_RIGHT, 0 };
926 static char k_left[] = { '\340', PCK_LEFT, 0 };
927 static char k_ctl_right[] = { '\340', PCK_CTL_RIGHT, 0 };
928 static char k_ctl_left[] = { '\340', PCK_CTL_LEFT, 0 };
929 static char k_insert[] = { '\340', PCK_INSERT, 0 };
930 static char k_delete[] = { '\340', PCK_DELETE, 0 };
931 static char k_ctl_delete[] = { '\340', PCK_CTL_DELETE, 0 };
932 static char k_ctl_backspace[] = { '\177', 0 };
933 static char k_home[] = { '\340', PCK_HOME, 0 };
934 static char k_end[] = { '\340', PCK_END, 0 };
935 static char k_up[] = { '\340', PCK_UP, 0 };
936 static char k_down[] = { '\340', PCK_DOWN, 0 };
937 static char k_backtab[] = { '\340', PCK_SHIFT_TAB, 0 };
938 static char k_pagedown[] = { '\340', PCK_PAGEDOWN, 0 };
939 static char k_pageup[] = { '\340', PCK_PAGEUP, 0 };
940 static char k_f1[] = { '\340', PCK_F1, 0 };
950 * If windowid is not NULL, assume less is executed in
951 * the XFree86 environment.
954 s = windowid ? ltgetstr("kr", &sp) : k_right;
957 s = windowid ? ltgetstr("kl", &sp) : k_left;
960 s = windowid ? ltgetstr("ku", &sp) : k_up;
963 s = windowid ? ltgetstr("kd", &sp) : k_down;
966 s = windowid ? ltgetstr("kP", &sp) : k_pageup;
969 s = windowid ? ltgetstr("kN", &sp) : k_pagedown;
972 s = windowid ? ltgetstr("kh", &sp) : k_home;
975 s = windowid ? ltgetstr("@7", &sp) : k_end;
978 s = windowid ? ltgetstr("kD", &sp) : k_delete;
1016 #if MSDOS_COMPILER || OS2
1020 case SK_CTL_LEFT_ARROW:
1023 case SK_CTL_RIGHT_ARROW:
1026 case SK_CTL_BACKSPACE:
1027 s = k_ctl_backspace;
1039 case SK_RIGHT_ARROW:
1040 s = ltgetstr("kr", &sp);
1043 s = ltgetstr("kl", &sp);
1046 s = ltgetstr("ku", &sp);
1049 s = ltgetstr("kd", &sp);
1052 s = ltgetstr("kP", &sp);
1055 s = ltgetstr("kN", &sp);
1058 s = ltgetstr("kh", &sp);
1061 s = ltgetstr("@7", &sp);
1064 s = ltgetstr("kD", &sp);
1074 tbuf[0] = CONTROL('K');
1085 * Get terminal capabilities via termcap.
1088 get_term(VOID_PARAM)
1090 termcap_debug = !isnullenv(lgetenv("LESS_TERMCAP_DEBUG"));
1097 * Set up default colors.
1098 * The xx_s_width and xx_e_width vars are already initialized to 0.
1100 #if MSDOS_COMPILER==MSOFTC
1101 sy_bg_color = _getbkcolor();
1102 sy_fg_color = _gettextcolor();
1105 #if MSDOS_COMPILER==BORLANDC || MSDOS_COMPILER==DJGPPC
1109 sy_bg_color = (w.attribute >> 4) & 0x0F;
1110 sy_fg_color = (w.attribute >> 0) & 0x0F;
1113 #if MSDOS_COMPILER==WIN32C
1115 CONSOLE_SCREEN_BUFFER_INFO scr;
1117 con_out_save = con_out = GetStdHandle(STD_OUTPUT_HANDLE);
1119 * Always open stdin in binary. Note this *must* be done
1120 * before any file operations have been done on fd0.
1123 GetConsoleMode(con_out, &init_output_mode);
1124 GetConsoleScreenBufferInfo(con_out, &scr);
1125 curr_attr = scr.wAttributes;
1126 sy_bg_color = (curr_attr & BG_COLORS) >> 4; /* normalize */
1127 sy_fg_color = curr_attr & FG_COLORS;
1132 nm_fg_color = sy_fg_color;
1133 nm_bg_color = sy_bg_color;
1145 * Get size of the screen.
1151 #else /* !MSDOS_COMPILER */
1157 * Some termcap libraries assume termbuf is static
1158 * (accessible after tgetent returns).
1160 static char termbuf[TERMBUF_SIZE];
1161 static char sbuf[TERMSBUF_SIZE];
1165 * Make sure the termcap database is available.
1167 sp = lgetenv("TERMCAP");
1171 if ((sp = homefile("termcap.dat")) != NULL)
1173 termcap = (char *) ecalloc(strlen(sp)+9, sizeof(char));
1174 sprintf(termcap, "TERMCAP=%s", sp);
1181 * Find out what kind of terminal this is.
1183 if ((term = lgetenv("TERM")) == NULL)
1184 term = DEFAULT_TERM;
1186 /* {{ Should probably just pass NULL instead of termbuf. }} */
1187 if (tgetent(termbuf, term) != TGETENT_OK)
1189 if (ltgetflag("hc"))
1193 * Get size of the screen.
1198 auto_wrap = ltgetflag("am");
1199 ignaw = ltgetflag("xn");
1200 above_mem = ltgetflag("da");
1201 below_mem = ltgetflag("db");
1202 clear_bg = ltgetflag("ut");
1205 * Assumes termcap variable "sg" is the printing width of:
1206 * the standout sequence, the end standout sequence,
1207 * the underline sequence, the end underline sequence,
1208 * the boldface sequence, and the end boldface sequence.
1210 if ((so_s_width = ltgetnum("sg")) < 0)
1212 so_e_width = so_s_width;
1214 bo_s_width = bo_e_width = so_s_width;
1215 ul_s_width = ul_e_width = so_s_width;
1216 bl_s_width = bl_e_width = so_s_width;
1219 if (so_s_width > 0 || so_e_width > 0)
1221 * Disable highlighting by default on magic cookie terminals.
1222 * Turning on highlighting might change the displayed width
1223 * of a line, causing the display to get messed up.
1224 * The user can turn it back on with -g,
1225 * but she won't like the results.
1231 * Get various string-valued capabilities.
1236 sc_pad = ltgetstr("pc", &sp);
1241 sc_s_keypad = ltgetstr("ks", &sp);
1242 if (sc_s_keypad == NULL)
1244 sc_e_keypad = ltgetstr("ke", &sp);
1245 if (sc_e_keypad == NULL)
1247 kent = ltgetstr("@8", &sp);
1249 sc_s_mousecap = ltgetstr("MOUSE_START", &sp);
1250 if (sc_s_mousecap == NULL)
1251 sc_s_mousecap = ESCS "[?1000h" ESCS "[?1006h";
1252 sc_e_mousecap = ltgetstr("MOUSE_END", &sp);
1253 if (sc_e_mousecap == NULL)
1254 sc_e_mousecap = ESCS "[?1006l" ESCS "[?1000l";
1256 sc_init = ltgetstr("ti", &sp);
1257 if (sc_init == NULL)
1260 sc_deinit= ltgetstr("te", &sp);
1261 if (sc_deinit == NULL)
1264 sc_eol_clear = ltgetstr("ce", &sp);
1265 if (sc_eol_clear == NULL || *sc_eol_clear == '\0')
1271 sc_eos_clear = ltgetstr("cd", &sp);
1272 if (below_mem && (sc_eos_clear == NULL || *sc_eos_clear == '\0'))
1278 sc_clear = ltgetstr("cl", &sp);
1279 if (sc_clear == NULL || *sc_clear == '\0')
1285 sc_move = ltgetstr("cm", &sp);
1286 if (sc_move == NULL || *sc_move == '\0')
1289 * This is not an error here, because we don't
1290 * always need sc_move.
1291 * We need it only if we don't have home or lower-left.
1298 tmodes("so", "se", &sc_s_in, &sc_s_out, "", "", &sp);
1299 tmodes("us", "ue", &sc_u_in, &sc_u_out, sc_s_in, sc_s_out, &sp);
1300 tmodes("md", "me", &sc_b_in, &sc_b_out, sc_s_in, sc_s_out, &sp);
1301 tmodes("mb", "me", &sc_bl_in, &sc_bl_out, sc_s_in, sc_s_out, &sp);
1303 sc_visual_bell = ltgetstr("vb", &sp);
1304 if (sc_visual_bell == NULL)
1305 sc_visual_bell = "";
1307 if (ltgetflag("bs"))
1308 sc_backspace = "\b";
1311 sc_backspace = ltgetstr("bc", &sp);
1312 if (sc_backspace == NULL || *sc_backspace == '\0')
1313 sc_backspace = "\b";
1317 * Choose between using "ho" and "cm" ("home" and "cursor move")
1318 * to move the cursor to the upper left corner of the screen.
1320 t1 = ltgetstr("ho", &sp);
1323 if (*sc_move == '\0')
1327 strcpy(sp, tgoto(sc_move, 0, 0));
1329 sp += strlen(sp) + 1;
1331 sc_home = cheaper(t1, t2, "|\b^");
1334 * Choose between using "ll" and "cm" ("lower left" and "cursor move")
1335 * to move the cursor to the lower left corner of the screen.
1337 t1 = ltgetstr("ll", &sp);
1340 if (*sc_move == '\0')
1344 strcpy(sp, tgoto(sc_move, 0, sc_height-1));
1346 sp += strlen(sp) + 1;
1348 sc_lower_left = cheaper(t1, t2, "\r");
1351 * Get carriage return string.
1353 sc_return = ltgetstr("cr", &sp);
1354 if (sc_return == NULL)
1358 * Choose between using "al" or "sr" ("add line" or "scroll reverse")
1359 * to add a line at the top of the screen.
1361 t1 = ltgetstr("al", &sp);
1364 t2 = ltgetstr("sr", &sp);
1368 if (*t1 == '\0' && *t2 == '\0')
1375 sc_addline = cheaper(t1, t2, "");
1376 if (*sc_addline == '\0')
1379 * Force repaint on any backward movement.
1384 #endif /* MSDOS_COMPILER */
1389 * Return the cost of displaying a termcap string.
1390 * We use the trick of calling tputs, but as a char printing function
1391 * we give it inc_costcount, which just increments "costcount".
1392 * This tells us how many chars would be printed by using this string.
1393 * {{ Couldn't we just use strlen? }}
1395 static int costcount;
1411 tputs(t, sc_height, inc_costcount);
1416 * Return the "best" of the two given termcap strings.
1417 * The best, if both exist, is the one with the lower
1418 * cost (see cost() function).
1421 cheaper(t1, t2, def)
1425 if (*t1 == '\0' && *t2 == '\0')
1434 if (cost(t1) < cost(t2))
1440 tmodes(incap, outcap, instr, outstr, def_instr, def_outstr, spp)
1449 *instr = ltgetstr(incap, spp);
1454 *outstr = def_outstr;
1458 *outstr = ltgetstr(outcap, spp);
1459 if (*outstr == NULL)
1460 /* No specific out capability; use "me". */
1461 *outstr = ltgetstr("me", spp);
1462 if (*outstr == NULL)
1463 /* Don't even have "me"; use a null string. */
1467 #endif /* MSDOS_COMPILER */
1471 * Below are the functions which perform all the
1472 * terminal-specific screen manipulation.
1478 #if MSDOS_COMPILER==WIN32C
1480 _settextposition(int row, int col)
1483 CONSOLE_SCREEN_BUFFER_INFO csbi;
1485 GetConsoleScreenBufferInfo(con_out, &csbi);
1486 cpos.X = csbi.srWindow.Left + (col - 1);
1487 cpos.Y = csbi.srWindow.Top + (row - 1);
1488 SetConsoleCursorPosition(con_out, cpos);
1493 * Initialize the screen to the correct color at startup.
1496 initcolor(VOID_PARAM)
1498 #if MSDOS_COMPILER==BORLANDC || MSDOS_COMPILER==DJGPPC
1501 SETCOLORS(nm_fg_color, nm_bg_color);
1504 * This clears the screen at startup. This is different from
1505 * the behavior of other versions of less. Disable it for now.
1512 * Create a complete, blank screen using "normal" colors.
1514 SETCOLORS(nm_fg_color, nm_bg_color);
1515 blanks = (char *) ecalloc(width+1, sizeof(char));
1516 for (col = 0; col < sc_width; col++)
1518 blanks[sc_width] = '\0';
1519 for (row = 0; row < sc_height; row++)
1526 #if MSDOS_COMPILER==WIN32C
1529 * Enable virtual terminal processing, if available.
1532 win32_init_vt_term(VOID_PARAM)
1536 if (vt_enabled == 0 || (vt_enabled == 1 && con_out == con_out_ours))
1539 GetConsoleMode(con_out, &output_mode);
1540 vt_enabled = SetConsoleMode(con_out,
1541 output_mode | ENABLE_VIRTUAL_TERMINAL_PROCESSING);
1550 win32_deinit_vt_term(VOID_PARAM)
1552 if (vt_enabled == 1 && con_out == con_out_save)
1553 SetConsoleMode(con_out, init_output_mode);
1557 * Termcap-like init with a private win32 console.
1560 win32_init_term(VOID_PARAM)
1562 CONSOLE_SCREEN_BUFFER_INFO scr;
1565 if (con_out_save == INVALID_HANDLE_VALUE)
1568 GetConsoleScreenBufferInfo(con_out_save, &scr);
1570 if (con_out_ours == INVALID_HANDLE_VALUE)
1573 * Create our own screen buffer, so that we
1574 * may restore the original when done.
1576 con_out_ours = CreateConsoleScreenBuffer(
1577 GENERIC_WRITE | GENERIC_READ,
1578 FILE_SHARE_WRITE | FILE_SHARE_READ,
1579 (LPSECURITY_ATTRIBUTES) NULL,
1580 CONSOLE_TEXTMODE_BUFFER,
1584 size.X = scr.srWindow.Right - scr.srWindow.Left + 1;
1585 size.Y = scr.srWindow.Bottom - scr.srWindow.Top + 1;
1586 SetConsoleScreenBufferSize(con_out_ours, size);
1587 SetConsoleActiveScreenBuffer(con_out_ours);
1588 con_out = con_out_ours;
1592 * Restore the startup console.
1595 win32_deinit_term(VOID_PARAM)
1597 if (con_out_save == INVALID_HANDLE_VALUE)
1600 (void) CloseHandle(con_out_ours);
1601 SetConsoleActiveScreenBuffer(con_out_save);
1602 con_out = con_out_save;
1609 do_tputs(str, affcnt, f_putc)
1615 if (ttyin_name != NULL)
1619 tputs(str, affcnt, f_putc);
1623 * Like tputs but we handle $<...> delay strings here because
1624 * some implementations of tputs don't perform delays correctly.
1627 ltputs(str, affcnt, f_putc)
1632 while (str != NULL && *str != '\0')
1635 char *obrac = strstr(str, "$<");
1639 int slen = obrac - str;
1640 if (slen < sizeof(str2))
1643 /* Output first part of string (before "$<"). */
1644 memcpy(str2, str, slen);
1646 do_tputs(str2, affcnt, f_putc);
1648 /* Perform the delay. */
1649 delay = lstrtoi(str, &str);
1654 /* Skip past closing ">" at end of delay string. */
1655 str = strstr(str, ">");
1662 /* Pass the rest of the string to tputs and we're done. */
1663 do_tputs(str, affcnt, f_putc);
1667 #endif /* MSDOS_COMPILER */
1670 * Configure the termimal so mouse clicks and wheel moves
1671 * produce input to less.
1674 init_mouse(VOID_PARAM)
1677 ltputs(sc_s_mousecap, sc_height, putchr);
1679 #if MSDOS_COMPILER==WIN32C
1680 SetConsoleMode(tty, ENABLE_PROCESSED_INPUT | ENABLE_MOUSE_INPUT
1681 | ENABLE_EXTENDED_FLAGS /* disable quick edit */);
1688 * Configure the terminal so mouse clicks and wheel moves
1689 * are handled by the system (so text can be selected, etc).
1692 deinit_mouse(VOID_PARAM)
1695 ltputs(sc_e_mousecap, sc_height, putchr);
1697 #if MSDOS_COMPILER==WIN32C
1698 SetConsoleMode(tty, ENABLE_PROCESSED_INPUT | ENABLE_EXTENDED_FLAGS
1699 | (console_mode & ENABLE_QUICK_EDIT_MODE));
1705 * Initialize terminal
1710 clear_bot_if_needed();
1712 if (!(quit_if_one_screen && one_screen))
1715 ltputs(sc_init, sc_height, putchr);
1717 ltputs(sc_s_keypad, sc_height, putchr);
1727 * This is nice to terminals with no alternate screen,
1728 * but with saved scrolled-off-the-top lines. This way,
1729 * no previous line is lost, but we start with a whole
1730 * screen to ourself.
1732 for (i = 1; i < sc_height; i++)
1737 #if MSDOS_COMPILER==WIN32C
1738 if (!(quit_if_one_screen && one_screen))
1746 win32_init_vt_term();
1755 * Deinitialize terminal
1763 if (!(quit_if_one_screen && one_screen))
1768 ltputs(sc_e_keypad, sc_height, putchr);
1770 ltputs(sc_deinit, sc_height, putchr);
1773 /* Restore system colors. */
1774 SETCOLORS(sy_fg_color, sy_bg_color);
1775 #if MSDOS_COMPILER==WIN32C
1776 win32_deinit_vt_term();
1777 if (!(quit_if_one_screen && one_screen))
1782 win32_deinit_term();
1785 /* Need clreol to make SETCOLORS take effect. */
1793 * Are we interactive (ie. writing to an initialized tty)?
1796 interactive(VOID_PARAM)
1798 return (is_tty && init_done);
1802 assert_interactive(VOID_PARAM)
1804 if (interactive()) return;
1809 * Home cursor (move to upper left corner of screen).
1814 assert_interactive();
1816 ltputs(sc_home, 1, putchr);
1819 _settextposition(1,1);
1824 * Add a blank line (called with cursor at home).
1825 * Should scroll the display down.
1828 add_line(VOID_PARAM)
1830 assert_interactive();
1832 ltputs(sc_addline, sc_height, putchr);
1835 #if MSDOS_COMPILER==MSOFTC
1836 _scrolltextwindow(_GSCROLLDOWN);
1837 _settextposition(1,1);
1839 #if MSDOS_COMPILER==BORLANDC || MSDOS_COMPILER==DJGPPC
1840 movetext(1,1, sc_width,sc_height-1, 1,2);
1844 #if MSDOS_COMPILER==WIN32C
1847 SMALL_RECT rcSrc, rcClip;
1849 CONSOLE_SCREEN_BUFFER_INFO csbi;
1851 GetConsoleScreenBufferInfo(con_out,&csbi);
1853 /* The clip rectangle is the entire visible screen. */
1854 rcClip.Left = csbi.srWindow.Left;
1855 rcClip.Top = csbi.srWindow.Top;
1856 rcClip.Right = csbi.srWindow.Right;
1857 rcClip.Bottom = csbi.srWindow.Bottom;
1859 /* The source rectangle is the visible screen minus the last line. */
1863 /* Move the top left corner of the source window down one row. */
1864 new_org.X = rcSrc.Left;
1865 new_org.Y = rcSrc.Top + 1;
1867 /* Fill the right character and attributes. */
1868 fillchar.Char.AsciiChar = ' ';
1869 curr_attr = MAKEATTR(nm_fg_color, nm_bg_color);
1870 fillchar.Attributes = curr_attr;
1871 ScrollConsoleScreenBuffer(con_out, &rcSrc, &rcClip, new_org, &fillchar);
1872 _settextposition(1,1);
1882 * Remove the n topmost lines and scroll everything below it in the
1883 * window upward. This is needed to stop leaking the topmost line
1884 * into the scrollback buffer when we go down-one-line (in WIN32).
1890 #if MSDOS_COMPILER==WIN32C
1891 SMALL_RECT rcSrc, rcClip;
1894 CONSOLE_SCREEN_BUFFER_INFO csbi; /* to get buffer info */
1896 if (n >= sc_height - 1)
1905 GetConsoleScreenBufferInfo(con_out, &csbi);
1907 /* Get the extent of all-visible-rows-but-the-last. */
1908 rcSrc.Left = csbi.srWindow.Left;
1909 rcSrc.Top = csbi.srWindow.Top + n;
1910 rcSrc.Right = csbi.srWindow.Right;
1911 rcSrc.Bottom = csbi.srWindow.Bottom;
1913 /* Get the clip rectangle. */
1914 rcClip.Left = rcSrc.Left;
1915 rcClip.Top = csbi.srWindow.Top;
1916 rcClip.Right = rcSrc.Right;
1917 rcClip.Bottom = rcSrc.Bottom ;
1919 /* Move the source window up n rows. */
1920 new_org.X = rcSrc.Left;
1921 new_org.Y = rcSrc.Top - n;
1923 /* Fill the right character and attributes. */
1924 fillchar.Char.AsciiChar = ' ';
1925 curr_attr = MAKEATTR(nm_fg_color, nm_bg_color);
1926 fillchar.Attributes = curr_attr;
1928 ScrollConsoleScreenBuffer(con_out, &rcSrc, &rcClip, new_org, &fillchar);
1930 /* Position cursor on first blank line. */
1931 goto_line(sc_height - n - 1);
1936 #if MSDOS_COMPILER==WIN32C
1941 win32_clear(VOID_PARAM)
1944 * This will clear only the currently visible rows of the NT
1945 * console buffer, which means none of the precious scrollback
1946 * rows are touched making for faster scrolling. Note that, if
1947 * the window has fewer columns than the console buffer (i.e.
1948 * there is a horizontal scrollbar as well), the entire width
1949 * of the visible rows will be cleared.
1954 CONSOLE_SCREEN_BUFFER_INFO csbi;
1956 /* get the number of cells in the current buffer */
1957 GetConsoleScreenBufferInfo(con_out, &csbi);
1958 winsz = csbi.dwSize.X * (csbi.srWindow.Bottom - csbi.srWindow.Top + 1);
1960 topleft.Y = csbi.srWindow.Top;
1962 curr_attr = MAKEATTR(nm_fg_color, nm_bg_color);
1963 FillConsoleOutputCharacter(con_out, ' ', winsz, topleft, &nchars);
1964 FillConsoleOutputAttribute(con_out, curr_attr, winsz, topleft, &nchars);
1968 * Remove the n topmost lines and scroll everything below it in the
1975 SMALL_RECT rcSrc, rcClip;
1981 CONSOLE_SCREEN_BUFFER_INFO csbi;
1986 if (n >= sc_height - 1)
1989 _settextposition(1,1);
1993 /* Get the extent of what will remain visible after scrolling. */
1994 GetConsoleScreenBufferInfo(con_out, &csbi);
1995 rcSrc.Left = csbi.srWindow.Left;
1996 rcSrc.Top = csbi.srWindow.Top + n;
1997 rcSrc.Right = csbi.srWindow.Right;
1998 rcSrc.Bottom = csbi.srWindow.Bottom;
2000 /* Get the clip rectangle. */
2001 rcClip.Left = rcSrc.Left;
2002 rcClip.Top = csbi.srWindow.Top;
2003 rcClip.Right = rcSrc.Right;
2004 rcClip.Bottom = rcSrc.Bottom ;
2006 /* Move the source text to the top of the screen. */
2007 new_org.X = rcSrc.Left;
2008 new_org.Y = rcClip.Top;
2010 /* Fill the right character and attributes. */
2011 fillchar.Char.AsciiChar = ' ';
2012 fillchar.Attributes = MAKEATTR(nm_fg_color, nm_bg_color);
2014 /* Scroll the window. */
2015 SetConsoleTextAttribute(con_out, fillchar.Attributes);
2016 ScrollConsoleScreenBuffer(con_out, &rcSrc, &rcClip, new_org, &fillchar);
2018 /* Clear remaining lines at bottom. */
2019 topleft.X = csbi.dwCursorPosition.X;
2020 topleft.Y = rcSrc.Bottom - n;
2021 size = (n * csbi.dwSize.X) + (rcSrc.Right - topleft.X);
2022 FillConsoleOutputCharacter(con_out, ' ', size, topleft,
2024 FillConsoleOutputAttribute(con_out, fillchar.Attributes, size, topleft,
2026 SetConsoleTextAttribute(con_out, curr_attr);
2028 /* Move cursor n lines up from where it was. */
2029 csbi.dwCursorPosition.Y -= n;
2030 SetConsoleCursorPosition(con_out, csbi.dwCursorPosition);
2035 * Move cursor to lower left corner of screen.
2038 lower_left(VOID_PARAM)
2040 assert_interactive();
2042 ltputs(sc_lower_left, 1, putchr);
2045 _settextposition(sc_height, 1);
2050 * Move cursor to left position of current line.
2053 line_left(VOID_PARAM)
2055 assert_interactive();
2057 ltputs(sc_return, 1, putchr);
2062 #if MSDOS_COMPILER==WIN32C
2064 CONSOLE_SCREEN_BUFFER_INFO scr;
2065 GetConsoleScreenBufferInfo(con_out, &scr);
2066 row = scr.dwCursorPosition.Y - scr.srWindow.Top + 1;
2069 #if MSDOS_COMPILER==BORLANDC || MSDOS_COMPILER==DJGPPC
2073 struct rccoord tpos = _gettextposition();
2078 _settextposition(row, 1);
2084 * Check if the console size has changed and reset internals
2085 * (in lieu of SIGWINCH for WIN32).
2088 check_winch(VOID_PARAM)
2090 #if MSDOS_COMPILER==WIN32C
2091 CONSOLE_SCREEN_BUFFER_INFO scr;
2094 if (con_out == INVALID_HANDLE_VALUE)
2098 GetConsoleScreenBufferInfo(con_out, &scr);
2099 size.Y = scr.srWindow.Bottom - scr.srWindow.Top + 1;
2100 size.X = scr.srWindow.Right - scr.srWindow.Left + 1;
2101 if (size.Y != sc_height || size.X != sc_width)
2105 if (!no_init && con_out_ours == con_out)
2106 SetConsoleScreenBufferSize(con_out, size);
2108 wscroll = (sc_height + 1) / 2;
2115 * Goto a specific line on the screen.
2121 assert_interactive();
2123 ltputs(tgoto(sc_move, 0, sindex), 1, putchr);
2126 _settextposition(sindex+1, 1);
2130 #if MSDOS_COMPILER==MSOFTC || MSDOS_COMPILER==BORLANDC
2132 * Create an alternate screen which is all white.
2133 * This screen is used to create a "flash" effect, by displaying it
2134 * briefly and then switching back to the normal screen.
2135 * {{ Yuck! There must be a better way to get a visual bell. }}
2138 create_flash(VOID_PARAM)
2140 #if MSDOS_COMPILER==MSOFTC
2141 struct videoconfig w;
2145 _getvideoconfig(&w);
2146 videopages = w.numvideopages;
2149 at_enter(AT_STANDOUT);
2154 at_enter(AT_STANDOUT);
2155 blanks = (char *) ecalloc(w.numtextcols, sizeof(char));
2156 for (col = 0; col < w.numtextcols; col++)
2158 for (row = w.numtextrows; row > 0; row--)
2159 _outmem(blanks, w.numtextcols);
2166 #if MSDOS_COMPILER==BORLANDC
2169 whitescreen = (unsigned short *)
2170 malloc(sc_width * sc_height * sizeof(short));
2171 if (whitescreen == NULL)
2173 for (n = 0; n < sc_width * sc_height; n++)
2174 whitescreen[n] = 0x7020;
2179 #endif /* MSDOS_COMPILER */
2182 * Output the "visual bell", if there is one.
2188 if (*sc_visual_bell == '\0')
2190 ltputs(sc_visual_bell, sc_height, putchr);
2192 #if MSDOS_COMPILER==DJGPPC
2195 #if MSDOS_COMPILER==MSOFTC
2197 * Create a flash screen on the second video page.
2198 * Switch to that page, then switch back.
2208 #if MSDOS_COMPILER==BORLANDC
2209 unsigned short *currscreen;
2212 * Get a copy of the current screen.
2213 * Display the flash screen.
2214 * Then restore the old screen.
2218 if (whitescreen == NULL)
2220 currscreen = (unsigned short *)
2221 malloc(sc_width * sc_height * sizeof(short));
2222 if (currscreen == NULL) return;
2223 gettext(1, 1, sc_width, sc_height, currscreen);
2224 puttext(1, 1, sc_width, sc_height, whitescreen);
2226 puttext(1, 1, sc_width, sc_height, currscreen);
2229 #if MSDOS_COMPILER==WIN32C
2230 /* paint screen with an inverse color */
2233 /* leave it displayed for 100 msec. */
2236 /* restore with a redraw */
2252 putchr(CONTROL('G'));
2254 #if MSDOS_COMPILER==WIN32C
2263 * Ring the terminal bell.
2268 if (quiet == VERY_QUIET)
2280 assert_interactive();
2282 ltputs(sc_clear, sc_height, putchr);
2285 #if MSDOS_COMPILER==WIN32C
2288 _clearscreen(_GCLEARSCREEN);
2294 * Clear from the cursor to the end of the cursor's line.
2295 * {{ This must not move the cursor. }}
2298 clear_eol(VOID_PARAM)
2300 /* assert_interactive();*/
2302 ltputs(sc_eol_clear, 1, putchr);
2304 #if MSDOS_COMPILER==MSOFTC
2307 struct rccoord tpos;
2311 * Save current state.
2313 tpos = _gettextposition();
2314 _gettextwindow(&top, &left, &bot, &right);
2316 * Set a temporary window to the current line,
2317 * from the cursor's position to the right edge of the screen.
2318 * Then clear that window.
2320 _settextwindow(tpos.row, tpos.col, tpos.row, sc_width);
2321 _clearscreen(_GWINDOW);
2325 _settextwindow(top, left, bot, right);
2326 _settextposition(tpos.row, tpos.col);
2328 #if MSDOS_COMPILER==BORLANDC || MSDOS_COMPILER==DJGPPC
2332 #if MSDOS_COMPILER==WIN32C
2335 CONSOLE_SCREEN_BUFFER_INFO scr;
2338 memset(&scr, 0, sizeof(scr));
2339 GetConsoleScreenBufferInfo(con_out, &scr);
2340 cpos.X = scr.dwCursorPosition.X;
2341 cpos.Y = scr.dwCursorPosition.Y;
2342 curr_attr = MAKEATTR(nm_fg_color, nm_bg_color);
2343 FillConsoleOutputAttribute(con_out, curr_attr,
2344 scr.dwSize.X - cpos.X, cpos, &nchars);
2345 FillConsoleOutputCharacter(con_out, ' ',
2346 scr.dwSize.X - cpos.X, cpos, &nchars);
2354 * Clear the current line.
2355 * Clear the screen if there's off-screen memory below the display.
2358 clear_eol_bot(VOID_PARAM)
2360 assert_interactive();
2365 ltputs(sc_eos_clear, 1, putchr);
2367 ltputs(sc_eol_clear, 1, putchr);
2372 * Clear the bottom line of the display.
2373 * Leave the cursor at the beginning of the bottom line.
2376 clear_bot(VOID_PARAM)
2379 * If we're in a non-normal attribute mode, temporarily exit
2380 * the mode while we do the clear. Some terminals fill the
2381 * cleared area with the current attribute.
2388 if (attrmode == AT_NORMAL)
2392 int saved_attrmode = attrmode;
2396 at_enter(saved_attrmode);
2401 * Color string may be "x[y]" where x and y are 4-bit color chars,
2402 * or "N[.M]" where N and M are decimal integers>
2403 * Any of x,y,N,M may also be "-" to mean "unchanged".
2407 * Parse a 4-bit color char.
2416 case 'r': return CV_RED;
2417 case 'g': return CV_GREEN;
2418 case 'y': return CV_RED|CV_GREEN;
2419 case 'b': return CV_BLUE;
2420 case 'm': return CV_RED|CV_BLUE;
2421 case 'c': return CV_GREEN|CV_BLUE;
2422 case 'w': return CV_RED|CV_GREEN|CV_BLUE;
2423 case 'K': return 0|CV_BRIGHT;
2424 case 'R': return CV_RED|CV_BRIGHT;
2425 case 'G': return CV_GREEN|CV_BRIGHT;
2426 case 'Y': return CV_RED|CV_GREEN|CV_BRIGHT;
2427 case 'B': return CV_BLUE|CV_BRIGHT;
2428 case 'M': return CV_RED|CV_BLUE|CV_BRIGHT;
2429 case 'C': return CV_GREEN|CV_BLUE|CV_BRIGHT;
2430 case 'W': return CV_RED|CV_GREEN|CV_BLUE|CV_BRIGHT;
2431 case '-': return CV_NOCHANGE;
2432 default: return CV_ERROR;
2437 * Parse a color as a decimal integer.
2450 int color = lstrtoi(ops, ps);
2458 * Parse a color pair and return the foreground/background values.
2459 * Return type of color specifier:
2460 * CV_4BIT: fg/bg values are OR of CV_{RGB} bits.
2461 * CV_6BIT: fg/bg values are integers entered by user.
2464 parse_color(str, p_fg, p_bg)
2471 COLOR_TYPE type = CT_NULL;
2473 if (str == NULL || *str == '\0')
2476 str++; /* ignore leading + */
2478 fg = parse_color4(str[0]);
2479 bg = parse_color4((strlen(str) < 2) ? '-' : str[1]);
2480 if (fg != CV_ERROR && bg != CV_ERROR)
2484 fg = parse_color6(&str);
2485 bg = (fg != CV_ERROR && *str++ == '.') ? parse_color6(&str) : CV_NOCHANGE;
2486 if (fg != CV_ERROR && bg != CV_ERROR)
2489 if (p_fg != NULL) *p_fg = fg;
2490 if (p_bg != NULL) *p_bg = bg;
2503 case CV_RED: return 31;
2504 case CV_GREEN: return 32;
2505 case CV_RED|CV_GREEN: return 33;
2506 case CV_BLUE: return 34;
2507 case CV_RED|CV_BLUE: return 35;
2508 case CV_GREEN|CV_BLUE: return 36;
2509 case CV_RED|CV_GREEN|CV_BLUE: return 37;
2511 case CV_BRIGHT: return 90;
2512 case CV_RED|CV_BRIGHT: return 91;
2513 case CV_GREEN|CV_BRIGHT: return 92;
2514 case CV_RED|CV_GREEN|CV_BRIGHT: return 93;
2515 case CV_BLUE|CV_BRIGHT: return 94;
2516 case CV_RED|CV_BLUE|CV_BRIGHT: return 95;
2517 case CV_GREEN|CV_BLUE|CV_BRIGHT: return 96;
2518 case CV_RED|CV_GREEN|CV_BLUE|CV_BRIGHT: return 97;
2520 default: return color;
2525 tput_fmt(fmt, color, f_putc)
2531 if (color == attrcolor)
2533 SNPRINTF1(buf, sizeof(buf), fmt, color);
2534 ltputs(buf, 1, f_putc);
2539 tput_color(str, f_putc)
2546 if (str != NULL && strcmp(str, "*") == 0)
2548 /* Special case: reset to normal */
2549 tput_fmt(ESCS"[m", -1, f_putc);
2552 switch (parse_color(str, &fg, &bg))
2556 tput_fmt(ESCS"[%dm", sgr_color(fg), f_putc);
2558 tput_fmt(ESCS"[%dm", sgr_color(bg)+10, f_putc);
2562 tput_fmt(ESCS"[38;5;%dm", fg, f_putc);
2564 tput_fmt(ESCS"[48;5;%dm", bg, f_putc);
2572 tput_inmode(mode_str, attr, attr_bit, f_putc)
2579 if ((attr & attr_bit) == 0)
2581 color_str = get_color_map(attr_bit);
2582 if (color_str == NULL || *color_str == '\0' || *color_str == '+')
2584 ltputs(mode_str, 1, f_putc);
2585 if (color_str == NULL || *color_str++ != '+')
2588 /* Color overrides mode string */
2589 tput_color(color_str, f_putc);
2593 tput_outmode(mode_str, attr_bit, f_putc)
2598 if ((attrmode & attr_bit) == 0)
2600 ltputs(mode_str, 1, f_putc);
2603 #else /* MSDOS_COMPILER */
2605 #if MSDOS_COMPILER==WIN32C
2607 WIN32put_fmt(fmt, color)
2612 int len = SNPRINTF1(buf, sizeof(buf), fmt, color);
2613 WIN32textout(buf, len);
2625 char *str = get_color_map(attr);
2626 if (str == NULL || str[0] == '\0')
2628 switch (parse_color(str, &fg, &bg))
2631 if (fg >= 0 && bg >= 0)
2645 #if MSDOS_COMPILER==WIN32C
2650 out = WIN32put_fmt(ESCS"[38;5;%dm", fg);
2652 out = WIN32put_fmt(ESCS"[48;5;%dm", bg);
2662 #endif /* MSDOS_COMPILER */
2668 attr = apply_at_specials(attr);
2670 /* The one with the most priority is last. */
2671 tput_inmode(sc_u_in, attr, AT_UNDERLINE, putchr);
2672 tput_inmode(sc_b_in, attr, AT_BOLD, putchr);
2673 tput_inmode(sc_bl_in, attr, AT_BLINK, putchr);
2674 /* Don't use standout and color at the same time. */
2675 if (use_color && (attr & AT_COLOR))
2676 tput_color(get_color_map(attr), putchr);
2678 tput_inmode(sc_s_in, attr, AT_STANDOUT, putchr);
2681 /* The one with the most priority is first. */
2682 if ((attr & AT_COLOR) && use_color)
2684 win_set_color(attr);
2685 } else if (attr & AT_STANDOUT)
2687 SETCOLORS(so_fg_color, so_bg_color);
2688 } else if (attr & AT_BLINK)
2690 SETCOLORS(bl_fg_color, bl_bg_color);
2691 } else if (attr & AT_BOLD)
2693 SETCOLORS(bo_fg_color, bo_bg_color);
2694 } else if (attr & AT_UNDERLINE)
2696 SETCOLORS(ul_fg_color, ul_bg_color);
2706 /* Undo things in the reverse order we did them. */
2707 tput_color("*", putchr);
2708 tput_outmode(sc_s_out, AT_STANDOUT, putchr);
2709 tput_outmode(sc_bl_out, AT_BLINK, putchr);
2710 tput_outmode(sc_b_out, AT_BOLD, putchr);
2711 tput_outmode(sc_u_out, AT_UNDERLINE, putchr);
2714 SETCOLORS(nm_fg_color, nm_bg_color);
2716 attrmode = AT_NORMAL;
2723 int new_attrmode = apply_at_specials(attr);
2724 int ignore_modes = AT_ANSI;
2726 if ((new_attrmode & ~ignore_modes) != (attrmode & ~ignore_modes))
2734 is_at_equiv(attr1, attr2)
2738 attr1 = apply_at_specials(attr1);
2739 attr2 = apply_at_specials(attr2);
2741 return (attr1 == attr2);
2745 apply_at_specials(attr)
2748 if (attr & AT_BINARY)
2750 if (attr & AT_HILITE)
2751 attr |= AT_STANDOUT;
2752 attr &= ~(AT_BINARY|AT_HILITE);
2758 * Output a plain backspace, without erasing the previous char.
2768 ltputs(sc_backspace, 1, putchr);
2774 #if MSDOS_COMPILER==MSOFTC
2775 struct rccoord tpos;
2776 tpos = _gettextposition();
2780 #if MSDOS_COMPILER==BORLANDC || MSDOS_COMPILER==DJGPPC
2784 #if MSDOS_COMPILER==WIN32C
2785 CONSOLE_SCREEN_BUFFER_INFO scr;
2786 GetConsoleScreenBufferInfo(con_out, &scr);
2787 row = scr.dwCursorPosition.Y - scr.srWindow.Top + 1;
2788 col = scr.dwCursorPosition.X - scr.srWindow.Left + 1;
2795 _settextposition(row, col-1);
2796 #endif /* MSDOS_COMPILER */
2800 #if MSDOS_COMPILER==WIN32C
2802 * Determine whether an input character is waiting to be read.
2805 win32_kbhit(VOID_PARAM)
2813 currentKey.ascii = 0;
2814 currentKey.scan = 0;
2816 if (x11mouseCount > 0)
2818 currentKey.ascii = x11mousebuf[x11mousePos++];
2825 * Wait for a real key-down event, but
2826 * ignore SHIFT and CONTROL key events.
2830 PeekConsoleInput(tty, &ip, 1, &read);
2833 ReadConsoleInput(tty, &ip, 1, &read);
2834 /* generate an X11 mouse sequence from the mouse event */
2835 if (mousecap && ip.EventType == MOUSE_EVENT &&
2836 ip.Event.MouseEvent.dwEventFlags != MOUSE_MOVED)
2838 x11mousebuf[3] = X11MOUSE_OFFSET + ip.Event.MouseEvent.dwMousePosition.X + 1;
2839 x11mousebuf[4] = X11MOUSE_OFFSET + ip.Event.MouseEvent.dwMousePosition.Y + 1;
2840 switch (ip.Event.MouseEvent.dwEventFlags)
2842 case 0: /* press or release */
2843 if (ip.Event.MouseEvent.dwButtonState == 0)
2844 x11mousebuf[2] = X11MOUSE_OFFSET + X11MOUSE_BUTTON_REL;
2845 else if (ip.Event.MouseEvent.dwButtonState & (FROM_LEFT_3RD_BUTTON_PRESSED | FROM_LEFT_4TH_BUTTON_PRESSED))
2848 x11mousebuf[2] = X11MOUSE_OFFSET + X11MOUSE_BUTTON1 + ((int)ip.Event.MouseEvent.dwButtonState << 1);
2851 x11mousebuf[2] = X11MOUSE_OFFSET + (((int)ip.Event.MouseEvent.dwButtonState < 0) ? X11MOUSE_WHEEL_DOWN : X11MOUSE_WHEEL_UP);
2858 currentKey.ascii = ESC;
2862 } while (ip.EventType != KEY_EVENT ||
2863 ip.Event.KeyEvent.bKeyDown != TRUE ||
2864 ip.Event.KeyEvent.wVirtualScanCode == 0 ||
2865 ip.Event.KeyEvent.wVirtualKeyCode == VK_SHIFT ||
2866 ip.Event.KeyEvent.wVirtualKeyCode == VK_CONTROL ||
2867 ip.Event.KeyEvent.wVirtualKeyCode == VK_MENU);
2869 currentKey.ascii = ip.Event.KeyEvent.uChar.AsciiChar;
2870 currentKey.scan = ip.Event.KeyEvent.wVirtualScanCode;
2871 keyCount = ip.Event.KeyEvent.wRepeatCount;
2873 if (ip.Event.KeyEvent.dwControlKeyState &
2874 (LEFT_ALT_PRESSED | RIGHT_ALT_PRESSED))
2876 switch (currentKey.scan)
2878 case PCK_ALT_E: /* letter 'E' */
2879 currentKey.ascii = 0;
2882 } else if (ip.Event.KeyEvent.dwControlKeyState &
2883 (LEFT_CTRL_PRESSED | RIGHT_CTRL_PRESSED))
2885 switch (currentKey.scan)
2887 case PCK_RIGHT: /* right arrow */
2888 currentKey.scan = PCK_CTL_RIGHT;
2890 case PCK_LEFT: /* left arrow */
2891 currentKey.scan = PCK_CTL_LEFT;
2893 case PCK_DELETE: /* delete */
2894 currentKey.scan = PCK_CTL_DELETE;
2897 } else if (ip.Event.KeyEvent.dwControlKeyState & SHIFT_PRESSED)
2899 switch (currentKey.scan)
2901 case PCK_SHIFT_TAB: /* tab */
2902 currentKey.ascii = 0;
2911 * Read a character from the keyboard.
2914 WIN32getch(VOID_PARAM)
2918 if (pending_scancode)
2920 pending_scancode = 0;
2921 return ((char)(currentKey.scan & 0x00FF));
2925 while (win32_kbhit() == FALSE)
2933 ascii = currentKey.ascii;
2935 * On PC's, the extended keys return a 2 byte sequence beginning
2936 * with '00', so if the ascii code is 00, the next byte will be
2937 * the lsb of the scan code.
2939 pending_scancode = (ascii == 0x00);
2940 } while (pending_scancode &&
2941 (currentKey.scan == PCK_CAPS_LOCK || currentKey.scan == PCK_NUM_LOCK));
2943 return ((char)ascii);
2951 WIN32setcolors(fg, bg)
2961 WIN32textout(text, len)
2965 #if MSDOS_COMPILER==WIN32C
2970 * We've got UTF-8 text in a non-UTF-8 console. Convert it to
2971 * wide and use WriteConsoleW.
2974 len = MultiByteToWideChar(CP_UTF8, 0, text, len, wtext,
2975 sizeof(wtext)/sizeof(*wtext));
2976 WriteConsoleW(con_out, wtext, len, &written, NULL);
2978 WriteConsole(con_out, text, len, &written, NULL);