2 * Copyright (C) 1984-2023 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
71 #if HAVE_NCURSESW_TERMCAP_H
72 #include <ncursesw/termcap.h>
74 #if HAVE_NCURSES_TERMCAP_H
75 #include <ncurses/termcap.h>
86 #include <sys/signal.h>
90 #include <sys/stream.h>
96 #endif /* MSDOS_COMPILER */
99 * Check for broken termios package that forces you to manually
100 * set the line discipline.
103 #define MUST_SET_LINE_DISCIPLINE 1
105 #define MUST_SET_LINE_DISCIPLINE 0
109 #define DEFAULT_TERM "ansi"
110 static char *windowid;
112 #define DEFAULT_TERM "unknown"
115 #if MSDOS_COMPILER==MSOFTC
116 static int videopages;
117 static long msec_loops;
118 static int flash_created = 0;
119 #define SET_FG_COLOR(fg) _settextcolor(fg)
120 #define SET_BG_COLOR(bg) _setbkcolor(bg)
121 #define SETCOLORS(fg,bg) { SET_FG_COLOR(fg); SET_BG_COLOR(bg); }
124 #if MSDOS_COMPILER==BORLANDC
125 static unsigned short *whitescreen;
126 static int flash_created = 0;
128 #if MSDOS_COMPILER==BORLANDC || MSDOS_COMPILER==DJGPPC
129 #define _settextposition(y,x) gotoxy(x,y)
130 #define _clearscreen(m) clrscr()
131 #define _outtext(s) cputs(s)
132 #define SET_FG_COLOR(fg) textcolor(fg)
133 #define SET_BG_COLOR(bg) textbackground(bg)
134 #define SETCOLORS(fg,bg) { SET_FG_COLOR(fg); SET_BG_COLOR(bg); }
135 extern int sc_height;
138 #if MSDOS_COMPILER==WIN32C
139 #define UTF8_MAX_LENGTH 4
147 static int keyCount = 0;
148 static WORD curr_attr;
149 static int pending_scancode = 0;
150 static char x11mousebuf[] = "[M???"; /* Mouse report, after ESC */
151 static int x11mousePos, x11mouseCount;
152 static int win_unget_pending = FALSE;
153 static int win_unget_data;
155 static HANDLE con_out_save = INVALID_HANDLE_VALUE; /* previous console */
156 static HANDLE con_out_ours = INVALID_HANDLE_VALUE; /* our own */
157 HANDLE con_out = INVALID_HANDLE_VALUE; /* current console */
161 static void win32_init_term();
162 static void win32_deinit_term();
164 #ifndef ENABLE_VIRTUAL_TERMINAL_PROCESSING
165 #define ENABLE_VIRTUAL_TERMINAL_PROCESSING 4
168 #define FG_COLORS (FOREGROUND_RED | FOREGROUND_GREEN | FOREGROUND_BLUE | FOREGROUND_INTENSITY)
169 #define BG_COLORS (BACKGROUND_RED | BACKGROUND_GREEN | BACKGROUND_BLUE | BACKGROUND_INTENSITY)
170 #define MAKEATTR(fg,bg) ((WORD)((fg)|((bg)<<4)))
171 #define APPLY_COLORS() { if (SetConsoleTextAttribute(con_out, curr_attr) == 0) \
172 error("SETCOLORS failed", NULL_PARG); }
173 #define SET_FG_COLOR(fg) { curr_attr &= ~0x0f; curr_attr |= (fg); APPLY_COLORS(); }
174 #define SET_BG_COLOR(bg) { curr_attr &= ~0xf0; curr_attr |= ((bg)<<4); APPLY_COLORS(); }
175 #define SETCOLORS(fg,bg) { curr_attr = MAKEATTR(fg,bg); APPLY_COLORS(); }
179 public int nm_fg_color; /* Color of normal text */
180 public int nm_bg_color;
181 public int bo_fg_color; /* Color of bold text */
182 public int bo_bg_color;
183 public int ul_fg_color; /* Color of underlined text */
184 public int ul_bg_color;
185 public int so_fg_color; /* Color of standout text */
186 public int so_bg_color;
187 public int bl_fg_color; /* Color of blinking text */
188 public int bl_bg_color;
189 static int sy_fg_color; /* Color of system text (before less) */
190 static int sy_bg_color;
191 public int sgr_mode; /* Honor ANSI sequences rather than using above */
192 #if MSDOS_COMPILER==WIN32C
193 static DWORD init_output_mode; /* The initial console output mode */
194 public int vt_enabled = -1; /* Is virtual terminal processing available? */
199 * Strings passed to tputs() to do various terminal functions.
202 *sc_pad, /* Pad string */
203 *sc_home, /* Cursor home */
204 *sc_addline, /* Add line, scroll down following lines */
205 *sc_lower_left, /* Cursor to last line, first column */
206 *sc_return, /* Cursor to beginning of current line */
207 *sc_move, /* General cursor positioning */
208 *sc_clear, /* Clear screen */
209 *sc_eol_clear, /* Clear to end of line */
210 *sc_eos_clear, /* Clear to end of screen */
211 *sc_s_in, /* Enter standout (highlighted) mode */
212 *sc_s_out, /* Exit standout mode */
213 *sc_u_in, /* Enter underline mode */
214 *sc_u_out, /* Exit underline mode */
215 *sc_b_in, /* Enter bold mode */
216 *sc_b_out, /* Exit bold mode */
217 *sc_bl_in, /* Enter blink mode */
218 *sc_bl_out, /* Exit blink mode */
219 *sc_visual_bell, /* Visual bell (flash screen) sequence */
220 *sc_backspace, /* Backspace cursor */
221 *sc_s_keypad, /* Start keypad mode */
222 *sc_e_keypad, /* End keypad mode */
223 *sc_s_mousecap, /* Start mouse capture mode */
224 *sc_e_mousecap, /* End mouse capture mode */
225 *sc_init, /* Startup terminal initialization */
226 *sc_deinit; /* Exit terminal de-initialization */
228 static int attrcolor = -1;
231 static int init_done = 0;
233 public int auto_wrap; /* Terminal does \r\n when write past margin */
234 public int ignaw; /* Terminal ignores \n immediately after wrap */
235 public int erase_char; /* The user's erase char */
236 public int erase2_char; /* The user's other erase char */
237 public int kill_char; /* The user's line-kill char */
238 public int werase_char; /* The user's word-erase char */
239 public int sc_width, sc_height; /* Height & width of screen */
240 public int bo_s_width, bo_e_width; /* Printing width of boldface seq */
241 public int ul_s_width, ul_e_width; /* Printing width of underline seq */
242 public int so_s_width, so_e_width; /* Printing width of standout seq */
243 public int bl_s_width, bl_e_width; /* Printing width of blink seq */
244 public int above_mem, below_mem; /* Memory retained above/below screen */
245 public int can_goto_line; /* Can move cursor to any line */
246 public int clear_bg; /* Clear fills with background color */
247 public int missing_cap = 0; /* Some capability is missing */
248 public char *kent = NULL; /* Keypad ENTER sequence */
249 public int term_init_done = FALSE;
250 public int full_screen = TRUE;
252 static int attrmode = AT_NORMAL;
253 static int termcap_debug = -1;
254 static int no_alt_screen; /* sc_init does not switch to alt screen */
256 extern int one_screen;
258 extern char *ttyin_name;
262 static char *cheaper(char *t1, char *t2, char *def);
263 static void tmodes(char *incap, char *outcap, char **instr,
264 char **outstr, char *def_instr, char *def_outstr, char **spp);
268 * These two variables are sometimes defined in,
269 * and needed by, the termcap library.
271 #if MUST_DEFINE_OSPEED
272 extern short ospeed; /* Terminal output baud rate */
273 extern char PC; /* Pad character */
280 extern int quiet; /* If VERY_QUIET, use visual bell for bell */
282 extern int no_back_scroll;
285 extern int no_keypad;
288 extern int screen_trashed;
289 extern int top_scroll;
290 extern int quit_if_one_screen;
294 extern int use_color;
296 extern int hilite_search;
298 #if MSDOS_COMPILER==WIN32C
300 extern DWORD console_mode;
301 #ifndef ENABLE_EXTENDED_FLAGS
302 #define ENABLE_EXTENDED_FLAGS 0x80
303 #define ENABLE_QUICK_EDIT_MODE 0x40
309 #if (HAVE_TERMIOS_H && HAVE_TERMIOS_FUNCS) || defined(TCGETA)
311 * Set termio flags for use by less.
313 static void set_termio_flags(
314 #if HAVE_TERMIOS_H && HAVE_TERMIOS_FUNCS
377 * Change terminal to "raw mode", or restore to "normal" mode.
379 * 1. An outstanding read will complete on receipt of a single keystroke.
380 * 2. Input is not echoed.
381 * 3. On output, \n is mapped to \r\n.
382 * 4. \t is NOT expanded into spaces.
383 * 5. Signal-causing characters such as ctrl-C (interrupt),
384 * etc. are NOT disabled.
385 * It doesn't matter whether an input \n is mapped to \r, or vice versa.
387 public void raw_mode(int on)
389 static int curr_on = 0;
393 erase2_char = '\b'; /* in case OS doesn't know about erase2 */
395 if (ttyin_name != NULL)
397 /* {{ For consistent conditions when running tests. }} */
399 kill_char = CONTROL('U');
400 werase_char = CONTROL('W');
403 #if HAVE_TERMIOS_H && HAVE_TERMIOS_FUNCS
406 static struct termios save_term;
407 static int saved_term = 0;
412 * Get terminal modes.
414 if (tcgetattr(tty, &s) < 0)
417 kill_char = CONTROL('U');
418 werase_char = CONTROL('W');
422 * Save modes and set certain variables dependent on modes.
430 switch (cfgetospeed(&s))
433 case B0: ospeed = 0; break;
436 case B50: ospeed = 1; break;
439 case B75: ospeed = 2; break;
442 case B110: ospeed = 3; break;
445 case B134: ospeed = 4; break;
448 case B150: ospeed = 5; break;
451 case B200: ospeed = 6; break;
454 case B300: ospeed = 7; break;
457 case B600: ospeed = 8; break;
460 case B1200: ospeed = 9; break;
463 case B1800: ospeed = 10; break;
466 case B2400: ospeed = 11; break;
469 case B4800: ospeed = 12; break;
472 case B9600: ospeed = 13; break;
475 case EXTA: ospeed = 14; break;
478 case EXTB: ospeed = 15; break;
481 case B57600: ospeed = 16; break;
484 case B115200: ospeed = 17; break;
489 erase_char = s.c_cc[VERASE];
491 erase2_char = s.c_cc[VERASE2];
493 kill_char = s.c_cc[VKILL];
495 werase_char = s.c_cc[VWERASE];
497 werase_char = CONTROL('W');
501 * Set the modes to the way we want them.
503 set_termio_flags(&s);
518 #if MUST_SET_LINE_DISCIPLINE
520 * System's termios is broken; need to explicitly
521 * request TERMIODISC line discipline.
523 s.c_line = TERMIODISC;
529 * Restore saved modes.
536 tcsetattr(tty, TCSADRAIN, &s);
537 #if MUST_SET_LINE_DISCIPLINE
541 * Broken termios *ignores* any line discipline
542 * except TERMIODISC. A different old line discipline
543 * is therefore not restored, yet. Restore the old
544 * line discipline by hand.
546 ioctl(tty, TIOCSETD, &save_term.c_line);
554 static struct termio save_term;
555 static int saved_term = 0;
560 * Get terminal modes.
562 ioctl(tty, TCGETA, &s);
565 * Save modes and set certain variables dependent on modes.
573 ospeed = s.c_cflag & CBAUD;
575 erase_char = s.c_cc[VERASE];
576 kill_char = s.c_cc[VKILL];
578 werase_char = s.c_cc[VWERASE];
580 werase_char = CONTROL('W');
584 * Set the modes to the way we want them.
586 set_termio_flags(&s);
598 * Restore saved modes.
602 ioctl(tty, TCSETAW, &s);
608 static struct sgttyb save_term;
609 static int saved_term = 0;
614 * Get terminal modes.
616 ioctl(tty, TIOCGETP, &s);
619 * Save modes and set certain variables dependent on modes.
627 ospeed = s.sg_ospeed;
629 erase_char = s.sg_erase;
630 kill_char = s.sg_kill;
631 werase_char = CONTROL('W');
634 * Set the modes to the way we want them.
636 s.sg_flags |= CBREAK;
637 s.sg_flags &= ~(ECHO|XTABS);
641 * Restore saved modes.
645 ioctl(tty, TIOCSETN, &s);
651 static struct sgbuf save_term;
652 static int saved_term = 0;
657 * Get terminal modes.
662 * Save modes and set certain variables dependent on modes.
669 erase_char = s.sg_bspch;
670 kill_char = s.sg_dlnch;
671 werase_char = CONTROL('W');
674 * Set the modes to the way we want them.
683 * Restore saved modes.
690 /* MS-DOS, Windows, or OS2 */
693 LSIGNAL(SIGINT, SIG_IGN);
696 #if MSDOS_COMPILER==DJGPPC
697 kill_char = CONTROL('U');
699 * So that when we shell out or run another program, its
700 * stdin is in cooked mode. We do not switch stdin to binary
701 * mode if fd0 is zero, since that means we were called before
702 * tty was reopened in open_getchr, in which case we would be
703 * changing the original stdin device outside less.
706 setmode(0, on ? O_BINARY : O_TEXT);
710 werase_char = CONTROL('W');
720 * Some glue to prevent calling termcap functions if tgetent() failed.
724 static char * ltget_env(char *capname)
730 struct env { struct env *next; char *name; char *value; };
731 static struct env *envs = NULL;
733 for (p = envs; p != NULL; p = p->next)
734 if (strcmp(p->name, capname) == 0)
736 p = (struct env *) ecalloc(1, sizeof(struct env));
737 p->name = save(capname);
738 p->value = (char *) ecalloc(strlen(capname)+3, sizeof(char));
739 sprintf(p->value, "<%s>", capname);
744 SNPRINTF1(name, sizeof(name), "LESS_TERMCAP_%s", capname);
745 return (lgetenv(name));
748 static int ltgetflag(char *capname)
752 if ((s = ltget_env(capname)) != NULL)
753 return (*s != '\0' && *s != '0');
756 return (tgetflag(capname));
759 static int ltgetnum(char *capname)
763 if ((s = ltget_env(capname)) != NULL)
767 return (tgetnum(capname));
770 static char * ltgetstr(char *capname, char **pp)
774 if ((s = ltget_env(capname)) != NULL)
778 return (tgetstr(capname, pp));
780 #endif /* MSDOS_COMPILER */
783 * Get size of the output screen.
785 public void scrsize(void)
794 #define DEF_SC_WIDTH 80
796 #define DEF_SC_HEIGHT 25
798 #define DEF_SC_HEIGHT 24
802 sys_width = sys_height = 0;
805 if (ttyin_name != NULL)
808 #if MSDOS_COMPILER==MSOFTC
810 struct videoconfig w;
812 sys_height = w.numtextrows;
813 sys_width = w.numtextcols;
816 #if MSDOS_COMPILER==BORLANDC || MSDOS_COMPILER==DJGPPC
820 sys_height = w.screenheight;
821 sys_width = w.screenwidth;
824 #if MSDOS_COMPILER==WIN32C
826 CONSOLE_SCREEN_BUFFER_INFO scr;
827 GetConsoleScreenBufferInfo(con_out, &scr);
828 sys_height = scr.srWindow.Bottom - scr.srWindow.Top + 1;
829 sys_width = scr.srWindow.Right - scr.srWindow.Left + 1;
839 * When using terminal emulators for XFree86/OS2, the
840 * _scrsize function does not work well.
841 * Call the scrsize.exe program to get the window size.
843 windowid = getenv("WINDOWID");
844 if (windowid != NULL)
846 FILE *fd = popen("scrsize", "rt");
850 fscanf(fd, "%i %i", &w, &h);
864 if (ioctl(2, TIOCGWINSZ, &w) == 0)
867 sys_height = w.ws_row;
869 sys_width = w.ws_col;
876 if (ioctl(2, WIOCGETD, &w) == 0)
879 sys_height = w.uw_height / w.uw_vs;
881 sys_width = w.uw_width / w.uw_hs;
893 sc_height = sys_height;
894 else if ((s = lgetenv("LINES")) != NULL)
897 else if ((n = ltgetnum("li")) > 0)
900 if ((s = lgetenv("LESS_LINES")) != NULL)
902 int height = atoi(s);
903 sc_height = (height < 0) ? sc_height + height : height;
907 sc_height = DEF_SC_HEIGHT;
910 sc_width = sys_width;
911 else if ((s = lgetenv("COLUMNS")) != NULL)
914 else if ((n = ltgetnum("co")) > 0)
917 if ((s = lgetenv("LESS_COLUMNS")) != NULL)
920 sc_width = (width < 0) ? sc_width + width : width;
923 sc_width = DEF_SC_WIDTH;
926 #if MSDOS_COMPILER==MSOFTC
928 * Figure out how many empty loops it takes to delay a millisecond.
930 static void get_clock(void)
935 * Get synchronized at the start of a tick.
938 while (clock() == start)
941 * Now count loops till the next tick.
945 while (clock() == start)
948 * Convert from (loops per clock) to (loops per millisecond).
950 msec_loops *= CLOCKS_PER_SEC;
955 * Delay for a specified number of milliseconds.
957 static void delay(int msec)
963 for (i = 0; i < msec_loops; i++)
970 * Return the characters actually input by a "special" key.
972 public char * special_key_str(int key)
974 static char tbuf[40];
976 #if MSDOS_COMPILER || OS2
977 static char k_right[] = { '\340', PCK_RIGHT, 0 };
978 static char k_left[] = { '\340', PCK_LEFT, 0 };
979 static char k_ctl_right[] = { '\340', PCK_CTL_RIGHT, 0 };
980 static char k_ctl_left[] = { '\340', PCK_CTL_LEFT, 0 };
981 static char k_insert[] = { '\340', PCK_INSERT, 0 };
982 static char k_delete[] = { '\340', PCK_DELETE, 0 };
983 static char k_ctl_delete[] = { '\340', PCK_CTL_DELETE, 0 };
984 static char k_ctl_backspace[] = { '\177', 0 };
985 static char k_backspace[] = { '\b', 0 };
986 static char k_home[] = { '\340', PCK_HOME, 0 };
987 static char k_end[] = { '\340', PCK_END, 0 };
988 static char k_up[] = { '\340', PCK_UP, 0 };
989 static char k_down[] = { '\340', PCK_DOWN, 0 };
990 static char k_backtab[] = { '\340', PCK_SHIFT_TAB, 0 };
991 static char k_pagedown[] = { '\340', PCK_PAGEDOWN, 0 };
992 static char k_pageup[] = { '\340', PCK_PAGEUP, 0 };
993 static char k_f1[] = { '\340', PCK_F1, 0 };
1003 * If windowid is not NULL, assume less is executed in
1004 * the XFree86 environment.
1006 case SK_RIGHT_ARROW:
1007 s = windowid ? ltgetstr("kr", &sp) : k_right;
1010 s = windowid ? ltgetstr("kl", &sp) : k_left;
1013 s = windowid ? ltgetstr("ku", &sp) : k_up;
1016 s = windowid ? ltgetstr("kd", &sp) : k_down;
1019 s = windowid ? ltgetstr("kP", &sp) : k_pageup;
1022 s = windowid ? ltgetstr("kN", &sp) : k_pagedown;
1025 s = windowid ? ltgetstr("kh", &sp) : k_home;
1028 s = windowid ? ltgetstr("@7", &sp) : k_end;
1031 s = windowid ? ltgetstr("kD", &sp) : k_delete;
1041 case SK_RIGHT_ARROW:
1069 #if MSDOS_COMPILER || OS2
1073 case SK_CTL_LEFT_ARROW:
1076 case SK_CTL_RIGHT_ARROW:
1079 case SK_CTL_BACKSPACE:
1080 s = k_ctl_backspace;
1095 case SK_RIGHT_ARROW:
1096 s = ltgetstr("kr", &sp);
1099 s = ltgetstr("kl", &sp);
1102 s = ltgetstr("ku", &sp);
1105 s = ltgetstr("kd", &sp);
1108 s = ltgetstr("kP", &sp);
1111 s = ltgetstr("kN", &sp);
1114 s = ltgetstr("kh", &sp);
1117 s = ltgetstr("@7", &sp);
1120 s = ltgetstr("kD", &sp);
1129 s = ltgetstr("kb", &sp);
1139 tbuf[0] = CONTROL('K');
1150 * Get terminal capabilities via termcap.
1152 public void get_term(void)
1154 termcap_debug = !isnullenv(lgetenv("LESS_TERMCAP_DEBUG"));
1161 * Set up default colors.
1162 * The xx_s_width and xx_e_width vars are already initialized to 0.
1164 #if MSDOS_COMPILER==MSOFTC
1165 sy_bg_color = _getbkcolor();
1166 sy_fg_color = _gettextcolor();
1169 #if MSDOS_COMPILER==BORLANDC || MSDOS_COMPILER==DJGPPC
1173 sy_bg_color = (w.attribute >> 4) & 0x0F;
1174 sy_fg_color = (w.attribute >> 0) & 0x0F;
1177 #if MSDOS_COMPILER==WIN32C
1179 CONSOLE_SCREEN_BUFFER_INFO scr;
1181 con_out_save = con_out = GetStdHandle(STD_OUTPUT_HANDLE);
1183 * Always open stdin in binary. Note this *must* be done
1184 * before any file operations have been done on fd0.
1187 GetConsoleMode(con_out, &init_output_mode);
1188 GetConsoleScreenBufferInfo(con_out, &scr);
1189 curr_attr = scr.wAttributes;
1190 sy_bg_color = (curr_attr & BG_COLORS) >> 4; /* normalize */
1191 sy_fg_color = curr_attr & FG_COLORS;
1196 nm_fg_color = sy_fg_color;
1197 nm_bg_color = sy_bg_color;
1209 * Get size of the screen.
1215 #else /* !MSDOS_COMPILER */
1221 * Some termcap libraries assume termbuf is static
1222 * (accessible after tgetent returns).
1224 static char termbuf[TERMBUF_SIZE];
1225 static char sbuf[TERMSBUF_SIZE];
1229 * Make sure the termcap database is available.
1231 sp = lgetenv("TERMCAP");
1235 if ((sp = homefile("termcap.dat")) != NULL)
1237 termcap = (char *) ecalloc(strlen(sp)+9, sizeof(char));
1238 sprintf(termcap, "TERMCAP=%s", sp);
1245 * Find out what kind of terminal this is.
1247 if ((term = lgetenv("TERM")) == NULL)
1248 term = DEFAULT_TERM;
1250 /* {{ Should probably just pass NULL instead of termbuf. }} */
1251 if (tgetent(termbuf, term) != TGETENT_OK)
1253 if (ltgetflag("hc"))
1257 * Get size of the screen.
1262 auto_wrap = ltgetflag("am");
1263 ignaw = ltgetflag("xn");
1264 above_mem = ltgetflag("da");
1265 below_mem = ltgetflag("db");
1266 clear_bg = ltgetflag("ut");
1267 no_alt_screen = ltgetflag("NR");
1270 * Assumes termcap variable "sg" is the printing width of:
1271 * the standout sequence, the end standout sequence,
1272 * the underline sequence, the end underline sequence,
1273 * the boldface sequence, and the end boldface sequence.
1275 if ((so_s_width = ltgetnum("sg")) < 0)
1277 so_e_width = so_s_width;
1279 bo_s_width = bo_e_width = so_s_width;
1280 ul_s_width = ul_e_width = so_s_width;
1281 bl_s_width = bl_e_width = so_s_width;
1284 if (so_s_width > 0 || so_e_width > 0)
1286 * Disable highlighting by default on magic cookie terminals.
1287 * Turning on highlighting might change the displayed width
1288 * of a line, causing the display to get messed up.
1289 * The user can turn it back on with -g,
1290 * but she won't like the results.
1296 * Get various string-valued capabilities.
1301 sc_pad = ltgetstr("pc", &sp);
1306 sc_s_keypad = ltgetstr("ks", &sp);
1307 if (sc_s_keypad == NULL)
1309 sc_e_keypad = ltgetstr("ke", &sp);
1310 if (sc_e_keypad == NULL)
1312 kent = ltgetstr("@8", &sp);
1314 sc_s_mousecap = ltgetstr("MOUSE_START", &sp);
1315 if (sc_s_mousecap == NULL)
1316 sc_s_mousecap = ESCS "[?1000h" ESCS "[?1006h";
1317 sc_e_mousecap = ltgetstr("MOUSE_END", &sp);
1318 if (sc_e_mousecap == NULL)
1319 sc_e_mousecap = ESCS "[?1006l" ESCS "[?1000l";
1321 sc_init = ltgetstr("ti", &sp);
1322 if (sc_init == NULL)
1325 sc_deinit= ltgetstr("te", &sp);
1326 if (sc_deinit == NULL)
1329 sc_eol_clear = ltgetstr("ce", &sp);
1330 if (sc_eol_clear == NULL || *sc_eol_clear == '\0')
1336 sc_eos_clear = ltgetstr("cd", &sp);
1337 if (below_mem && (sc_eos_clear == NULL || *sc_eos_clear == '\0'))
1343 sc_clear = ltgetstr("cl", &sp);
1344 if (sc_clear == NULL || *sc_clear == '\0')
1350 sc_move = ltgetstr("cm", &sp);
1351 if (sc_move == NULL || *sc_move == '\0')
1354 * This is not an error here, because we don't
1355 * always need sc_move.
1356 * We need it only if we don't have home or lower-left.
1363 tmodes("so", "se", &sc_s_in, &sc_s_out, "", "", &sp);
1364 tmodes("us", "ue", &sc_u_in, &sc_u_out, sc_s_in, sc_s_out, &sp);
1365 tmodes("md", "me", &sc_b_in, &sc_b_out, sc_s_in, sc_s_out, &sp);
1366 tmodes("mb", "me", &sc_bl_in, &sc_bl_out, sc_s_in, sc_s_out, &sp);
1368 sc_visual_bell = ltgetstr("vb", &sp);
1369 if (sc_visual_bell == NULL)
1370 sc_visual_bell = "";
1372 if (ltgetflag("bs"))
1373 sc_backspace = "\b";
1376 sc_backspace = ltgetstr("bc", &sp);
1377 if (sc_backspace == NULL || *sc_backspace == '\0')
1378 sc_backspace = "\b";
1382 * Choose between using "ho" and "cm" ("home" and "cursor move")
1383 * to move the cursor to the upper left corner of the screen.
1385 t1 = ltgetstr("ho", &sp);
1388 if (*sc_move == '\0')
1392 strcpy(sp, tgoto(sc_move, 0, 0));
1394 sp += strlen(sp) + 1;
1396 sc_home = cheaper(t1, t2, "|\b^");
1399 * Choose between using "ll" and "cm" ("lower left" and "cursor move")
1400 * to move the cursor to the lower left corner of the screen.
1402 t1 = ltgetstr("ll", &sp);
1403 if (t1 == NULL || !full_screen)
1405 if (*sc_move == '\0')
1409 strcpy(sp, tgoto(sc_move, 0, sc_height-1));
1411 sp += strlen(sp) + 1;
1413 sc_lower_left = cheaper(t1, t2, "\r");
1416 * Get carriage return string.
1418 sc_return = ltgetstr("cr", &sp);
1419 if (sc_return == NULL)
1423 * Choose between using "al" or "sr" ("add line" or "scroll reverse")
1424 * to add a line at the top of the screen.
1426 t1 = ltgetstr("al", &sp);
1429 t2 = ltgetstr("sr", &sp);
1433 if (*t1 == '\0' && *t2 == '\0')
1440 sc_addline = cheaper(t1, t2, "");
1441 if (*sc_addline == '\0')
1444 * Force repaint on any backward movement.
1449 #endif /* MSDOS_COMPILER */
1454 * Return the cost of displaying a termcap string.
1455 * We use the trick of calling tputs, but as a char printing function
1456 * we give it inc_costcount, which just increments "costcount".
1457 * This tells us how many chars would be printed by using this string.
1458 * {{ Couldn't we just use strlen? }}
1460 static int costcount;
1463 static int inc_costcount(int c)
1469 static int cost(char *t)
1472 tputs(t, sc_height, inc_costcount);
1477 * Return the "best" of the two given termcap strings.
1478 * The best, if both exist, is the one with the lower
1479 * cost (see cost() function).
1481 static char * cheaper(char *t1, char *t2, char *def)
1483 if (*t1 == '\0' && *t2 == '\0')
1492 if (cost(t1) < cost(t2))
1497 static void tmodes(char *incap, char *outcap, char **instr, char **outstr, char *def_instr, char *def_outstr, char **spp)
1499 *instr = ltgetstr(incap, spp);
1504 *outstr = def_outstr;
1508 *outstr = ltgetstr(outcap, spp);
1509 if (*outstr == NULL)
1510 /* No specific out capability; use "me". */
1511 *outstr = ltgetstr("me", spp);
1512 if (*outstr == NULL)
1513 /* Don't even have "me"; use a null string. */
1517 #endif /* MSDOS_COMPILER */
1521 * Below are the functions which perform all the
1522 * terminal-specific screen manipulation.
1528 #if MSDOS_COMPILER==WIN32C
1529 static void _settextposition(int row, int col)
1532 CONSOLE_SCREEN_BUFFER_INFO csbi;
1534 GetConsoleScreenBufferInfo(con_out, &csbi);
1535 cpos.X = csbi.srWindow.Left + (col - 1);
1536 cpos.Y = csbi.srWindow.Top + (row - 1);
1537 SetConsoleCursorPosition(con_out, cpos);
1542 * Initialize the screen to the correct color at startup.
1544 static void initcolor(void)
1546 #if MSDOS_COMPILER==BORLANDC || MSDOS_COMPILER==DJGPPC
1549 SETCOLORS(nm_fg_color, nm_bg_color);
1552 * This clears the screen at startup. This is different from
1553 * the behavior of other versions of less. Disable it for now.
1560 * Create a complete, blank screen using "normal" colors.
1562 SETCOLORS(nm_fg_color, nm_bg_color);
1563 blanks = (char *) ecalloc(width+1, sizeof(char));
1564 for (col = 0; col < sc_width; col++)
1566 blanks[sc_width] = '\0';
1567 for (row = 0; row < sc_height; row++)
1574 #if MSDOS_COMPILER==WIN32C
1577 * Enable virtual terminal processing, if available.
1579 static void win32_init_vt_term(void)
1583 if (vt_enabled == 0 || (vt_enabled == 1 && con_out == con_out_ours))
1586 GetConsoleMode(con_out, &output_mode);
1587 vt_enabled = SetConsoleMode(con_out,
1588 output_mode | ENABLE_VIRTUAL_TERMINAL_PROCESSING);
1596 static void win32_deinit_vt_term(void)
1598 if (vt_enabled == 1 && con_out == con_out_save)
1599 SetConsoleMode(con_out, init_output_mode);
1603 * Termcap-like init with a private win32 console.
1605 static void win32_init_term(void)
1607 CONSOLE_SCREEN_BUFFER_INFO scr;
1610 if (con_out_save == INVALID_HANDLE_VALUE)
1613 GetConsoleScreenBufferInfo(con_out_save, &scr);
1615 if (con_out_ours == INVALID_HANDLE_VALUE)
1618 * Create our own screen buffer, so that we
1619 * may restore the original when done.
1621 con_out_ours = CreateConsoleScreenBuffer(
1622 GENERIC_WRITE | GENERIC_READ,
1623 FILE_SHARE_WRITE | FILE_SHARE_READ,
1624 (LPSECURITY_ATTRIBUTES) NULL,
1625 CONSOLE_TEXTMODE_BUFFER,
1629 size.X = scr.srWindow.Right - scr.srWindow.Left + 1;
1630 size.Y = scr.srWindow.Bottom - scr.srWindow.Top + 1;
1631 SetConsoleScreenBufferSize(con_out_ours, size);
1632 SetConsoleActiveScreenBuffer(con_out_ours);
1633 con_out = con_out_ours;
1637 * Restore the startup console.
1639 static void win32_deinit_term(void)
1641 if (con_out_save == INVALID_HANDLE_VALUE)
1644 (void) CloseHandle(con_out_ours);
1645 SetConsoleActiveScreenBuffer(con_out_save);
1646 con_out = con_out_save;
1652 static void do_tputs(char *str, int affcnt, int (*f_putc)(int))
1655 if (ttyin_name != NULL && f_putc == putchr)
1659 tputs(str, affcnt, f_putc);
1663 * Like tputs but we handle $<...> delay strings here because
1664 * some implementations of tputs don't perform delays correctly.
1666 static void ltputs(char *str, int affcnt, int (*f_putc)(int))
1668 while (str != NULL && *str != '\0')
1671 char *obrac = strstr(str, "$<");
1675 int slen = obrac - str;
1676 if (slen < sizeof(str2))
1679 /* Output first part of string (before "$<"). */
1680 memcpy(str2, str, slen);
1682 do_tputs(str2, affcnt, f_putc);
1684 /* Perform the delay. */
1685 delay = lstrtoi(str, &str, 10);
1687 if (ckd_mul(&delay, delay, affcnt))
1691 /* Skip past closing ">" at end of delay string. */
1692 str = strstr(str, ">");
1699 /* Pass the rest of the string to tputs and we're done. */
1700 do_tputs(str, affcnt, f_putc);
1704 #endif /* MSDOS_COMPILER */
1707 * Configure the terminal so mouse clicks and wheel moves
1708 * produce input to less.
1710 public void init_mouse(void)
1713 ltputs(sc_s_mousecap, sc_height, putchr);
1715 #if MSDOS_COMPILER==WIN32C
1716 SetConsoleMode(tty, ENABLE_PROCESSED_INPUT | ENABLE_MOUSE_INPUT
1717 | ENABLE_EXTENDED_FLAGS /* disable quick edit */);
1724 * Configure the terminal so mouse clicks and wheel moves
1725 * are handled by the system (so text can be selected, etc).
1727 public void deinit_mouse(void)
1730 ltputs(sc_e_mousecap, sc_height, putchr);
1732 #if MSDOS_COMPILER==WIN32C
1733 SetConsoleMode(tty, ENABLE_PROCESSED_INPUT | ENABLE_EXTENDED_FLAGS
1734 | (console_mode & ENABLE_QUICK_EDIT_MODE));
1740 * Initialize terminal
1742 public void init(void)
1744 clear_bot_if_needed();
1746 if (!(quit_if_one_screen && one_screen))
1750 ltputs(sc_init, sc_height, putchr);
1752 * Some terminals leave the cursor unmoved when switching
1753 * to the alt screen. To avoid having the text appear at
1754 * a seemingly random line on the alt screen, move to
1755 * lower left if we are using an alt screen.
1757 if (*sc_init != '\0' && *sc_deinit != '\0' && !no_alt_screen)
1762 ltputs(sc_s_keypad, sc_height, putchr);
1772 * This is nice to terminals with no alternate screen,
1773 * but with saved scrolled-off-the-top lines. This way,
1774 * no previous line is lost, but we start with a whole
1775 * screen to ourself.
1777 for (i = 1; i < sc_height; i++)
1782 #if MSDOS_COMPILER==WIN32C
1783 if (!(quit_if_one_screen && one_screen))
1794 win32_init_vt_term();
1803 * Deinitialize terminal
1805 public void deinit(void)
1810 if (!(quit_if_one_screen && one_screen))
1815 ltputs(sc_e_keypad, sc_height, putchr);
1817 ltputs(sc_deinit, sc_height, putchr);
1820 /* Restore system colors. */
1821 SETCOLORS(sy_fg_color, sy_bg_color);
1822 #if MSDOS_COMPILER==WIN32C
1823 win32_deinit_vt_term();
1824 if (!(quit_if_one_screen && one_screen))
1829 win32_deinit_term();
1832 /* Need clreol to make SETCOLORS take effect. */
1840 * Are we interactive (ie. writing to an initialized tty)?
1842 public int interactive(void)
1844 return (is_tty && init_done);
1847 static void assert_interactive(void)
1849 if (interactive()) return;
1854 * Home cursor (move to upper left corner of screen).
1856 public void home(void)
1858 assert_interactive();
1860 ltputs(sc_home, 1, putchr);
1863 _settextposition(1,1);
1868 public void dump_screen(void)
1871 SNPRINTF1(dump_cmd, sizeof(dump_cmd), ESCS"0;0;%dR", sc_width * sc_height);
1872 ltputs(dump_cmd, sc_height, putchr);
1878 * Add a blank line (called with cursor at home).
1879 * Should scroll the display down.
1881 public void add_line(void)
1883 assert_interactive();
1885 ltputs(sc_addline, sc_height, putchr);
1888 #if MSDOS_COMPILER==MSOFTC
1889 _scrolltextwindow(_GSCROLLDOWN);
1890 _settextposition(1,1);
1892 #if MSDOS_COMPILER==BORLANDC || MSDOS_COMPILER==DJGPPC
1893 movetext(1,1, sc_width,sc_height-1, 1,2);
1897 #if MSDOS_COMPILER==WIN32C
1900 SMALL_RECT rcSrc, rcClip;
1902 CONSOLE_SCREEN_BUFFER_INFO csbi;
1904 GetConsoleScreenBufferInfo(con_out,&csbi);
1906 /* The clip rectangle is the entire visible screen. */
1907 rcClip.Left = csbi.srWindow.Left;
1908 rcClip.Top = csbi.srWindow.Top;
1909 rcClip.Right = csbi.srWindow.Right;
1910 rcClip.Bottom = csbi.srWindow.Bottom;
1912 /* The source rectangle is the visible screen minus the last line. */
1916 /* Move the top left corner of the source window down one row. */
1917 new_org.X = rcSrc.Left;
1918 new_org.Y = rcSrc.Top + 1;
1920 /* Fill the right character and attributes. */
1921 fillchar.Char.AsciiChar = ' ';
1922 curr_attr = MAKEATTR(nm_fg_color, nm_bg_color);
1923 fillchar.Attributes = curr_attr;
1924 ScrollConsoleScreenBuffer(con_out, &rcSrc, &rcClip, new_org, &fillchar);
1925 _settextposition(1,1);
1935 * Remove the n topmost lines and scroll everything below it in the
1936 * window upward. This is needed to stop leaking the topmost line
1937 * into the scrollback buffer when we go down-one-line (in WIN32).
1939 public void remove_top(int n)
1941 #if MSDOS_COMPILER==WIN32C
1942 SMALL_RECT rcSrc, rcClip;
1945 CONSOLE_SCREEN_BUFFER_INFO csbi; /* to get buffer info */
1947 if (n >= sc_height - 1)
1956 GetConsoleScreenBufferInfo(con_out, &csbi);
1958 /* Get the extent of all-visible-rows-but-the-last. */
1959 rcSrc.Left = csbi.srWindow.Left;
1960 rcSrc.Top = csbi.srWindow.Top + n;
1961 rcSrc.Right = csbi.srWindow.Right;
1962 rcSrc.Bottom = csbi.srWindow.Bottom;
1964 /* Get the clip rectangle. */
1965 rcClip.Left = rcSrc.Left;
1966 rcClip.Top = csbi.srWindow.Top;
1967 rcClip.Right = rcSrc.Right;
1968 rcClip.Bottom = rcSrc.Bottom ;
1970 /* Move the source window up n rows. */
1971 new_org.X = rcSrc.Left;
1972 new_org.Y = rcSrc.Top - n;
1974 /* Fill the right character and attributes. */
1975 fillchar.Char.AsciiChar = ' ';
1976 curr_attr = MAKEATTR(nm_fg_color, nm_bg_color);
1977 fillchar.Attributes = curr_attr;
1979 ScrollConsoleScreenBuffer(con_out, &rcSrc, &rcClip, new_org, &fillchar);
1981 /* Position cursor on first blank line. */
1982 goto_line(sc_height - n - 1);
1987 #if MSDOS_COMPILER==WIN32C
1991 static void win32_clear(void)
1994 * This will clear only the currently visible rows of the NT
1995 * console buffer, which means none of the precious scrollback
1996 * rows are touched making for faster scrolling. Note that, if
1997 * the window has fewer columns than the console buffer (i.e.
1998 * there is a horizontal scrollbar as well), the entire width
1999 * of the visible rows will be cleared.
2004 CONSOLE_SCREEN_BUFFER_INFO csbi;
2006 /* get the number of cells in the current buffer */
2007 GetConsoleScreenBufferInfo(con_out, &csbi);
2008 winsz = csbi.dwSize.X * (csbi.srWindow.Bottom - csbi.srWindow.Top + 1);
2010 topleft.Y = csbi.srWindow.Top;
2012 curr_attr = MAKEATTR(nm_fg_color, nm_bg_color);
2013 FillConsoleOutputCharacter(con_out, ' ', winsz, topleft, &nchars);
2014 FillConsoleOutputAttribute(con_out, curr_attr, winsz, topleft, &nchars);
2018 * Remove the n topmost lines and scroll everything below it in the
2021 public void win32_scroll_up(int n)
2023 SMALL_RECT rcSrc, rcClip;
2029 CONSOLE_SCREEN_BUFFER_INFO csbi;
2034 if (n >= sc_height - 1)
2037 _settextposition(1,1);
2041 /* Get the extent of what will remain visible after scrolling. */
2042 GetConsoleScreenBufferInfo(con_out, &csbi);
2043 rcSrc.Left = csbi.srWindow.Left;
2044 rcSrc.Top = csbi.srWindow.Top + n;
2045 rcSrc.Right = csbi.srWindow.Right;
2046 rcSrc.Bottom = csbi.srWindow.Bottom;
2048 /* Get the clip rectangle. */
2049 rcClip.Left = rcSrc.Left;
2050 rcClip.Top = csbi.srWindow.Top;
2051 rcClip.Right = rcSrc.Right;
2052 rcClip.Bottom = rcSrc.Bottom ;
2054 /* Move the source text to the top of the screen. */
2055 new_org.X = rcSrc.Left;
2056 new_org.Y = rcClip.Top;
2058 /* Fill the right character and attributes. */
2059 fillchar.Char.AsciiChar = ' ';
2060 fillchar.Attributes = MAKEATTR(nm_fg_color, nm_bg_color);
2062 /* Scroll the window. */
2063 SetConsoleTextAttribute(con_out, fillchar.Attributes);
2064 ScrollConsoleScreenBuffer(con_out, &rcSrc, &rcClip, new_org, &fillchar);
2066 /* Clear remaining lines at bottom. */
2067 topleft.X = csbi.dwCursorPosition.X;
2068 topleft.Y = rcSrc.Bottom - n;
2069 size = (n * csbi.dwSize.X) + (rcSrc.Right - topleft.X);
2070 FillConsoleOutputCharacter(con_out, ' ', size, topleft,
2072 FillConsoleOutputAttribute(con_out, fillchar.Attributes, size, topleft,
2074 SetConsoleTextAttribute(con_out, curr_attr);
2076 /* Move cursor n lines up from where it was. */
2077 csbi.dwCursorPosition.Y -= n;
2078 SetConsoleCursorPosition(con_out, csbi.dwCursorPosition);
2083 * Move cursor to lower left corner of screen.
2085 public void lower_left(void)
2087 assert_interactive();
2089 ltputs(sc_lower_left, 1, putchr);
2092 _settextposition(sc_height, 1);
2097 * Move cursor to left position of current line.
2099 public void line_left(void)
2101 assert_interactive();
2103 ltputs(sc_return, 1, putchr);
2108 #if MSDOS_COMPILER==WIN32C
2110 CONSOLE_SCREEN_BUFFER_INFO scr;
2111 GetConsoleScreenBufferInfo(con_out, &scr);
2112 row = scr.dwCursorPosition.Y - scr.srWindow.Top + 1;
2115 #if MSDOS_COMPILER==BORLANDC || MSDOS_COMPILER==DJGPPC
2119 struct rccoord tpos = _gettextposition();
2124 _settextposition(row, 1);
2130 * Check if the console size has changed and reset internals
2131 * (in lieu of SIGWINCH for WIN32).
2133 public void check_winch(void)
2135 #if MSDOS_COMPILER==WIN32C
2136 CONSOLE_SCREEN_BUFFER_INFO scr;
2139 if (con_out == INVALID_HANDLE_VALUE)
2143 GetConsoleScreenBufferInfo(con_out, &scr);
2144 size.Y = scr.srWindow.Bottom - scr.srWindow.Top + 1;
2145 size.X = scr.srWindow.Right - scr.srWindow.Left + 1;
2146 if (size.Y != sc_height || size.X != sc_width)
2150 if (!no_init && con_out_ours == con_out)
2151 SetConsoleScreenBufferSize(con_out, size);
2153 wscroll = (sc_height + 1) / 2;
2160 * Goto a specific line on the screen.
2162 public void goto_line(int sindex)
2164 assert_interactive();
2166 ltputs(tgoto(sc_move, 0, sindex), 1, putchr);
2169 _settextposition(sindex+1, 1);
2173 #if MSDOS_COMPILER==MSOFTC || MSDOS_COMPILER==BORLANDC
2175 * Create an alternate screen which is all white.
2176 * This screen is used to create a "flash" effect, by displaying it
2177 * briefly and then switching back to the normal screen.
2178 * {{ Yuck! There must be a better way to get a visual bell. }}
2180 static void create_flash(void)
2182 #if MSDOS_COMPILER==MSOFTC
2183 struct videoconfig w;
2187 _getvideoconfig(&w);
2188 videopages = w.numvideopages;
2191 at_enter(AT_STANDOUT);
2196 at_enter(AT_STANDOUT);
2197 blanks = (char *) ecalloc(w.numtextcols, sizeof(char));
2198 for (col = 0; col < w.numtextcols; col++)
2200 for (row = w.numtextrows; row > 0; row--)
2201 _outmem(blanks, w.numtextcols);
2208 #if MSDOS_COMPILER==BORLANDC
2211 whitescreen = (unsigned short *)
2212 malloc(sc_width * sc_height * sizeof(short));
2213 if (whitescreen == NULL)
2215 for (n = 0; n < sc_width * sc_height; n++)
2216 whitescreen[n] = 0x7020;
2221 #endif /* MSDOS_COMPILER */
2224 * Output the "visual bell", if there is one.
2226 public void vbell(void)
2231 if (*sc_visual_bell == '\0')
2233 ltputs(sc_visual_bell, sc_height, putchr);
2235 #if MSDOS_COMPILER==DJGPPC
2238 #if MSDOS_COMPILER==MSOFTC
2240 * Create a flash screen on the second video page.
2241 * Switch to that page, then switch back.
2251 #if MSDOS_COMPILER==BORLANDC
2252 unsigned short *currscreen;
2255 * Get a copy of the current screen.
2256 * Display the flash screen.
2257 * Then restore the old screen.
2261 if (whitescreen == NULL)
2263 currscreen = (unsigned short *)
2264 malloc(sc_width * sc_height * sizeof(short));
2265 if (currscreen == NULL) return;
2266 gettext(1, 1, sc_width, sc_height, currscreen);
2267 puttext(1, 1, sc_width, sc_height, whitescreen);
2269 puttext(1, 1, sc_width, sc_height, currscreen);
2272 #if MSDOS_COMPILER==WIN32C
2273 /* paint screen with an inverse color */
2276 /* leave it displayed for 100 msec. */
2279 /* restore with a redraw */
2291 static void beep(void)
2294 putchr(CONTROL('G'));
2296 #if MSDOS_COMPILER==WIN32C
2305 * Ring the terminal bell.
2307 public void bell(void)
2309 if (quiet == VERY_QUIET)
2318 public void clear(void)
2320 assert_interactive();
2322 ltputs(sc_clear, sc_height, putchr);
2325 #if MSDOS_COMPILER==WIN32C
2328 _clearscreen(_GCLEARSCREEN);
2334 * Clear from the cursor to the end of the cursor's line.
2335 * {{ This must not move the cursor. }}
2337 public void clear_eol(void)
2339 /* assert_interactive();*/
2341 ltputs(sc_eol_clear, 1, putchr);
2343 #if MSDOS_COMPILER==MSOFTC
2346 struct rccoord tpos;
2350 * Save current state.
2352 tpos = _gettextposition();
2353 _gettextwindow(&top, &left, &bot, &right);
2355 * Set a temporary window to the current line,
2356 * from the cursor's position to the right edge of the screen.
2357 * Then clear that window.
2359 _settextwindow(tpos.row, tpos.col, tpos.row, sc_width);
2360 _clearscreen(_GWINDOW);
2364 _settextwindow(top, left, bot, right);
2365 _settextposition(tpos.row, tpos.col);
2367 #if MSDOS_COMPILER==BORLANDC || MSDOS_COMPILER==DJGPPC
2371 #if MSDOS_COMPILER==WIN32C
2374 CONSOLE_SCREEN_BUFFER_INFO scr;
2377 memset(&scr, 0, sizeof(scr));
2378 GetConsoleScreenBufferInfo(con_out, &scr);
2379 cpos.X = scr.dwCursorPosition.X;
2380 cpos.Y = scr.dwCursorPosition.Y;
2381 curr_attr = MAKEATTR(nm_fg_color, nm_bg_color);
2382 FillConsoleOutputAttribute(con_out, curr_attr,
2383 scr.dwSize.X - cpos.X, cpos, &nchars);
2384 FillConsoleOutputCharacter(con_out, ' ',
2385 scr.dwSize.X - cpos.X, cpos, &nchars);
2393 * Clear the current line.
2394 * Clear the screen if there's off-screen memory below the display.
2396 static void clear_eol_bot(void)
2398 assert_interactive();
2403 ltputs(sc_eos_clear, 1, putchr);
2405 ltputs(sc_eol_clear, 1, putchr);
2410 * Clear the bottom line of the display.
2411 * Leave the cursor at the beginning of the bottom line.
2413 public void clear_bot(void)
2416 * If we're in a non-normal attribute mode, temporarily exit
2417 * the mode while we do the clear. Some terminals fill the
2418 * cleared area with the current attribute.
2425 if (attrmode == AT_NORMAL)
2429 int saved_attrmode = attrmode;
2433 at_enter(saved_attrmode);
2438 * Color string may be "x[y]" where x and y are 4-bit color chars,
2439 * or "N[.M]" where N and M are decimal integers>
2440 * Any of x,y,N,M may also be "-" to mean "unchanged".
2444 * Parse a 4-bit color char.
2446 static int parse_color4(char ch)
2451 case 'r': return CV_RED;
2452 case 'g': return CV_GREEN;
2453 case 'y': return CV_RED|CV_GREEN;
2454 case 'b': return CV_BLUE;
2455 case 'm': return CV_RED|CV_BLUE;
2456 case 'c': return CV_GREEN|CV_BLUE;
2457 case 'w': return CV_RED|CV_GREEN|CV_BLUE;
2458 case 'K': return 0|CV_BRIGHT;
2459 case 'R': return CV_RED|CV_BRIGHT;
2460 case 'G': return CV_GREEN|CV_BRIGHT;
2461 case 'Y': return CV_RED|CV_GREEN|CV_BRIGHT;
2462 case 'B': return CV_BLUE|CV_BRIGHT;
2463 case 'M': return CV_RED|CV_BLUE|CV_BRIGHT;
2464 case 'C': return CV_GREEN|CV_BLUE|CV_BRIGHT;
2465 case 'W': return CV_RED|CV_GREEN|CV_BLUE|CV_BRIGHT;
2466 case '-': return CV_NOCHANGE;
2467 default: return CV_ERROR;
2472 * Parse a color as a decimal integer.
2474 static int parse_color6(char **ps)
2483 int color = lstrtoi(ops, ps, 10);
2484 if (color < 0 || *ps == ops)
2491 * Parse a color pair and return the foreground/background values.
2492 * Return type of color specifier:
2493 * CV_4BIT: fg/bg values are OR of CV_{RGB} bits.
2494 * CV_6BIT: fg/bg values are integers entered by user.
2496 public COLOR_TYPE parse_color(char *str, int *p_fg, int *p_bg)
2500 COLOR_TYPE type = CT_NULL;
2502 if (str == NULL || *str == '\0')
2505 str++; /* ignore leading + */
2507 fg = parse_color4(str[0]);
2508 bg = parse_color4((strlen(str) < 2) ? '-' : str[1]);
2509 if (fg != CV_ERROR && bg != CV_ERROR)
2513 fg = parse_color6(&str);
2514 bg = (fg != CV_ERROR && *str++ == '.') ? parse_color6(&str) : CV_NOCHANGE;
2515 if (fg != CV_ERROR && bg != CV_ERROR)
2518 if (p_fg != NULL) *p_fg = fg;
2519 if (p_bg != NULL) *p_bg = bg;
2525 static int sgr_color(int color)
2530 case CV_RED: return 31;
2531 case CV_GREEN: return 32;
2532 case CV_RED|CV_GREEN: return 33;
2533 case CV_BLUE: return 34;
2534 case CV_RED|CV_BLUE: return 35;
2535 case CV_GREEN|CV_BLUE: return 36;
2536 case CV_RED|CV_GREEN|CV_BLUE: return 37;
2538 case CV_BRIGHT: return 90;
2539 case CV_RED|CV_BRIGHT: return 91;
2540 case CV_GREEN|CV_BRIGHT: return 92;
2541 case CV_RED|CV_GREEN|CV_BRIGHT: return 93;
2542 case CV_BLUE|CV_BRIGHT: return 94;
2543 case CV_RED|CV_BLUE|CV_BRIGHT: return 95;
2544 case CV_GREEN|CV_BLUE|CV_BRIGHT: return 96;
2545 case CV_RED|CV_GREEN|CV_BLUE|CV_BRIGHT: return 97;
2547 default: return color;
2551 static void tput_fmt(char *fmt, int color, int (*f_putc)(int))
2553 char buf[INT_STRLEN_BOUND(int)+16];
2554 if (color == attrcolor)
2556 SNPRINTF1(buf, sizeof(buf), fmt, color);
2557 ltputs(buf, 1, f_putc);
2561 static void tput_color(char *str, int (*f_putc)(int))
2566 if (str != NULL && strcmp(str, "*") == 0)
2568 /* Special case: reset to normal */
2569 tput_fmt(ESCS"[m", -1, f_putc);
2572 switch (parse_color(str, &fg, &bg))
2576 tput_fmt(ESCS"[%dm", sgr_color(fg), f_putc);
2578 tput_fmt(ESCS"[%dm", sgr_color(bg)+10, f_putc);
2582 tput_fmt(ESCS"[38;5;%dm", fg, f_putc);
2584 tput_fmt(ESCS"[48;5;%dm", bg, f_putc);
2591 static void tput_inmode(char *mode_str, int attr, int attr_bit, int (*f_putc)(int))
2594 if ((attr & attr_bit) == 0)
2596 color_str = get_color_map(attr_bit);
2597 if (color_str == NULL || *color_str == '\0' || *color_str == '+')
2599 ltputs(mode_str, 1, f_putc);
2600 if (color_str == NULL || *color_str++ != '+')
2603 /* Color overrides mode string */
2604 tput_color(color_str, f_putc);
2607 static void tput_outmode(char *mode_str, int attr_bit, int (*f_putc)(int))
2609 if ((attrmode & attr_bit) == 0)
2611 ltputs(mode_str, 1, f_putc);
2614 #else /* MSDOS_COMPILER */
2616 #if MSDOS_COMPILER==WIN32C
2617 static int WIN32put_fmt(char *fmt, int color)
2619 char buf[INT_STRLEN_BOUND(int)+16];
2620 int len = SNPRINTF1(buf, sizeof(buf), fmt, color);
2621 WIN32textout(buf, len);
2626 static int win_set_color(int attr)
2631 char *str = get_color_map(attr);
2632 if (str == NULL || str[0] == '\0')
2634 switch (parse_color(str, &fg, &bg))
2637 if (fg >= 0 && bg >= 0)
2651 #if MSDOS_COMPILER==WIN32C
2656 out = WIN32put_fmt(ESCS"[38;5;%dm", fg);
2658 out = WIN32put_fmt(ESCS"[48;5;%dm", bg);
2668 #endif /* MSDOS_COMPILER */
2670 public void at_enter(int attr)
2672 attr = apply_at_specials(attr);
2674 /* The one with the most priority is last. */
2675 tput_inmode(sc_u_in, attr, AT_UNDERLINE, putchr);
2676 tput_inmode(sc_b_in, attr, AT_BOLD, putchr);
2677 tput_inmode(sc_bl_in, attr, AT_BLINK, putchr);
2678 /* Don't use standout and color at the same time. */
2679 if (use_color && (attr & AT_COLOR))
2680 tput_color(get_color_map(attr), putchr);
2682 tput_inmode(sc_s_in, attr, AT_STANDOUT, putchr);
2685 /* The one with the most priority is first. */
2686 if ((attr & AT_COLOR) && use_color)
2688 win_set_color(attr);
2689 } else if (attr & AT_STANDOUT)
2691 SETCOLORS(so_fg_color, so_bg_color);
2692 } else if (attr & AT_BLINK)
2694 SETCOLORS(bl_fg_color, bl_bg_color);
2695 } else if (attr & AT_BOLD)
2697 SETCOLORS(bo_fg_color, bo_bg_color);
2698 } else if (attr & AT_UNDERLINE)
2700 SETCOLORS(ul_fg_color, ul_bg_color);
2706 public void at_exit(void)
2709 /* Undo things in the reverse order we did them. */
2710 tput_color("*", putchr);
2711 tput_outmode(sc_s_out, AT_STANDOUT, putchr);
2712 tput_outmode(sc_bl_out, AT_BLINK, putchr);
2713 tput_outmode(sc_b_out, AT_BOLD, putchr);
2714 tput_outmode(sc_u_out, AT_UNDERLINE, putchr);
2717 SETCOLORS(nm_fg_color, nm_bg_color);
2719 attrmode = AT_NORMAL;
2722 public void at_switch(int attr)
2724 int new_attrmode = apply_at_specials(attr);
2725 int ignore_modes = AT_ANSI;
2727 if ((new_attrmode & ~ignore_modes) != (attrmode & ~ignore_modes))
2734 public int is_at_equiv(int attr1, int attr2)
2736 attr1 = apply_at_specials(attr1);
2737 attr2 = apply_at_specials(attr2);
2739 return (attr1 == attr2);
2742 public int apply_at_specials(int attr)
2744 if (attr & AT_BINARY)
2746 if (attr & AT_HILITE)
2747 attr |= AT_STANDOUT;
2748 attr &= ~(AT_BINARY|AT_HILITE);
2754 * Output a plain backspace, without erasing the previous char.
2756 public void putbs(void)
2763 ltputs(sc_backspace, 1, putchr);
2769 #if MSDOS_COMPILER==MSOFTC
2770 struct rccoord tpos;
2771 tpos = _gettextposition();
2775 #if MSDOS_COMPILER==BORLANDC || MSDOS_COMPILER==DJGPPC
2779 #if MSDOS_COMPILER==WIN32C
2780 CONSOLE_SCREEN_BUFFER_INFO scr;
2781 GetConsoleScreenBufferInfo(con_out, &scr);
2782 row = scr.dwCursorPosition.Y - scr.srWindow.Top + 1;
2783 col = scr.dwCursorPosition.X - scr.srWindow.Left + 1;
2790 _settextposition(row, col-1);
2791 #endif /* MSDOS_COMPILER */
2795 #if MSDOS_COMPILER==WIN32C
2797 * Determine whether an input character is waiting to be read.
2799 public int win32_kbhit(void)
2804 if (keyCount > 0 || win_unget_pending)
2807 currentKey.ascii = 0;
2808 currentKey.scan = 0;
2810 if (x11mouseCount > 0)
2812 currentKey.ascii = x11mousebuf[x11mousePos++];
2819 * Wait for a real key-down event, but
2820 * ignore SHIFT and CONTROL key events.
2824 PeekConsoleInputW(tty, &ip, 1, &read);
2827 ReadConsoleInputW(tty, &ip, 1, &read);
2828 /* generate an X11 mouse sequence from the mouse event */
2829 if (mousecap && ip.EventType == MOUSE_EVENT &&
2830 ip.Event.MouseEvent.dwEventFlags != MOUSE_MOVED)
2832 x11mousebuf[3] = X11MOUSE_OFFSET + ip.Event.MouseEvent.dwMousePosition.X + 1;
2833 x11mousebuf[4] = X11MOUSE_OFFSET + ip.Event.MouseEvent.dwMousePosition.Y + 1;
2834 switch (ip.Event.MouseEvent.dwEventFlags)
2836 case 0: /* press or release */
2837 if (ip.Event.MouseEvent.dwButtonState == 0)
2838 x11mousebuf[2] = X11MOUSE_OFFSET + X11MOUSE_BUTTON_REL;
2839 else if (ip.Event.MouseEvent.dwButtonState & (FROM_LEFT_3RD_BUTTON_PRESSED | FROM_LEFT_4TH_BUTTON_PRESSED))
2842 x11mousebuf[2] = X11MOUSE_OFFSET + X11MOUSE_BUTTON1 + ((int)ip.Event.MouseEvent.dwButtonState << 1);
2845 x11mousebuf[2] = X11MOUSE_OFFSET + (((int)ip.Event.MouseEvent.dwButtonState < 0) ? X11MOUSE_WHEEL_DOWN : X11MOUSE_WHEEL_UP);
2852 currentKey.ascii = ESC;
2856 } while (ip.EventType != KEY_EVENT ||
2857 ip.Event.KeyEvent.bKeyDown != TRUE ||
2858 (ip.Event.KeyEvent.wVirtualScanCode == 0 && ip.Event.KeyEvent.uChar.UnicodeChar == 0) ||
2859 ((ip.Event.KeyEvent.dwControlKeyState & (RIGHT_ALT_PRESSED|LEFT_CTRL_PRESSED)) == (RIGHT_ALT_PRESSED|LEFT_CTRL_PRESSED) && ip.Event.KeyEvent.uChar.UnicodeChar == 0) ||
2860 ip.Event.KeyEvent.wVirtualKeyCode == VK_KANJI ||
2861 ip.Event.KeyEvent.wVirtualKeyCode == VK_SHIFT ||
2862 ip.Event.KeyEvent.wVirtualKeyCode == VK_CONTROL ||
2863 ip.Event.KeyEvent.wVirtualKeyCode == VK_MENU);
2865 currentKey.unicode = ip.Event.KeyEvent.uChar.UnicodeChar;
2866 currentKey.ascii = ip.Event.KeyEvent.uChar.AsciiChar;
2867 currentKey.scan = ip.Event.KeyEvent.wVirtualScanCode;
2868 keyCount = ip.Event.KeyEvent.wRepeatCount;
2870 if (ip.Event.KeyEvent.dwControlKeyState &
2871 (LEFT_ALT_PRESSED | RIGHT_ALT_PRESSED))
2873 switch (currentKey.scan)
2875 case PCK_ALT_E: /* letter 'E' */
2876 currentKey.ascii = 0;
2879 } else if (ip.Event.KeyEvent.dwControlKeyState &
2880 (LEFT_CTRL_PRESSED | RIGHT_CTRL_PRESSED))
2882 switch (currentKey.scan)
2884 case PCK_RIGHT: /* right arrow */
2885 currentKey.scan = PCK_CTL_RIGHT;
2887 case PCK_LEFT: /* left arrow */
2888 currentKey.scan = PCK_CTL_LEFT;
2890 case PCK_DELETE: /* delete */
2891 currentKey.scan = PCK_CTL_DELETE;
2894 } else if (ip.Event.KeyEvent.dwControlKeyState & SHIFT_PRESSED)
2896 switch (currentKey.scan)
2898 case PCK_SHIFT_TAB: /* tab */
2899 currentKey.ascii = 0;
2908 * Read a character from the keyboard.
2911 * - WIN32getch API should be int like libc (with unsigned char values or -1).
2912 * - The unicode code below can return 0 - incorrectly indicating scan code.
2913 * - UTF16-LE surrogate pairs don't work (and return 0).
2914 * - If win32_kbhit returns true then WIN32getch should never block, but it
2915 * will block till the next keypress if it's numlock/capslock scan code.
2917 public char WIN32getch(void)
2920 static unsigned char utf8[UTF8_MAX_LENGTH];
2921 static int utf8_size = 0;
2922 static int utf8_next_byte = 0;
2924 if (win_unget_pending)
2926 win_unget_pending = FALSE;
2927 return (char) win_unget_data;
2930 // Return the rest of multibyte character from the prior call
2931 if (utf8_next_byte < utf8_size)
2933 ascii = utf8[utf8_next_byte++];
2938 if (pending_scancode)
2940 pending_scancode = 0;
2941 return ((char)(currentKey.scan & 0x00FF));
2945 while (!win32_kbhit())
2952 // If multibyte character, return its first byte
2953 if (currentKey.unicode > 0x7f)
2955 utf8_size = WideCharToMultiByte(CP_UTF8, 0, ¤tKey.unicode, 1, (LPSTR) &utf8, sizeof(utf8), NULL, NULL);
2961 ascii = currentKey.ascii;
2963 * On PC's, the extended keys return a 2 byte sequence beginning
2964 * with '00', so if the ascii code is 00, the next byte will be
2965 * the lsb of the scan code.
2967 pending_scancode = (ascii == 0x00);
2968 } while (pending_scancode &&
2969 (currentKey.scan == PCK_CAPS_LOCK || currentKey.scan == PCK_NUM_LOCK));
2975 * Make the next call to WIN32getch return ch without changing the queue state.
2977 public void WIN32ungetch(int ch)
2979 win_unget_pending = TRUE;
2980 win_unget_data = ch;
2987 public void WIN32setcolors(int fg, int bg)
2994 public void WIN32textout(char *text, int len)
2996 #if MSDOS_COMPILER==WIN32C
3001 * We've got UTF-8 text in a non-UTF-8 console. Convert it to
3002 * wide and use WriteConsoleW.
3005 len = MultiByteToWideChar(CP_UTF8, 0, text, len, wtext,
3006 sizeof(wtext)/sizeof(*wtext));
3007 WriteConsoleW(con_out, wtext, len, &written, NULL);
3009 WriteConsole(con_out, text, len, &written, NULL);