1 /*
2 * Copyright (C) 1984-2025 Mark Nudelman
3 *
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.
6 *
7 * For more information, see the README file.
8 */
9
10
11 /*
12 * Routines which deal with the characteristics of the terminal.
13 * Uses termcap to be as terminal-independent as possible.
14 */
15
16 #include "less.h"
17 #include "cmd.h"
18
19 #if MSDOS_COMPILER
20 #include "pckeys.h"
21 #if MSDOS_COMPILER==MSOFTC
22 #include <graph.h>
23 #else
24 #if MSDOS_COMPILER==BORLANDC || MSDOS_COMPILER==DJGPPC
25 #include <conio.h>
26 #if MSDOS_COMPILER==DJGPPC
27 #include <pc.h>
28 extern int fd0;
29 #endif
30 #else
31 #if MSDOS_COMPILER==WIN32C
32 #include <windows.h>
33 #endif
34 #endif
35 #endif
36 #include <time.h>
37
38 #ifndef FOREGROUND_BLUE
39 #define FOREGROUND_BLUE 0x0001
40 #endif
41 #ifndef FOREGROUND_GREEN
42 #define FOREGROUND_GREEN 0x0002
43 #endif
44 #ifndef FOREGROUND_RED
45 #define FOREGROUND_RED 0x0004
46 #endif
47 #ifndef FOREGROUND_INTENSITY
48 #define FOREGROUND_INTENSITY 0x0008
49 #endif
50
51 #else
52
53 #if HAVE_SYS_IOCTL_H
54 #include <sys/ioctl.h>
55 #endif
56
57 #if HAVE_TERMIOS_H && HAVE_TERMIOS_FUNCS
58 #include <termios.h>
59 #else
60 #if HAVE_TERMIO_H
61 #include <termio.h>
62 #else
63 #if HAVE_SGSTAT_H
64 #include <sgstat.h>
65 #else
66 #include <sgtty.h>
67 #endif
68 #endif
69 #endif
70
71 #if HAVE_TERMINFO && !USE_TERMCAP
72 #define USE_TERMINFO 1
73 #endif
74
75 #if USE_TERMINFO
76 #include <curses.h>
77 #include <term.h>
78 #else
79 #if HAVE_NCURSESW_TERMCAP_H
80 #include <ncursesw/termcap.h>
81 #else
82 #if HAVE_NCURSES_TERMCAP_H
83 #include <ncurses/termcap.h>
84 #else
85 #if HAVE_TERMCAP_H
86 #include <termcap.h>
87 #endif
88 #endif
89 #endif
90 #endif
91 #ifdef _OSK
92 #include <signal.h>
93 #endif
94 #if OS2
95 #include <sys/signal.h>
96 #include "pckeys.h"
97 #endif
98 #if HAVE_SYS_STREAM_H
99 #include <sys/stream.h>
100 #endif
101 #if HAVE_SYS_PTEM_H
102 #include <sys/ptem.h>
103 #endif
104
105 #endif /* MSDOS_COMPILER */
106
107 /*
108 * Check for broken termios package that forces you to manually
109 * set the line discipline.
110 */
111 #ifdef __ultrix__
112 #define MUST_SET_LINE_DISCIPLINE 1
113 #else
114 #define MUST_SET_LINE_DISCIPLINE 0
115 #endif
116
117 #if OS2
118 #define DEFAULT_TERM "ansi"
119 static char *windowid;
120 #else
121 #define DEFAULT_TERM "unknown"
122 #endif
123
124 #if MSDOS_COMPILER==MSOFTC
125 static int videopages;
126 static long msec_loops;
127 static int flash_created = 0;
128 #define SET_FG_COLOR(fg) _settextcolor(fg)
129 #define SET_BG_COLOR(bg) _setbkcolor(bg)
130 #define SETCOLORS(fg,bg) { SET_FG_COLOR(fg); SET_BG_COLOR(bg); }
131 #endif
132
133 #if MSDOS_COMPILER==BORLANDC
134 static unsigned short *whitescreen;
135 static int flash_created = 0;
136 #endif
137 #if MSDOS_COMPILER==BORLANDC || MSDOS_COMPILER==DJGPPC
138 #define _settextposition(y,x) gotoxy(x,y)
139 #define _clearscreen(m) clrscr()
140 #define _outtext(s) cputs(s)
141 #define SET_FG_COLOR(fg) textcolor(fg)
142 #define SET_BG_COLOR(bg) textbackground(bg)
143 #define SETCOLORS(fg,bg) { SET_FG_COLOR(fg); SET_BG_COLOR(bg); }
144 extern int sc_height;
145 #endif
146
147 #if MSDOS_COMPILER==WIN32C
148 #define UTF8_MAX_LENGTH 4
149
150 static WORD curr_attr;
151
152 static HANDLE con_out_save = INVALID_HANDLE_VALUE; /* previous console */
153 static HANDLE con_out_ours = INVALID_HANDLE_VALUE; /* our own */
154 HANDLE con_out = INVALID_HANDLE_VALUE; /* current console */
155
156 extern int utf_mode;
157 extern lbool quitting;
158 static void win32_init_term();
159 static void win32_deinit_term();
160
161 #ifndef ENABLE_VIRTUAL_TERMINAL_PROCESSING
162 #define ENABLE_VIRTUAL_TERMINAL_PROCESSING 4
163 #endif
164
165 #define FG_COLORS (FOREGROUND_RED | FOREGROUND_GREEN | FOREGROUND_BLUE | FOREGROUND_INTENSITY)
166 #define BG_COLORS (BACKGROUND_RED | BACKGROUND_GREEN | BACKGROUND_BLUE | BACKGROUND_INTENSITY)
167 #define MAKEATTR(fg,bg) ((WORD)((fg)|((bg)<<4)))
168 #define APPLY_COLORS() { if (SetConsoleTextAttribute(con_out, curr_attr) == 0) \
169 error("SETCOLORS failed", NULL_PARG); }
170 #define SET_FG_COLOR(fg) { curr_attr &= ~0x0f; curr_attr |= (fg); APPLY_COLORS(); }
171 #define SET_BG_COLOR(bg) { curr_attr &= ~0xf0; curr_attr |= ((bg)<<4); APPLY_COLORS(); }
172 #define SETCOLORS(fg,bg) { curr_attr = MAKEATTR(fg,bg); APPLY_COLORS(); }
173 #endif
174
175 #if MSDOS_COMPILER
176 public int nm_fg_color = CV_ERROR; /* Color of normal text */
177 public int nm_bg_color = CV_ERROR;
178 public int nm_attr = 0;
179 public int bo_fg_color = CV_ERROR; /* Color of bold text */
180 public int bo_bg_color = CV_ERROR;
181 public int bo_attr = 0;
182 public int ul_fg_color = CV_ERROR; /* Color of underlined text */
183 public int ul_bg_color = CV_ERROR;
184 public int ul_attr = 0;
185 public int so_fg_color = CV_ERROR; /* Color of standout text */
186 public int so_bg_color = CV_ERROR;
187 public int so_attr = 0;
188 public int bl_fg_color = CV_ERROR; /* Color of blinking text */
189 public int bl_bg_color = CV_ERROR;
190 public int bl_attr = 0;
191 static int sy_fg_color; /* Color of system text (before less) */
192 static int sy_bg_color;
193 public int sgr_mode; /* Honor ANSI sequences rather than using above */
194 #if MSDOS_COMPILER==WIN32C
195 static DWORD init_console_output_mode;
196 extern DWORD init_console_input_mode;
197 extern DWORD curr_console_input_mode;
198 extern DWORD base_console_input_mode;
199 extern DWORD mouse_console_input_mode;
200 public int vt_enabled = -1; /* Is virtual terminal processing available? */
201 #endif
202 #else
203
204 /*
205 * These two variables are sometimes defined in,
206 * and needed by, the termcap library.
207 */
208 #if USE_TERMINFO
209 #undef HAVE_OSPEED
210 #else
211 #if MUST_DEFINE_OSPEED
212 extern short ospeed; /* Terminal output baud rate */
213 extern char PC; /* Pad character */
214 #endif
215 #ifdef _OSK
216 short ospeed;
217 char PC_, *UP, *BC;
218 #endif
219 #endif
220
221 /*
222 * Strings passed to tputs() to do various terminal functions.
223 */
224 static constant char
225 #if HAVE_OSPEED
226 *sc_pad, /* Pad string */
227 #endif
228 *sc_home, /* Cursor home */
229 *sc_addline, /* Add line, scroll down following lines */
230 *sc_lower_left, /* Cursor to last line, first column */
231 *sc_return, /* Cursor to beginning of current line */
232 *sc_move, /* General cursor positioning */
233 *sc_clear, /* Clear screen */
234 *sc_eol_clear, /* Clear to end of line */
235 *sc_eos_clear, /* Clear to end of screen */
236 *sc_s_in, /* Enter standout (highlighted) mode */
237 *sc_s_out, /* Exit standout mode */
238 *sc_u_in, /* Enter underline mode */
239 *sc_u_out, /* Exit underline mode */
240 *sc_b_in, /* Enter bold mode */
241 *sc_b_out, /* Exit bold mode */
242 *sc_bl_in, /* Enter blink mode */
243 *sc_bl_out, /* Exit blink mode */
244 *sc_visual_bell, /* Visual bell (flash screen) sequence */
245 *sc_backspace, /* Backspace cursor */
246 *sc_s_keypad, /* Start keypad mode */
247 *sc_e_keypad, /* End keypad mode */
248 *sc_s_mousecap, /* Start mouse capture mode */
249 *sc_e_mousecap, /* End mouse capture mode */
250 *sc_s_bracketed_paste, /* Start bracketed paste mode */
251 *sc_e_bracketed_paste, /* End bracketed paste mode */
252 *sc_suspend, /* Suspend screen updates */
253 *sc_resume, /* Resume screen updates */
254 *sc_init, /* Startup terminal initialization */
255 *sc_deinit; /* Exit terminal de-initialization */
256
257 static int attrcolor = -1;
258 #endif
259
260 /* term_init has been called; terminal is ready for use by less */
261 static lbool term_init_done = FALSE;
262 public lbool term_init_ever = FALSE;
263
264 public int auto_wrap; /* Terminal does \r\n when write past margin */
265 public int defer_wrap; /* After printing char in last column, doesn't wrap until next char */
266 public int erase_char; /* The user's erase char */
267 public int erase2_char; /* The user's other erase char */
268 public int kill_char; /* The user's line-kill char */
269 public int werase_char; /* The user's word-erase char */
270 public int sc_width, sc_height; /* Height & width of screen */
271 public int bo_s_width, bo_e_width; /* Printing width of boldface seq */
272 public int ul_s_width, ul_e_width; /* Printing width of underline seq */
273 public int so_s_width, so_e_width; /* Printing width of standout seq */
274 public int bl_s_width, bl_e_width; /* Printing width of blink seq */
275 public int above_mem, below_mem; /* Memory retained above/below screen */
276 public int can_goto_line; /* Can move cursor to any line */
277 public int clear_bg; /* Clear fills with background color */
278 public lbool missing_cap = FALSE; /* Some capability is missing */
279 public constant char *kent = NULL; /* Keypad ENTER sequence */
280 public lbool term_addrs = FALSE; /* "ti" has been sent to terminal */
281 public lbool full_screen = TRUE; /* We're using all lines of terminal */
282
283 static int attrmode = AT_NORMAL;
284 static int termcap_debug = -1;
285 static int no_alt_screen; /* sc_init does not switch to alt screen */
286 extern int binattr;
287 extern int one_screen;
288 extern int shell_lines;
289
290 #if !MSDOS_COMPILER
291 static constant char *cheaper(constant char *t1, constant char *t2, constant char *def);
292 static void tmodes(constant char *inti, constant char *outti, constant char *intc, constant char *outtc, constant char **instr,
293 constant char **outstr, constant char *def_instr, constant char *def_outstr, char **spp);
294 #endif
295
296 extern int quiet; /* If VERY_QUIET, use visual bell for bell */
297 extern int no_vbell;
298 extern int no_back_scroll;
299 extern int no_init;
300 extern int no_keypad;
301 extern int sigs;
302 extern int top_scroll;
303 extern int quit_if_one_screen;
304 extern int oldbot;
305 extern int mousecap;
306 extern int is_tty;
307 extern int use_color;
308 extern int no_paste;
309 extern int wscroll;
310 #if HILITE_SEARCH
311 extern int hilite_search;
312 #endif
313 #if MSDOS_COMPILER==WIN32C
314 extern HANDLE tty;
315 #else
316 extern int tty;
317 #endif
318
319 #if (HAVE_TERMIOS_H && HAVE_TERMIOS_FUNCS) || defined(TCGETA)
320 /*
321 * Set termio flags for use by less.
322 */
set_termio_flags(struct termios * s)323 static void set_termio_flags(
324 #if HAVE_TERMIOS_H && HAVE_TERMIOS_FUNCS
325 struct termios *s
326 #else
327 struct termio *s
328 #endif
329 )
330 {
331 s->c_lflag &= ~(0
332 #ifdef ICANON
333 | ICANON
334 #endif
335 #ifdef ECHO
336 | ECHO
337 #endif
338 #ifdef ECHOE
339 | ECHOE
340 #endif
341 #ifdef ECHOK
342 | ECHOK
343 #endif
344 #ifdef ECHONL
345 | ECHONL
346 #endif
347 );
348
349 s->c_oflag |= (0
350 #ifdef OPOST
351 | OPOST
352 #endif
353 #ifdef ONLCR
354 | ONLCR
355 #endif
356 );
357
358 s->c_oflag &= ~(0
359 #ifdef ONOEOT
360 | ONOEOT
361 #endif
362 #ifdef OCRNL
363 | OCRNL
364 #endif
365 #ifdef ONOCR
366 | ONOCR
367 #endif
368 #ifdef ONLRET
369 | ONLRET
370 #endif
371 );
372 }
373 #endif
374
375 /*
376 * Change terminal to "raw mode", or restore to "normal" mode.
377 * "Raw mode" means
378 * 1. An outstanding read will complete on receipt of a single keystroke.
379 * 2. Input is not echoed.
380 * 3. On output, \n is mapped to \r\n.
381 * 4. \t is NOT expanded into spaces.
382 * 5. Signal-causing characters such as ctrl-C (interrupt),
383 * etc. are NOT disabled.
384 * It doesn't matter whether an input \n is mapped to \r, or vice versa.
385 */
raw_mode(int on)386 public void raw_mode(int on)
387 {
388 static int curr_on = 0;
389
390 if (on == curr_on)
391 return;
392 erase2_char = '\b'; /* in case OS doesn't know about erase2 */
393 #if LESSTEST
394 if (is_lesstest())
395 {
396 /* {{ For consistent conditions when running tests. }} */
397 erase_char = '\b';
398 kill_char = CONTROL('U');
399 werase_char = CONTROL('W');
400 } else
401 #endif /*LESSTEST*/
402 #if HAVE_TERMIOS_H && HAVE_TERMIOS_FUNCS
403 {
404 struct termios s;
405 static struct termios save_term;
406 static int saved_term = 0;
407
408 if (on)
409 {
410 /*
411 * Get terminal modes.
412 */
413 if (tcgetattr(tty, &s) < 0)
414 {
415 erase_char = '\b';
416 kill_char = CONTROL('U');
417 werase_char = CONTROL('W');
418 } else
419 {
420 /*
421 * Save modes and set certain variables dependent on modes.
422 */
423 if (!saved_term)
424 {
425 save_term = s;
426 saved_term = 1;
427 }
428 #if HAVE_OSPEED
429 switch (cfgetospeed(&s))
430 {
431 #ifdef B0
432 case B0: ospeed = 0; break;
433 #endif
434 #ifdef B50
435 case B50: ospeed = 1; break;
436 #endif
437 #ifdef B75
438 case B75: ospeed = 2; break;
439 #endif
440 #ifdef B110
441 case B110: ospeed = 3; break;
442 #endif
443 #ifdef B134
444 case B134: ospeed = 4; break;
445 #endif
446 #ifdef B150
447 case B150: ospeed = 5; break;
448 #endif
449 #ifdef B200
450 case B200: ospeed = 6; break;
451 #endif
452 #ifdef B300
453 case B300: ospeed = 7; break;
454 #endif
455 #ifdef B600
456 case B600: ospeed = 8; break;
457 #endif
458 #ifdef B1200
459 case B1200: ospeed = 9; break;
460 #endif
461 #ifdef B1800
462 case B1800: ospeed = 10; break;
463 #endif
464 #ifdef B2400
465 case B2400: ospeed = 11; break;
466 #endif
467 #ifdef B4800
468 case B4800: ospeed = 12; break;
469 #endif
470 #ifdef B9600
471 case B9600: ospeed = 13; break;
472 #endif
473 #ifdef EXTA
474 case EXTA: ospeed = 14; break;
475 #endif
476 #ifdef EXTB
477 case EXTB: ospeed = 15; break;
478 #endif
479 #ifdef B57600
480 case B57600: ospeed = 16; break;
481 #endif
482 #ifdef B115200
483 case B115200: ospeed = 17; break;
484 #endif
485 default: ;
486 }
487 #endif
488 erase_char = s.c_cc[VERASE];
489 #ifdef VERASE2
490 erase2_char = s.c_cc[VERASE2];
491 #endif
492 kill_char = s.c_cc[VKILL];
493 #ifdef VWERASE
494 werase_char = s.c_cc[VWERASE];
495 #else
496 werase_char = CONTROL('W');
497 #endif
498
499 /*
500 * Set the modes to the way we want them.
501 */
502 set_termio_flags(&s);
503 s.c_cc[VMIN] = 1;
504 s.c_cc[VTIME] = 0;
505 #ifdef VLNEXT
506 s.c_cc[VLNEXT] = 0;
507 #endif
508 #ifdef VDSUSP
509 s.c_cc[VDSUSP] = 0;
510 #endif
511 #ifdef VSTOP
512 s.c_cc[VSTOP] = 0;
513 #endif
514 #ifdef VSTART
515 s.c_cc[VSTART] = 0;
516 #endif
517 #ifdef VDISCARD
518 s.c_cc[VDISCARD] = 0;
519 #endif
520 #if MUST_SET_LINE_DISCIPLINE
521 /*
522 * System's termios is broken; need to explicitly
523 * request TERMIODISC line discipline.
524 */
525 s.c_line = TERMIODISC;
526 #endif
527 }
528 } else
529 {
530 /*
531 * Restore saved modes.
532 */
533 s = save_term;
534 }
535 #if HAVE_FSYNC
536 fsync(tty);
537 #endif
538 tcsetattr(tty, TCSADRAIN, &s);
539 #if MUST_SET_LINE_DISCIPLINE
540 if (!on)
541 {
542 /*
543 * Broken termios *ignores* any line discipline
544 * except TERMIODISC. A different old line discipline
545 * is therefore not restored, yet. Restore the old
546 * line discipline by hand.
547 */
548 ioctl(tty, TIOCSETD, &save_term.c_line);
549 }
550 #endif
551 }
552 #else
553 #ifdef TCGETA
554 {
555 struct termio s;
556 static struct termio save_term;
557 static int saved_term = 0;
558
559 if (on)
560 {
561 /*
562 * Get terminal modes.
563 */
564 ioctl(tty, TCGETA, &s);
565
566 /*
567 * Save modes and set certain variables dependent on modes.
568 */
569 if (!saved_term)
570 {
571 save_term = s;
572 saved_term = 1;
573 }
574 #if HAVE_OSPEED
575 ospeed = s.c_cflag & CBAUD;
576 #endif
577 erase_char = s.c_cc[VERASE];
578 kill_char = s.c_cc[VKILL];
579 #ifdef VWERASE
580 werase_char = s.c_cc[VWERASE];
581 #else
582 werase_char = CONTROL('W');
583 #endif
584
585 /*
586 * Set the modes to the way we want them.
587 */
588 set_termio_flags(&s);
589 s.c_cc[VMIN] = 1;
590 s.c_cc[VTIME] = 0;
591 #ifdef VSTOP
592 s.c_cc[VSTOP] = 0;
593 #endif
594 #ifdef VSTART
595 s.c_cc[VSTART] = 0;
596 #endif
597 } else
598 {
599 /*
600 * Restore saved modes.
601 */
602 s = save_term;
603 }
604 ioctl(tty, TCSETAW, &s);
605 }
606 #else
607 #ifdef TIOCGETP
608 {
609 struct sgttyb s;
610 static struct sgttyb save_term;
611 static int saved_term = 0;
612
613 if (on)
614 {
615 /*
616 * Get terminal modes.
617 */
618 ioctl(tty, TIOCGETP, &s);
619
620 /*
621 * Save modes and set certain variables dependent on modes.
622 */
623 if (!saved_term)
624 {
625 save_term = s;
626 saved_term = 1;
627 }
628 #if HAVE_OSPEED
629 ospeed = s.sg_ospeed;
630 #endif
631 erase_char = s.sg_erase;
632 kill_char = s.sg_kill;
633 werase_char = CONTROL('W');
634
635 /*
636 * Set the modes to the way we want them.
637 */
638 s.sg_flags |= CBREAK;
639 s.sg_flags &= ~(ECHO);
640 } else
641 {
642 /*
643 * Restore saved modes.
644 */
645 s = save_term;
646 }
647 ioctl(tty, TIOCSETN, &s);
648 }
649 #else
650 #ifdef _OSK
651 {
652 struct sgbuf s;
653 static struct sgbuf save_term;
654 static int saved_term = 0;
655
656 if (on)
657 {
658 /*
659 * Get terminal modes.
660 */
661 _gs_opt(tty, &s);
662
663 /*
664 * Save modes and set certain variables dependent on modes.
665 */
666 if (!saved_term)
667 {
668 save_term = s;
669 saved_term = 1;
670 }
671 erase_char = s.sg_bspch;
672 kill_char = s.sg_dlnch;
673 werase_char = CONTROL('W');
674
675 /*
676 * Set the modes to the way we want them.
677 */
678 s.sg_echo = 0;
679 s.sg_eofch = 0;
680 s.sg_pause = 0;
681 s.sg_psch = 0;
682 } else
683 {
684 /*
685 * Restore saved modes.
686 */
687 s = save_term;
688 }
689 _ss_opt(tty, &s);
690 }
691 #else
692 /* MS-DOS, Windows, or OS2 */
693 #if OS2
694 /* OS2 */
695 LSIGNAL(SIGINT, SIG_IGN);
696 #endif
697 erase_char = '\b';
698 #if MSDOS_COMPILER==DJGPPC
699 kill_char = CONTROL('U');
700 /*
701 * So that when we shell out or run another program, its
702 * stdin is in cooked mode. We do not switch stdin to binary
703 * mode if fd0 is zero, since that means we were called before
704 * tty was reopened in open_getchr, in which case we would be
705 * changing the original stdin device outside less.
706 */
707 if (fd0 != 0)
708 setmode(0, on ? O_BINARY : O_TEXT);
709 #else
710 kill_char = ESC;
711 #endif
712 werase_char = CONTROL('W');
713 #endif
714 #endif
715 #endif
716 #endif
717 curr_on = on;
718 }
719
720 #if !MSDOS_COMPILER
721
722 /*
723 * Some glue to prevent calling termcap functions if tgetent() failed.
724 */
725 static int hardcopy;
726
ltget_env(constant char * tiname,constant char * tcname)727 static constant char * ltget_env(constant char *tiname, constant char *tcname)
728 {
729 char envname[64];
730 constant char *s;
731
732 if (termcap_debug)
733 {
734 struct env { struct env *next; char *name; char *value; };
735 constant char *capname = tcname != NULL ? tcname : tiname;
736 static struct env *envs = NULL;
737 struct env *p;
738 for (p = envs; p != NULL; p = p->next)
739 if (strcmp(p->name, capname) == 0)
740 return p->value;
741 p = (struct env *) ecalloc(1, sizeof(struct env));
742 p->name = save(capname);
743 p->value = (char *) ecalloc(strlen(capname)+3, sizeof(char));
744 sprintf(p->value, "<%s>", capname);
745 p->next = envs;
746 envs = p;
747 return p->value;
748 }
749 if (tiname != NULL)
750 {
751 SNPRINTF1(envname, sizeof(envname), "LESS_TERMINFO_%s", tiname);
752 s = lgetenv(envname);
753 if (!isnullenv(s))
754 return s;
755 }
756 if (tcname != NULL)
757 {
758 SNPRINTF1(envname, sizeof(envname), "LESS_TERMCAP_%s", tcname);
759 s = lgetenv(envname);
760 if (!isnullenv(s))
761 return s;
762 }
763 return NULL;
764 }
765
ltgetflag(constant char * tiname,constant char * tcname)766 static int ltgetflag(constant char *tiname, constant char *tcname)
767 {
768 constant char *s;
769
770 if ((s = ltget_env(tiname, tcname)) != NULL)
771 return (*s != '\0' && *s != '0');
772 if (hardcopy)
773 return (0);
774 #if USE_TERMINFO
775 return tiname == NULL ? 0 : tigetflag(tiname);
776 #else
777 return tcname == NULL ? 0 : tgetflag(tcname);
778 #endif
779 }
780
ltgetnum(constant char * tiname,constant char * tcname)781 static int ltgetnum(constant char *tiname, constant char *tcname)
782 {
783 constant char *s;
784
785 if ((s = ltget_env(tiname, tcname)) != NULL)
786 return (atoi(s));
787 if (hardcopy)
788 return (-1);
789 #if USE_TERMINFO
790 return tiname == NULL ? -1 : tigetnum(tiname);
791 #else
792 return tcname == NULL ? -1 : tgetnum(tcname);
793 #endif
794 }
795
ltgetstr(constant char * tiname,constant char * tcname,char ** pp)796 static constant char * ltgetstr(constant char *tiname, constant char *tcname, char **pp)
797 {
798 constant char *s;
799
800 if ((s = ltget_env(tiname, tcname)) != NULL)
801 return (s);
802 if (hardcopy)
803 return (NULL);
804 #if USE_TERMINFO
805 if (tiname == NULL)
806 return (NULL);
807 s = tigetstr(tiname);
808 if (s == (constant char *)-1)
809 s = NULL;
810 return (s);
811 #else
812 if (tcname == NULL)
813 return (NULL);
814 return tgetstr(tcname, pp);
815 #endif
816 }
817 #endif /* MSDOS_COMPILER */
818
819 /*
820 * Get size of the output screen.
821 */
scrsize(void)822 public void scrsize(void)
823 {
824 constant char *s;
825 int sys_height;
826 int sys_width;
827 #if !MSDOS_COMPILER
828 int n;
829 #endif
830
831 #define DEF_SC_WIDTH 80
832 #if MSDOS_COMPILER
833 #define DEF_SC_HEIGHT 25
834 #else
835 #define DEF_SC_HEIGHT 24
836 #endif
837
838 sys_width = sys_height = 0;
839
840 #if LESSTEST
841 if (0) /* can't use is_lesstest(): ttyin_name may not be set by scan_option yet */
842 #endif /*LESSTEST*/
843 {
844 #if MSDOS_COMPILER==MSOFTC
845 {
846 struct videoconfig w;
847 _getvideoconfig(&w);
848 sys_height = w.numtextrows;
849 sys_width = w.numtextcols;
850 }
851 #else
852 #if MSDOS_COMPILER==BORLANDC || MSDOS_COMPILER==DJGPPC
853 {
854 struct text_info w;
855 gettextinfo(&w);
856 sys_height = w.screenheight;
857 sys_width = w.screenwidth;
858 }
859 #else
860 #if MSDOS_COMPILER==WIN32C
861 {
862 CONSOLE_SCREEN_BUFFER_INFO scr;
863 GetConsoleScreenBufferInfo(con_out, &scr);
864 sys_height = scr.srWindow.Bottom - scr.srWindow.Top + 1;
865 sys_width = scr.srWindow.Right - scr.srWindow.Left + 1;
866 }
867 #else
868 #if OS2
869 {
870 int s[2];
871 _scrsize(s);
872 sys_width = s[0];
873 sys_height = s[1];
874 /*
875 * When using terminal emulators for XFree86/OS2, the
876 * _scrsize function does not work well.
877 * Call the scrsize.exe program to get the window size.
878 */
879 windowid = getenv("WINDOWID");
880 if (windowid != NULL)
881 {
882 FILE *fd = popen("scrsize", "rt");
883 if (fd != NULL)
884 {
885 int w, h;
886 fscanf(fd, "%i %i", &w, &h);
887 if (w > 0 && h > 0)
888 {
889 sys_width = w;
890 sys_height = h;
891 }
892 pclose(fd);
893 }
894 }
895 }
896 #else
897 #ifdef TIOCGWINSZ
898 {
899 struct winsize w;
900 if (ioctl(2, TIOCGWINSZ, &w) == 0)
901 {
902 if (w.ws_row > 0)
903 sys_height = w.ws_row;
904 if (w.ws_col > 0)
905 sys_width = w.ws_col;
906 }
907 }
908 #else
909 #ifdef WIOCGETD
910 {
911 struct uwdata w;
912 if (ioctl(2, WIOCGETD, &w) == 0)
913 {
914 if (w.uw_height > 0)
915 sys_height = w.uw_height / w.uw_vs;
916 if (w.uw_width > 0)
917 sys_width = w.uw_width / w.uw_hs;
918 }
919 }
920 #endif
921 #endif
922 #endif
923 #endif
924 #endif
925 #endif
926 }
927
928 if (sys_height > 0)
929 sc_height = sys_height;
930 else if ((s = lgetenv("LINES")) != NULL)
931 sc_height = atoi(s);
932 #if !MSDOS_COMPILER
933 else if ((n = ltgetnum("lines", "li")) > 0)
934 sc_height = n;
935 #endif
936 if ((s = lgetenv("LESS_LINES")) != NULL)
937 {
938 int height = atoi(s);
939 sc_height = (height < 0) ? sc_height + height : height;
940 full_screen = FALSE;
941 }
942 if (sc_height <= 0)
943 sc_height = DEF_SC_HEIGHT;
944
945 if (sys_width > 0)
946 sc_width = sys_width;
947 else if ((s = lgetenv("COLUMNS")) != NULL)
948 sc_width = atoi(s);
949 #if !MSDOS_COMPILER
950 else if ((n = ltgetnum("cols", "co")) > 0)
951 sc_width = n;
952 #endif
953 if ((s = lgetenv("LESS_COLUMNS")) != NULL)
954 {
955 int width = atoi(s);
956 sc_width = (width < 0) ? sc_width + width : width;
957 }
958 if (sc_width <= 0)
959 sc_width = DEF_SC_WIDTH;
960 screen_size_changed();
961 }
962
963 /*
964 * Recalculate things that depend on the screen size.
965 */
screen_size_changed(void)966 public void screen_size_changed(void)
967 {
968 constant char *env = lgetenv("LESS_SHELL_LINES");
969 shell_lines = isnullenv(env) ? 1 : atoi(env);
970 if (shell_lines >= sc_height)
971 shell_lines = sc_height - 1;
972 wscroll = (sc_height + 1) / 2;
973 calc_jump_sline();
974 calc_shift_count();
975 calc_match_shift();
976 }
977
978 #if MSDOS_COMPILER==MSOFTC
979 /*
980 * Figure out how many empty loops it takes to delay a millisecond.
981 */
get_clock(void)982 static void get_clock(void)
983 {
984 clock_t start;
985
986 /*
987 * Get synchronized at the start of a tick.
988 */
989 start = clock();
990 while (clock() == start)
991 ;
992 /*
993 * Now count loops till the next tick.
994 */
995 start = clock();
996 msec_loops = 0;
997 while (clock() == start)
998 msec_loops++;
999 /*
1000 * Convert from (loops per clock) to (loops per millisecond).
1001 */
1002 msec_loops *= CLOCKS_PER_SEC;
1003 msec_loops /= 1000;
1004 }
1005
1006 /*
1007 * Delay for a specified number of milliseconds.
1008 */
delay(int msec)1009 static void delay(int msec)
1010 {
1011 long i;
1012
1013 while (msec-- > 0)
1014 {
1015 for (i = 0; i < msec_loops; i++)
1016 (void) clock();
1017 }
1018 }
1019 #endif
1020
1021 /*
1022 * Return the characters actually input by a "special" key.
1023 */
special_key_str(int key)1024 public constant char * special_key_str(int key)
1025 {
1026 static char tbuf[40];
1027 constant char *s;
1028 #if MSDOS_COMPILER || OS2
1029 static char k_right[] = { '\340', PCK_RIGHT, 0 };
1030 static char k_left[] = { '\340', PCK_LEFT, 0 };
1031 static char k_ctl_right[] = { '\340', PCK_CTL_RIGHT, 0 };
1032 static char k_ctl_left[] = { '\340', PCK_CTL_LEFT, 0 };
1033 static char k_insert[] = { '\340', PCK_INSERT, 0 };
1034 static char k_delete[] = { '\340', PCK_DELETE, 0 };
1035 static char k_ctl_delete[] = { '\340', PCK_CTL_DELETE, 0 };
1036 static char k_ctl_backspace[] = { '\177', 0 };
1037 static char k_backspace[] = { '\b', 0 };
1038 static char k_home[] = { '\340', PCK_HOME, 0 };
1039 static char k_end[] = { '\340', PCK_END, 0 };
1040 static char k_up[] = { '\340', PCK_UP, 0 };
1041 static char k_down[] = { '\340', PCK_DOWN, 0 };
1042 static char k_backtab[] = { '\340', PCK_SHIFT_TAB, 0 };
1043 static char k_pagedown[] = { '\340', PCK_PAGEDOWN, 0 };
1044 static char k_pageup[] = { '\340', PCK_PAGEUP, 0 };
1045 static char k_ctl_home[] = { '\340', PCK_CTL_HOME, 0 };
1046 static char k_ctl_end[] = { '\340', PCK_CTL_END, 0 };
1047 static char k_shift_home[] = { '\340', PCK_SHIFT_HOME, 0 };
1048 static char k_shift_end[] = { '\340', PCK_SHIFT_END, 0 };
1049 static char k_f1[] = { '\340', PCK_F1, 0 };
1050 #endif
1051 #if !MSDOS_COMPILER
1052 char *sp = tbuf;
1053 #endif
1054
1055 switch (key)
1056 {
1057 #if OS2
1058 /*
1059 * If windowid is not NULL, assume less is executed in
1060 * the XFree86 environment.
1061 */
1062 case SK_RIGHT_ARROW:
1063 s = windowid ? ltgetstr("kcuf1", "kr", &sp) : k_right;
1064 break;
1065 case SK_LEFT_ARROW:
1066 s = windowid ? ltgetstr("kcub1", "kl", &sp) : k_left;
1067 break;
1068 case SK_UP_ARROW:
1069 s = windowid ? ltgetstr("kcuu1", "ku", &sp) : k_up;
1070 break;
1071 case SK_DOWN_ARROW:
1072 s = windowid ? ltgetstr("kcud1", "kd", &sp) : k_down;
1073 break;
1074 case SK_PAGE_UP:
1075 s = windowid ? ltgetstr("kpp", "kP", &sp) : k_pageup;
1076 break;
1077 case SK_PAGE_DOWN:
1078 s = windowid ? ltgetstr("knp", "kN", &sp) : k_pagedown;
1079 break;
1080 case SK_HOME:
1081 s = windowid ? ltgetstr("khome", "kh", &sp) : k_home;
1082 break;
1083 case SK_END:
1084 s = windowid ? ltgetstr("kend", "@7", &sp) : k_end;
1085 break;
1086 case SK_F1:
1087 s = windowid ? ltgetstr("kf1", "k1", &sp) : k_f1;
1088 break;
1089 case SK_DELETE:
1090 s = windowid ? ltgetstr("kdch1", "kD", &sp) : k_delete;
1091 if (s == NULL)
1092 {
1093 tbuf[0] = '\177';
1094 tbuf[1] = '\0';
1095 s = tbuf;
1096 }
1097 break;
1098 #endif
1099 #if MSDOS_COMPILER
1100 case SK_RIGHT_ARROW:
1101 s = k_right;
1102 break;
1103 case SK_LEFT_ARROW:
1104 s = k_left;
1105 break;
1106 case SK_UP_ARROW:
1107 s = k_up;
1108 break;
1109 case SK_DOWN_ARROW:
1110 s = k_down;
1111 break;
1112 case SK_PAGE_UP:
1113 s = k_pageup;
1114 break;
1115 case SK_PAGE_DOWN:
1116 s = k_pagedown;
1117 break;
1118 case SK_HOME:
1119 s = k_home;
1120 break;
1121 case SK_END:
1122 s = k_end;
1123 break;
1124 case SK_DELETE:
1125 s = k_delete;
1126 break;
1127 #endif
1128 #if MSDOS_COMPILER || OS2
1129 case SK_INSERT:
1130 s = k_insert;
1131 break;
1132 case SK_CTL_LEFT_ARROW:
1133 s = k_ctl_left;
1134 break;
1135 case SK_CTL_RIGHT_ARROW:
1136 s = k_ctl_right;
1137 break;
1138 case SK_CTL_BACKSPACE:
1139 s = k_ctl_backspace;
1140 break;
1141 case SK_CTL_DELETE:
1142 s = k_ctl_delete;
1143 break;
1144 case SK_BACKSPACE:
1145 s = k_backspace;
1146 break;
1147 case SK_F1:
1148 s = k_f1;
1149 break;
1150 case SK_BACKTAB:
1151 s = k_backtab;
1152 break;
1153 case SK_SHIFT_HOME:
1154 s = k_shift_home;
1155 break;
1156 case SK_CTL_HOME:
1157 s = k_ctl_home;
1158 break;
1159 case SK_SHIFT_END:
1160 s = k_shift_end;
1161 break;
1162 case SK_CTL_END:
1163 s = k_ctl_end;
1164 break;
1165 #else
1166 case SK_RIGHT_ARROW:
1167 s = ltgetstr("kcuf1", "kr", &sp);
1168 break;
1169 case SK_LEFT_ARROW:
1170 s = ltgetstr("kcub1", "kl", &sp);
1171 break;
1172 case SK_UP_ARROW:
1173 s = ltgetstr("kcuu1", "ku", &sp);
1174 break;
1175 case SK_DOWN_ARROW:
1176 s = ltgetstr("kcud1", "kd", &sp);
1177 break;
1178 case SK_PAGE_UP:
1179 s = ltgetstr("kpp", "kP", &sp);
1180 break;
1181 case SK_PAGE_DOWN:
1182 s = ltgetstr("knp", "kN", &sp);
1183 break;
1184 case SK_HOME:
1185 s = ltgetstr("khome", "kh", &sp);
1186 break;
1187 case SK_SHIFT_HOME:
1188 s = ltgetstr("kHOM", "#2", &sp);
1189 break;
1190 case SK_CTL_HOME:
1191 s = ltgetstr("kHOM5", NULL, &sp);
1192 break;
1193 case SK_END:
1194 s = ltgetstr("kend", "@7", &sp);
1195 break;
1196 case SK_SHIFT_END:
1197 s = ltgetstr("kEND", "#7", &sp);
1198 break;
1199 case SK_CTL_END:
1200 s = ltgetstr("kEND5", NULL, &sp);
1201 break;
1202 case SK_INSERT:
1203 s = ltgetstr("kich1", "kI", &sp);
1204 break;
1205 case SK_BACKTAB:
1206 s = ltgetstr("kcbt", "kB", &sp);
1207 break;
1208 case SK_CTL_RIGHT_ARROW:
1209 s = ltgetstr("kRIT5", NULL, &sp);
1210 break;
1211 case SK_CTL_LEFT_ARROW:
1212 s = ltgetstr("kLFT5", NULL, &sp);
1213 break;
1214 case SK_F1:
1215 s = ltgetstr("kf1", "k1", &sp);
1216 break;
1217 case SK_PAD_UL:
1218 s = ltgetstr("ka1", "K1", &sp);
1219 break;
1220 case SK_PAD_U:
1221 s = ltgetstr("ka2", NULL, &sp);
1222 break;
1223 case SK_PAD_UR:
1224 s = ltgetstr("ka3", "K3", &sp);
1225 break;
1226 case SK_PAD_L:
1227 s = ltgetstr("kb1", NULL, &sp);
1228 break;
1229 case SK_PAD_CENTER:
1230 s = ltgetstr("kb2", "K2", &sp);
1231 break;
1232 case SK_PAD_R:
1233 s = ltgetstr("kb3", NULL, &sp);
1234 break;
1235 case SK_PAD_DL:
1236 s = ltgetstr("kc1", "K4", &sp);
1237 break;
1238 case SK_PAD_D:
1239 s = ltgetstr("kc2", NULL, &sp);
1240 break;
1241 case SK_PAD_DR:
1242 s = ltgetstr("kc3", "K5", &sp);
1243 break;
1244 case SK_PAD_STAR:
1245 s = ltgetstr("kpMUL", NULL, &sp);
1246 break;
1247 case SK_PAD_SLASH:
1248 s = ltgetstr("kpDIV", NULL, &sp);
1249 break;
1250 case SK_PAD_DASH:
1251 s = ltgetstr("kpSUB", NULL, &sp);
1252 break;
1253 case SK_PAD_PLUS:
1254 s = ltgetstr("kpADD", NULL, &sp);
1255 break;
1256 case SK_PAD_DOT:
1257 s = ltgetstr("kpDOT", NULL, &sp);
1258 break;
1259 case SK_PAD_COMMA:
1260 s = ltgetstr("kpCMA", NULL, &sp);
1261 break;
1262 case SK_PAD_ZERO:
1263 s = ltgetstr("kpZRO", NULL, &sp);
1264 break;
1265 case SK_DELETE:
1266 s = ltgetstr("kdch1", "kD", &sp);
1267 if (s == NULL)
1268 {
1269 tbuf[0] = '\177';
1270 tbuf[1] = '\0';
1271 s = tbuf;
1272 }
1273 break;
1274 case SK_BACKSPACE:
1275 s = ltgetstr("kbs", "kb", &sp);
1276 if (s == NULL)
1277 {
1278 tbuf[0] = '\b';
1279 tbuf[1] = '\0';
1280 s = tbuf;
1281 }
1282 break;
1283 #endif
1284 case SK_CONTROL_K:
1285 tbuf[0] = CONTROL('K');
1286 tbuf[1] = '\0';
1287 s = tbuf;
1288 break;
1289 default:
1290 return (NULL);
1291 }
1292 return (s);
1293 }
1294
1295 #if !MSDOS_COMPILER
ltgoto(constant char * cap,int col,int line)1296 static constant char *ltgoto(constant char *cap, int col, int line)
1297 {
1298 #if USE_TERMINFO
1299 return tparm(cap, line, col);
1300 #else
1301 return tgoto(cap, col, line);
1302 #endif
1303 }
1304 #endif /* MSDOS_COMPILER */
1305
1306 #if MSDOS_COMPILER
init_win_colors(void)1307 public void init_win_colors(void)
1308 {
1309 if (nm_fg_color == CV_ERROR || nm_fg_color == CV_NOCHANGE) nm_fg_color = sy_fg_color;
1310 if (nm_bg_color == CV_ERROR || nm_bg_color == CV_NOCHANGE) nm_bg_color = sy_bg_color;
1311 if (bo_fg_color == CV_NOCHANGE) bo_fg_color = sy_fg_color; else if (bo_fg_color == CV_ERROR) bo_fg_color = sy_fg_color | 8;
1312 if (bo_bg_color == CV_NOCHANGE) bo_bg_color = sy_bg_color; else if (bo_bg_color == CV_ERROR) bo_bg_color = sy_bg_color;
1313 if (ul_fg_color == CV_NOCHANGE) ul_fg_color = sy_fg_color; else if (ul_fg_color == CV_ERROR) ul_fg_color = (sy_bg_color == 3 || sy_bg_color == 11) ? 0 : 11;
1314 if (ul_bg_color == CV_NOCHANGE) ul_bg_color = sy_bg_color; else if (ul_bg_color == CV_ERROR) ul_bg_color = sy_bg_color;
1315 if (so_fg_color == CV_NOCHANGE) so_fg_color = sy_fg_color; else if (so_fg_color == CV_ERROR) so_fg_color = sy_bg_color;
1316 if (so_bg_color == CV_NOCHANGE) so_bg_color = sy_bg_color; else if (so_bg_color == CV_ERROR) so_bg_color = sy_fg_color;
1317 if (bl_fg_color == CV_NOCHANGE) bl_fg_color = sy_fg_color; else if (bl_fg_color == CV_ERROR) bl_fg_color = ul_bg_color;
1318 if (bl_bg_color == CV_NOCHANGE) bl_bg_color = sy_bg_color; else if (bl_bg_color == CV_ERROR) bl_bg_color = ul_fg_color;
1319 nm_fg_color |= nm_attr;
1320 bo_fg_color |= bo_attr;
1321 ul_fg_color |= ul_attr;
1322 so_fg_color |= so_attr;
1323 bl_fg_color |= bl_attr;
1324 }
1325 #endif /* MSDOS_COMPILER */
1326
1327 /*
1328 * Get terminal capabilities via termcap.
1329 */
get_term()1330 public void get_term()
1331 {
1332 termcap_debug = !isnullenv(lgetenv("LESS_TERMCAP_DEBUG"));
1333 #if MSDOS_COMPILER
1334 auto_wrap = 1;
1335 defer_wrap = 0;
1336 can_goto_line = 1;
1337 clear_bg = 1;
1338 /*
1339 * Set up default colors.
1340 * The xx_s_width and xx_e_width vars are already initialized to 0.
1341 */
1342 #if MSDOS_COMPILER==MSOFTC
1343 sy_bg_color = _getbkcolor();
1344 sy_fg_color = _gettextcolor();
1345 get_clock();
1346 #else
1347 #if MSDOS_COMPILER==BORLANDC || MSDOS_COMPILER==DJGPPC
1348 {
1349 struct text_info w;
1350 gettextinfo(&w);
1351 sy_bg_color = (w.attribute >> 4) & 0x0F;
1352 sy_fg_color = (w.attribute >> 0) & 0x0F;
1353 }
1354 #else
1355 #if MSDOS_COMPILER==WIN32C
1356 {
1357 CONSOLE_SCREEN_BUFFER_INFO scr;
1358
1359 con_out_save = con_out = GetStdHandle(STD_OUTPUT_HANDLE);
1360 /*
1361 * Always open stdin in binary. Note this *must* be done
1362 * before any file operations have been done on fd0.
1363 */
1364 SET_BINARY(0);
1365 GetConsoleMode(con_out, &init_console_output_mode);
1366 GetConsoleScreenBufferInfo(con_out, &scr);
1367 curr_attr = scr.wAttributes;
1368 sy_bg_color = (curr_attr & BG_COLORS) >> 4; /* normalize */
1369 sy_fg_color = curr_attr & FG_COLORS;
1370 }
1371 #endif
1372 #endif
1373 #endif
1374 init_win_colors();
1375
1376 /*
1377 * Get size of the screen.
1378 */
1379 scrsize();
1380 pos_init();
1381
1382 #else /* !MSDOS_COMPILER */
1383 {
1384 constant char *t1;
1385 constant char *t2;
1386 constant char *term;
1387 char *sp;
1388 /*
1389 * Some termcap libraries assume termbuf is static
1390 * (accessible after tgetent returns).
1391 */
1392 #if !USE_TERMINFO
1393 static char termbuf[TERMBUF_SIZE];
1394 #endif
1395 static char sbuf[TERMSBUF_SIZE];
1396
1397 #if OS2
1398 /*
1399 * Make sure the termcap database is available.
1400 */
1401 constant char *cp = lgetenv("TERMCAP");
1402 if (isnullenv(cp))
1403 {
1404 char *termcap;
1405 if ((sp = homefile("termcap.dat")) != NULL)
1406 {
1407 termcap = (char *) ecalloc(strlen(sp)+9, sizeof(char));
1408 sprintf(termcap, "TERMCAP=%s", sp);
1409 free(sp);
1410 putenv(termcap);
1411 }
1412 }
1413 #endif
1414 /*
1415 * Find out what kind of terminal this is.
1416 */
1417 if ((term = lgetenv("TERM")) == NULL && (term = getenv("TERM")) == NULL)
1418 term = DEFAULT_TERM;
1419 hardcopy = 0;
1420 #if USE_TERMINFO
1421 if (setupterm(term, -1, NULL) != OK)
1422 hardcopy = 1;
1423 #else
1424 if (tgetent(termbuf, term) != TGETENT_OK)
1425 hardcopy = 1;
1426 #endif
1427 if (!hardcopy && ltgetflag("hc", "hc"))
1428 hardcopy = 1;
1429
1430 /*
1431 * Get size of the screen.
1432 */
1433 scrsize();
1434 pos_init();
1435
1436 auto_wrap = ltgetflag("am", "am");
1437 defer_wrap = ltgetflag("xenl", "xn");
1438 above_mem = ltgetflag("da", "da");
1439 below_mem = ltgetflag("db", "db");
1440 clear_bg = ltgetflag("bce", "ut");
1441 no_alt_screen = ltgetflag("nrrmc", "NR");
1442
1443 /*
1444 * Assumes termcap variable "sg" is the printing width of:
1445 * the standout sequence, the end standout sequence,
1446 * the underline sequence, the end underline sequence,
1447 * the boldface sequence, and the end boldface sequence.
1448 */
1449 if ((so_s_width = ltgetnum("xmc", "sg")) < 0)
1450 so_s_width = 0;
1451 so_e_width = so_s_width;
1452
1453 bo_s_width = bo_e_width = so_s_width;
1454 ul_s_width = ul_e_width = so_s_width;
1455 bl_s_width = bl_e_width = so_s_width;
1456
1457 #if HILITE_SEARCH
1458 if (so_s_width > 0 || so_e_width > 0)
1459 /*
1460 * Disable highlighting by default on magic cookie terminals.
1461 * Turning on highlighting might change the displayed width
1462 * of a line, causing the display to get messed up.
1463 * The user can turn it back on with -g,
1464 * but she won't like the results.
1465 */
1466 hilite_search = 0;
1467 #endif
1468
1469 /*
1470 * Get various string-valued capabilities.
1471 */
1472 sp = sbuf;
1473
1474 #if HAVE_OSPEED
1475 sc_pad = ltgetstr("pad", "pc", &sp);
1476 if (sc_pad != NULL)
1477 PC = *sc_pad;
1478 #endif
1479
1480 sc_s_keypad = ltgetstr("smkx", "ks", &sp);
1481 if (sc_s_keypad == NULL)
1482 sc_s_keypad = "";
1483 sc_e_keypad = ltgetstr("rmkx", "ke", &sp);
1484 if (sc_e_keypad == NULL)
1485 sc_e_keypad = "";
1486 kent = ltgetstr("kent", "@8", &sp);
1487
1488 sc_s_mousecap = ltgetstr("MOUSE_START", "MOUSE_START", &sp);
1489 if (sc_s_mousecap == NULL)
1490 sc_s_mousecap = ESCS "[?1000h" ESCS "[?1002h" ESCS "[?1006h";
1491 sc_e_mousecap = ltgetstr("MOUSE_END", "MOUSE_END", &sp);
1492 if (sc_e_mousecap == NULL)
1493 sc_e_mousecap = ESCS "[?1006l" ESCS "[?1002l" ESCS "[?1000l";
1494
1495 sc_s_bracketed_paste = ltgetstr("BRACKETED_PASTE_START", "BRACKETED_PASTE_START", &sp);
1496 if (sc_s_bracketed_paste == NULL)
1497 sc_s_bracketed_paste = ESCS"[?2004h";
1498 sc_e_bracketed_paste = ltgetstr("BRACKETED_PASTE_END", "BRACKETED_PASTE_END", &sp);
1499 if (sc_e_bracketed_paste == NULL)
1500 sc_e_bracketed_paste = ESCS"[?2004l";
1501
1502 sc_suspend = ltgetstr("SUSPEND", "SUSPEND", &sp);
1503 if (sc_suspend == NULL)
1504 sc_suspend = "";
1505 sc_resume = ltgetstr("RESUME", "RESUME", &sp);
1506 if (sc_resume == NULL)
1507 sc_resume = "";
1508
1509 sc_init = ltgetstr("smcup", "ti", &sp);
1510 if (sc_init == NULL)
1511 sc_init = "";
1512
1513 sc_deinit= ltgetstr("rmcup", "te", &sp);
1514 if (sc_deinit == NULL)
1515 sc_deinit = "";
1516
1517 sc_eol_clear = ltgetstr("el", "ce", &sp);
1518 if (sc_eol_clear == NULL || *sc_eol_clear == '\0')
1519 {
1520 missing_cap = TRUE;
1521 sc_eol_clear = "";
1522 }
1523
1524 sc_eos_clear = ltgetstr("ed", "cd", &sp);
1525 if (below_mem && (sc_eos_clear == NULL || *sc_eos_clear == '\0'))
1526 {
1527 missing_cap = TRUE;
1528 sc_eos_clear = "";
1529 }
1530
1531 sc_clear = ltgetstr("clear", "cl", &sp);
1532 if (sc_clear == NULL || *sc_clear == '\0')
1533 {
1534 missing_cap = TRUE;
1535 sc_clear = "\n\n";
1536 }
1537
1538 sc_move = ltgetstr("cup", "cm", &sp);
1539 if (sc_move == NULL || *sc_move == '\0')
1540 {
1541 /*
1542 * This is not an error here, because we don't
1543 * always need sc_move.
1544 * We need it only if we don't have home or lower-left.
1545 */
1546 sc_move = "";
1547 can_goto_line = 0;
1548 } else
1549 can_goto_line = 1;
1550
1551 tmodes("smso", "rmso", "so", "se", &sc_s_in, &sc_s_out, "", "", &sp);
1552 tmodes("smul", "rmul", "us", "ue", &sc_u_in, &sc_u_out, sc_s_in, sc_s_out, &sp);
1553 tmodes("bold", "sgr0", "md", "me", &sc_b_in, &sc_b_out, sc_s_in, sc_s_out, &sp);
1554 tmodes("blink", "sgr0", "mb", "me", &sc_bl_in, &sc_bl_out, sc_s_in, sc_s_out, &sp);
1555
1556 sc_visual_bell = ltgetstr("flash", "vb", &sp);
1557 if (sc_visual_bell == NULL)
1558 sc_visual_bell = "";
1559
1560 if (ltgetflag(NULL, "bs"))
1561 sc_backspace = "\b";
1562 else
1563 {
1564 sc_backspace = ltgetstr("OTbc", "bc", &sp);
1565 if (sc_backspace == NULL || *sc_backspace == '\0')
1566 sc_backspace = "\b";
1567 }
1568
1569 /*
1570 * Choose between using "ho" and "cm" ("home" and "cursor move")
1571 * to move the cursor to the upper left corner of the screen.
1572 */
1573 t1 = ltgetstr("home", "ho", &sp);
1574 if (t1 == NULL)
1575 t1 = "";
1576 if (*sc_move == '\0')
1577 t2 = "";
1578 else
1579 {
1580 strcpy(sp, ltgoto(sc_move, 0, 0));
1581 t2 = sp;
1582 sp += strlen(sp) + 1;
1583 }
1584 sc_home = cheaper(t1, t2, "|\b^");
1585
1586 /*
1587 * Choose between using "ll" and "cm" ("lower left" and "cursor move")
1588 * to move the cursor to the lower left corner of the screen.
1589 */
1590 t1 = ltgetstr("ll", "ll", &sp);
1591 if (t1 == NULL || !full_screen)
1592 t1 = "";
1593 if (*sc_move == '\0')
1594 t2 = "";
1595 else
1596 {
1597 strcpy(sp, ltgoto(sc_move, 0, sc_height-1));
1598 t2 = sp;
1599 sp += strlen(sp) + 1;
1600 }
1601 sc_lower_left = cheaper(t1, t2, "\r");
1602
1603 /*
1604 * Get carriage return string.
1605 */
1606 sc_return = ltgetstr("cr", "cr", &sp);
1607 if (sc_return == NULL)
1608 sc_return = "\r";
1609
1610 /*
1611 * Choose between using "al" or "sr" ("add line" or "scroll reverse")
1612 * to add a line at the top of the screen.
1613 */
1614 t1 = ltgetstr("ill", "al", &sp);
1615 if (t1 == NULL)
1616 t1 = "";
1617 t2 = ltgetstr("ri", "sr", &sp);
1618 if (t2 == NULL)
1619 t2 = "";
1620 if (*t1 == '\0' && *t2 == '\0')
1621 sc_addline = "";
1622 else if (above_mem)
1623 sc_addline = t1;
1624 else
1625 sc_addline = cheaper(t1, t2, "");
1626 if (*sc_addline == '\0')
1627 {
1628 /*
1629 * Force repaint on any backward movement.
1630 */
1631 no_back_scroll = 1;
1632 }
1633 }
1634 #endif /* MSDOS_COMPILER */
1635 }
1636
1637 #if !MSDOS_COMPILER
1638 /*
1639 * Return the cost of displaying a termcap string.
1640 * We use the trick of calling tputs, but as a char printing function
1641 * we give it inc_costcount, which just increments "costcount".
1642 * This tells us how many chars would be printed by using this string.
1643 */
1644 static int costcount;
1645
1646 /*ARGSUSED*/
inc_costcount(int c)1647 static int inc_costcount(int c)
1648 {
1649 costcount++;
1650 return (c);
1651 }
1652
cost(constant char * t)1653 static int cost(constant char *t)
1654 {
1655 costcount = 0;
1656 tputs(t, sc_height, inc_costcount);
1657 return (costcount);
1658 }
1659
1660 /*
1661 * Return the "best" of the two given termcap strings.
1662 * The best, if both exist, is the one with the lower
1663 * cost (see cost() function).
1664 */
cheaper(constant char * t1,constant char * t2,constant char * def)1665 static constant char * cheaper(constant char *t1, constant char *t2, constant char *def)
1666 {
1667 if (*t1 == '\0' && *t2 == '\0')
1668 {
1669 missing_cap = TRUE;
1670 return (def);
1671 }
1672 if (*t1 == '\0')
1673 return (t2);
1674 if (*t2 == '\0')
1675 return (t1);
1676 if (cost(t1) < cost(t2))
1677 return (t1);
1678 return (t2);
1679 }
1680
tmodes(constant char * inti,constant char * outti,constant char * intc,constant char * outtc,constant char ** instr,constant char ** outstr,constant char * def_instr,constant char * def_outstr,char ** spp)1681 static void tmodes(constant char *inti, constant char *outti, constant char *intc, constant char *outtc, constant char **instr, constant char **outstr, constant char *def_instr, constant char *def_outstr, char **spp)
1682 {
1683 *instr = ltgetstr(inti, intc, spp);
1684 if (*instr == NULL)
1685 {
1686 /* Use defaults. */
1687 *instr = def_instr;
1688 *outstr = def_outstr;
1689 return;
1690 }
1691
1692 *outstr = ltgetstr(outti, outtc, spp);
1693 if (*outstr == NULL)
1694 /* No specific out capability; use "me". */
1695 *outstr = ltgetstr("sgr0", "me", spp);
1696 if (*outstr == NULL)
1697 /* Don't even have "me"; use a null string. */
1698 *outstr = "";
1699 }
1700
1701 #endif /* MSDOS_COMPILER */
1702
1703
1704 /*
1705 * Below are the functions which perform all the
1706 * terminal-specific screen manipulation.
1707 */
1708
1709
1710 #if MSDOS_COMPILER
1711
1712 #if MSDOS_COMPILER==WIN32C
_settextposition(int row,int col)1713 static void _settextposition(int row, int col)
1714 {
1715 COORD cpos;
1716 CONSOLE_SCREEN_BUFFER_INFO csbi;
1717
1718 GetConsoleScreenBufferInfo(con_out, &csbi);
1719 cpos.X = csbi.srWindow.Left + (col - 1);
1720 cpos.Y = csbi.srWindow.Top + (row - 1);
1721 SetConsoleCursorPosition(con_out, cpos);
1722 }
1723 #endif
1724
1725 /*
1726 * Initialize the screen to the correct color at startup.
1727 */
initcolor(void)1728 static void initcolor(void)
1729 {
1730 #if MSDOS_COMPILER==BORLANDC || MSDOS_COMPILER==DJGPPC
1731 intensevideo();
1732 #endif
1733 SETCOLORS(nm_fg_color, nm_bg_color);
1734 #if 0
1735 /*
1736 * This clears the screen at startup. This is different from
1737 * the behavior of other versions of less. Disable it for now.
1738 */
1739 char *blanks;
1740 int row;
1741 int col;
1742
1743 /*
1744 * Create a complete, blank screen using "normal" colors.
1745 */
1746 SETCOLORS(nm_fg_color, nm_bg_color);
1747 blanks = (char *) ecalloc(width+1, sizeof(char));
1748 for (col = 0; col < sc_width; col++)
1749 blanks[col] = ' ';
1750 blanks[sc_width] = '\0';
1751 for (row = 0; row < sc_height; row++)
1752 _outtext(blanks);
1753 free(blanks);
1754 #endif
1755 }
1756 #endif
1757
1758 #if MSDOS_COMPILER==WIN32C
1759
1760 /*
1761 * Enable virtual terminal processing, if available.
1762 */
win32_init_vt_term(void)1763 static void win32_init_vt_term(void)
1764 {
1765 if (vt_enabled == 0 || (vt_enabled == 1 && con_out == con_out_ours))
1766 return; /* already initialized */
1767
1768 /* don't care about the initial mode, and win VT hard-enables am+xn */
1769 vt_enabled = SetConsoleMode(con_out, ENABLE_PROCESSED_OUTPUT |
1770 ENABLE_VIRTUAL_TERMINAL_PROCESSING |
1771 ENABLE_WRAP_AT_EOL_OUTPUT);
1772 if (vt_enabled)
1773 {
1774 auto_wrap = 1;
1775 defer_wrap = 1;
1776 }
1777 }
1778
win32_deinit_vt_term(void)1779 static void win32_deinit_vt_term(void)
1780 {
1781 if (vt_enabled == 1 && con_out == con_out_save)
1782 SetConsoleMode(con_out, init_console_output_mode);
1783 }
1784
1785 /*
1786 * Termcap-like init with a private win32 console.
1787 */
win32_init_term(void)1788 static void win32_init_term(void)
1789 {
1790 CONSOLE_SCREEN_BUFFER_INFO scr;
1791 COORD size;
1792
1793 if (con_out_save == INVALID_HANDLE_VALUE)
1794 return;
1795
1796 GetConsoleScreenBufferInfo(con_out_save, &scr);
1797
1798 if (con_out_ours == INVALID_HANDLE_VALUE)
1799 {
1800 /*
1801 * Create our own screen buffer, so that we
1802 * may restore the original when done.
1803 */
1804 con_out_ours = CreateConsoleScreenBuffer(
1805 GENERIC_WRITE | GENERIC_READ,
1806 FILE_SHARE_WRITE | FILE_SHARE_READ,
1807 (LPSECURITY_ATTRIBUTES) NULL,
1808 CONSOLE_TEXTMODE_BUFFER,
1809 (LPVOID) NULL);
1810
1811 /*
1812 * We don't care about the initial state. We need processed
1813 * output without anything else (no wrap at EOL, no VT,
1814 * no disabled auto-return).
1815 */
1816 if (SetConsoleMode(con_out_ours, ENABLE_PROCESSED_OUTPUT))
1817 auto_wrap = 0;
1818 }
1819
1820 size.X = scr.srWindow.Right - scr.srWindow.Left + 1;
1821 size.Y = scr.srWindow.Bottom - scr.srWindow.Top + 1;
1822 SetConsoleScreenBufferSize(con_out_ours, size);
1823 SetConsoleActiveScreenBuffer(con_out_ours);
1824 con_out = con_out_ours;
1825 }
1826
1827 /*
1828 * Restore the startup console.
1829 */
win32_deinit_term(void)1830 static void win32_deinit_term(void)
1831 {
1832 if (con_out_save == INVALID_HANDLE_VALUE)
1833 return;
1834 if (quitting)
1835 (void) CloseHandle(con_out_ours);
1836 SetConsoleActiveScreenBuffer(con_out_save);
1837 con_out = con_out_save;
1838 }
1839
1840 #endif
1841
1842 #if !MSDOS_COMPILER
do_tputs(constant char * str,int affcnt,int (* f_putc)(int))1843 static void do_tputs(constant char *str, int affcnt, int (*f_putc)(int))
1844 {
1845 #if LESSTEST
1846 if (is_lesstest() && f_putc == putchr)
1847 putstr(str);
1848 else
1849 #endif /*LESSTEST*/
1850 tputs(str, affcnt, f_putc);
1851 }
1852
1853 /*
1854 * Like tputs but we handle $<...> delay strings here because
1855 * some implementations of tputs don't perform delays correctly.
1856 */
ltputs(constant char * str,int affcnt,int (* f_putc)(int))1857 static void ltputs(constant char *str, int affcnt, int (*f_putc)(int))
1858 {
1859 while (str != NULL && *str != '\0')
1860 {
1861 constant char *obrac = strstr(str, "$<");
1862 if (obrac != NULL)
1863 {
1864 char str2[64];
1865 size_t slen = ptr_diff(obrac, str);
1866 if (slen < sizeof(str2))
1867 {
1868 int delay;
1869 /* Output first part of string (before "$<"). */
1870 memcpy(str2, str, slen);
1871 str2[slen] = '\0';
1872 do_tputs(str2, affcnt, f_putc);
1873 str += slen + 2;
1874 /* Perform the delay. */
1875 delay = lstrtoic(str, &str, 10);
1876 if (*str == '*')
1877 if (ckd_mul(&delay, delay, affcnt))
1878 delay = INT_MAX;
1879 flush();
1880 sleep_ms(delay);
1881 /* Skip past closing ">" at end of delay string. */
1882 str = strstr(str, ">");
1883 if (str != NULL)
1884 str++;
1885 continue;
1886 }
1887 }
1888 /* Pass the rest of the string to tputs and we're done. */
1889 do_tputs(str, affcnt, f_putc);
1890 break;
1891 }
1892 }
1893 #endif /* MSDOS_COMPILER */
1894
1895 /*
1896 * Configure the terminal so mouse clicks and wheel moves
1897 * produce input to less.
1898 */
init_mouse(void)1899 public void init_mouse(void)
1900 {
1901 #if !MSDOS_COMPILER
1902 ltputs(sc_s_mousecap, sc_height, putchr);
1903 #else
1904 #if MSDOS_COMPILER==WIN32C
1905 curr_console_input_mode = mouse_console_input_mode;
1906 SetConsoleMode(tty, curr_console_input_mode);
1907 #endif
1908 #endif
1909 }
1910
1911 /*
1912 * Configure the terminal so mouse clicks and wheel moves
1913 * are handled by the system (so text can be selected, etc).
1914 */
deinit_mouse(void)1915 public void deinit_mouse(void)
1916 {
1917 #if !MSDOS_COMPILER
1918 ltputs(sc_e_mousecap, sc_height, putchr);
1919 #else
1920 #if MSDOS_COMPILER==WIN32C
1921 curr_console_input_mode = base_console_input_mode;
1922 SetConsoleMode(tty, curr_console_input_mode);
1923 #endif
1924 #endif
1925 }
1926
1927 /*
1928 * Suspend screen updates.
1929 */
suspend_screen(void)1930 public void suspend_screen(void)
1931 {
1932 #if !MSDOS_COMPILER
1933 ltputs(sc_suspend, 1, putchr);
1934 #endif
1935 }
1936
1937 /*
1938 * Resume screen updates.
1939 */
resume_screen(void)1940 public void resume_screen(void)
1941 {
1942 #if !MSDOS_COMPILER
1943 ltputs(sc_resume, 1, putchr);
1944 #endif
1945 }
1946
1947 /*
1948 * Initialize terminal
1949 */
term_init(void)1950 public void term_init(void)
1951 {
1952 if (term_init_done)
1953 return;
1954 term_init_done = term_init_ever = TRUE;
1955 clear_bot_if_needed();
1956 #if !MSDOS_COMPILER
1957 if (!(quit_if_one_screen && one_screen))
1958 {
1959 if (!no_init)
1960 {
1961 ltputs(sc_init, sc_height, putchr);
1962 /*
1963 * Some terminals leave the cursor unmoved when switching
1964 * to the alt screen. To avoid having the text appear at
1965 * a seemingly random line on the alt screen, move to
1966 * lower left if we are using an alt screen.
1967 */
1968 if (*sc_init != '\0' && *sc_deinit != '\0' && !no_alt_screen)
1969 lower_left();
1970 term_addrs = TRUE;
1971 }
1972 if (!no_keypad)
1973 ltputs(sc_s_keypad, sc_height, putchr);
1974 if (mousecap)
1975 init_mouse();
1976 if (no_paste)
1977 init_bracketed_paste();
1978 }
1979 if (top_scroll)
1980 {
1981 int i;
1982
1983 /*
1984 * This is nice to terminals with no alternate screen,
1985 * but with saved scrolled-off-the-top lines. This way,
1986 * no previous line is lost, but we start with a whole
1987 * screen to ourself.
1988 */
1989 for (i = 1; i < sc_height; i++)
1990 putchr('\n');
1991 } else
1992 line_left();
1993 #else
1994 #if MSDOS_COMPILER==WIN32C
1995 if (!(quit_if_one_screen && one_screen))
1996 {
1997 if (!no_init)
1998 {
1999 win32_init_term();
2000 term_addrs = TRUE;
2001 }
2002 if (mousecap)
2003 init_mouse();
2004
2005 }
2006 win32_init_vt_term();
2007 #endif
2008 initcolor();
2009 flush();
2010 #endif
2011 }
2012
2013 /*
2014 * Deinitialize terminal
2015 */
term_deinit(void)2016 public void term_deinit(void)
2017 {
2018 if (!term_init_done)
2019 return;
2020 #if !MSDOS_COMPILER
2021 if (!(quit_if_one_screen && one_screen))
2022 {
2023 if (mousecap)
2024 deinit_mouse();
2025 if (no_paste)
2026 deinit_bracketed_paste();
2027 if (!no_keypad)
2028 ltputs(sc_e_keypad, sc_height, putchr);
2029 if (!no_init)
2030 ltputs(sc_deinit, sc_height, putchr);
2031 }
2032 #else
2033 /* Restore system colors. */
2034 SETCOLORS(sy_fg_color, sy_bg_color);
2035 #if MSDOS_COMPILER==WIN32C
2036 win32_deinit_vt_term();
2037 if (!(quit_if_one_screen && one_screen))
2038 {
2039 if (mousecap)
2040 deinit_mouse();
2041 if (!no_init)
2042 win32_deinit_term();
2043 }
2044 #else
2045 /* Need clreol to make SETCOLORS take effect. */
2046 clreol();
2047 #endif
2048 #endif
2049 term_init_done = FALSE;
2050 }
2051
2052 /*
2053 * Are we interactive (ie. writing to an initialized tty)?
2054 */
interactive(void)2055 public lbool interactive(void)
2056 {
2057 return (is_tty && term_init_done);
2058 }
2059
assert_interactive(void)2060 static void assert_interactive(void)
2061 {
2062 }
2063
2064 /*
2065 * Home cursor (move to upper left corner of screen).
2066 */
home(void)2067 public void home(void)
2068 {
2069 assert_interactive();
2070 #if !MSDOS_COMPILER
2071 ltputs(sc_home, 1, putchr);
2072 #else
2073 flush();
2074 _settextposition(1,1);
2075 #endif
2076 }
2077
2078 #if LESSTEST
dump_screen(void)2079 public void dump_screen(void)
2080 {
2081 char dump_cmd[32];
2082 SNPRINTF1(dump_cmd, sizeof(dump_cmd), ESCS"0;0;%dR", sc_width * sc_height);
2083 ltputs(dump_cmd, sc_height, putchr);
2084 flush();
2085 }
2086 #endif /*LESSTEST*/
2087
2088 /*
2089 * Add a blank line (called with cursor at home).
2090 * Should scroll the display down.
2091 */
add_line(void)2092 public void add_line(void)
2093 {
2094 assert_interactive();
2095 #if !MSDOS_COMPILER
2096 ltputs(sc_addline, sc_height, putchr);
2097 #else
2098 flush();
2099 #if MSDOS_COMPILER==MSOFTC
2100 _scrolltextwindow(_GSCROLLDOWN);
2101 _settextposition(1,1);
2102 #else
2103 #if MSDOS_COMPILER==BORLANDC || MSDOS_COMPILER==DJGPPC
2104 movetext(1,1, sc_width,sc_height-1, 1,2);
2105 gotoxy(1,1);
2106 clreol();
2107 #else
2108 #if MSDOS_COMPILER==WIN32C
2109 {
2110 CHAR_INFO fillchar;
2111 SMALL_RECT rcSrc, rcClip;
2112 COORD new_org;
2113 CONSOLE_SCREEN_BUFFER_INFO csbi;
2114
2115 GetConsoleScreenBufferInfo(con_out,&csbi);
2116
2117 /* The clip rectangle is the entire visible screen. */
2118 rcClip.Left = csbi.srWindow.Left;
2119 rcClip.Top = csbi.srWindow.Top;
2120 rcClip.Right = csbi.srWindow.Right;
2121 rcClip.Bottom = csbi.srWindow.Bottom;
2122
2123 /* The source rectangle is the visible screen minus the last line. */
2124 rcSrc = rcClip;
2125 rcSrc.Bottom--;
2126
2127 /* Move the top left corner of the source window down one row. */
2128 new_org.X = rcSrc.Left;
2129 new_org.Y = rcSrc.Top + 1;
2130
2131 /* Fill the right character and attributes. */
2132 fillchar.Char.AsciiChar = ' ';
2133 curr_attr = MAKEATTR(nm_fg_color, nm_bg_color);
2134 fillchar.Attributes = curr_attr;
2135 ScrollConsoleScreenBuffer(con_out, &rcSrc, &rcClip, new_org, &fillchar);
2136 _settextposition(1,1);
2137 }
2138 #endif
2139 #endif
2140 #endif
2141 #endif
2142 }
2143
2144 #if 0
2145 /*
2146 * Remove the n topmost lines and scroll everything below it in the
2147 * window upward. This is needed to stop leaking the topmost line
2148 * into the scrollback buffer when we go down-one-line (in WIN32).
2149 */
2150 public void remove_top(int n)
2151 {
2152 #if MSDOS_COMPILER==WIN32C
2153 SMALL_RECT rcSrc, rcClip;
2154 CHAR_INFO fillchar;
2155 COORD new_org;
2156 CONSOLE_SCREEN_BUFFER_INFO csbi; /* to get buffer info */
2157
2158 if (n >= sc_height - 1)
2159 {
2160 lclear();
2161 home();
2162 return;
2163 }
2164
2165 flush();
2166
2167 GetConsoleScreenBufferInfo(con_out, &csbi);
2168
2169 /* Get the extent of all-visible-rows-but-the-last. */
2170 rcSrc.Left = csbi.srWindow.Left;
2171 rcSrc.Top = csbi.srWindow.Top + n;
2172 rcSrc.Right = csbi.srWindow.Right;
2173 rcSrc.Bottom = csbi.srWindow.Bottom;
2174
2175 /* Get the clip rectangle. */
2176 rcClip.Left = rcSrc.Left;
2177 rcClip.Top = csbi.srWindow.Top;
2178 rcClip.Right = rcSrc.Right;
2179 rcClip.Bottom = rcSrc.Bottom ;
2180
2181 /* Move the source window up n rows. */
2182 new_org.X = rcSrc.Left;
2183 new_org.Y = rcSrc.Top - n;
2184
2185 /* Fill the right character and attributes. */
2186 fillchar.Char.AsciiChar = ' ';
2187 curr_attr = MAKEATTR(nm_fg_color, nm_bg_color);
2188 fillchar.Attributes = curr_attr;
2189
2190 ScrollConsoleScreenBuffer(con_out, &rcSrc, &rcClip, new_org, &fillchar);
2191
2192 /* Position cursor on first blank line. */
2193 goto_line(sc_height - n - 1);
2194 #endif
2195 }
2196 #endif
2197
2198 #if MSDOS_COMPILER==WIN32C
2199 /*
2200 * Clear the screen.
2201 */
win32_clear(void)2202 static void win32_clear(void)
2203 {
2204 /*
2205 * This will clear only the currently visible rows of the NT
2206 * console buffer, which means none of the precious scrollback
2207 * rows are touched making for faster scrolling. Note that, if
2208 * the window has fewer columns than the console buffer (i.e.
2209 * there is a horizontal scrollbar as well), the entire width
2210 * of the visible rows will be cleared.
2211 */
2212 COORD topleft;
2213 DWORD nchars;
2214 DWORD winsz;
2215 CONSOLE_SCREEN_BUFFER_INFO csbi;
2216
2217 /* get the number of cells in the current buffer */
2218 GetConsoleScreenBufferInfo(con_out, &csbi);
2219 winsz = csbi.dwSize.X * (csbi.srWindow.Bottom - csbi.srWindow.Top + 1);
2220 topleft.X = 0;
2221 topleft.Y = csbi.srWindow.Top;
2222
2223 curr_attr = MAKEATTR(nm_fg_color, nm_bg_color);
2224 FillConsoleOutputCharacter(con_out, ' ', winsz, topleft, &nchars);
2225 FillConsoleOutputAttribute(con_out, curr_attr, winsz, topleft, &nchars);
2226 }
2227
2228 /*
2229 * Remove the n topmost lines and scroll everything below it in the
2230 * window upward.
2231 */
win32_scroll_up(int n)2232 public void win32_scroll_up(int n)
2233 {
2234 SMALL_RECT rcSrc, rcClip;
2235 CHAR_INFO fillchar;
2236 COORD topleft;
2237 COORD new_org;
2238 DWORD nchars;
2239 DWORD size;
2240 CONSOLE_SCREEN_BUFFER_INFO csbi;
2241
2242 if (n <= 0)
2243 return;
2244
2245 if (n >= sc_height - 1)
2246 {
2247 win32_clear();
2248 _settextposition(1,1);
2249 return;
2250 }
2251
2252 /* Get the extent of what will remain visible after scrolling. */
2253 GetConsoleScreenBufferInfo(con_out, &csbi);
2254 rcSrc.Left = csbi.srWindow.Left;
2255 rcSrc.Top = csbi.srWindow.Top + n;
2256 rcSrc.Right = csbi.srWindow.Right;
2257 rcSrc.Bottom = csbi.srWindow.Bottom;
2258
2259 /* Get the clip rectangle. */
2260 rcClip.Left = rcSrc.Left;
2261 rcClip.Top = csbi.srWindow.Top;
2262 rcClip.Right = rcSrc.Right;
2263 rcClip.Bottom = rcSrc.Bottom ;
2264
2265 /* Move the source text to the top of the screen. */
2266 new_org.X = rcSrc.Left;
2267 new_org.Y = rcClip.Top;
2268
2269 /* Fill the right character and attributes. */
2270 fillchar.Char.AsciiChar = ' ';
2271 fillchar.Attributes = MAKEATTR(nm_fg_color, nm_bg_color);
2272
2273 /* Scroll the window. */
2274 SetConsoleTextAttribute(con_out, fillchar.Attributes);
2275 ScrollConsoleScreenBuffer(con_out, &rcSrc, &rcClip, new_org, &fillchar);
2276
2277 /* Clear remaining lines at bottom. */
2278 topleft.X = csbi.dwCursorPosition.X;
2279 topleft.Y = rcSrc.Bottom - n;
2280 size = (n * csbi.dwSize.X) + (rcSrc.Right - topleft.X);
2281 FillConsoleOutputCharacter(con_out, ' ', size, topleft,
2282 &nchars);
2283 FillConsoleOutputAttribute(con_out, fillchar.Attributes, size, topleft,
2284 &nchars);
2285 SetConsoleTextAttribute(con_out, curr_attr);
2286
2287 /* Move cursor n lines up from where it was. */
2288 csbi.dwCursorPosition.Y -= n;
2289 SetConsoleCursorPosition(con_out, csbi.dwCursorPosition);
2290 }
2291 #endif
2292
2293 /*
2294 * Move cursor to lower left corner of screen.
2295 */
lower_left(void)2296 public void lower_left(void)
2297 {
2298 assert_interactive();
2299 #if !MSDOS_COMPILER
2300 ltputs(sc_lower_left, 1, putchr);
2301 #else
2302 flush();
2303 _settextposition(sc_height, 1);
2304 #endif
2305 }
2306
2307 /*
2308 * Move cursor to left position of current line.
2309 */
line_left(void)2310 public void line_left(void)
2311 {
2312 assert_interactive();
2313 #if !MSDOS_COMPILER
2314 ltputs(sc_return, 1, putchr);
2315 #else
2316 {
2317 int row;
2318 flush();
2319 #if MSDOS_COMPILER==WIN32C
2320 {
2321 CONSOLE_SCREEN_BUFFER_INFO scr;
2322 GetConsoleScreenBufferInfo(con_out, &scr);
2323 row = scr.dwCursorPosition.Y - scr.srWindow.Top + 1;
2324 }
2325 #else
2326 #if MSDOS_COMPILER==BORLANDC || MSDOS_COMPILER==DJGPPC
2327 row = wherey();
2328 #else
2329 {
2330 struct rccoord tpos = _gettextposition();
2331 row = tpos.row;
2332 }
2333 #endif
2334 #endif
2335 _settextposition(row, 1);
2336 }
2337 #endif
2338 }
2339
2340 /*
2341 * Check if the console size has changed and reset internals
2342 * (in lieu of SIGWINCH for WIN32).
2343 */
check_winch(void)2344 public void check_winch(void)
2345 {
2346 #if MSDOS_COMPILER==WIN32C
2347 CONSOLE_SCREEN_BUFFER_INFO scr;
2348 COORD size;
2349
2350 if (con_out == INVALID_HANDLE_VALUE)
2351 return;
2352
2353 flush();
2354 GetConsoleScreenBufferInfo(con_out, &scr);
2355 size.Y = scr.srWindow.Bottom - scr.srWindow.Top + 1;
2356 size.X = scr.srWindow.Right - scr.srWindow.Left + 1;
2357 if (size.Y != sc_height || size.X != sc_width)
2358 {
2359 sc_height = size.Y;
2360 sc_width = size.X;
2361 if (!no_init && con_out_ours == con_out)
2362 SetConsoleScreenBufferSize(con_out, size);
2363 pos_init();
2364 screen_size_changed();
2365 screen_trashed();
2366 }
2367 #endif
2368 }
2369
2370 /*
2371 * Goto a specific line on the screen.
2372 */
goto_line(int sindex)2373 public void goto_line(int sindex)
2374 {
2375 assert_interactive();
2376 #if !MSDOS_COMPILER
2377 ltputs(ltgoto(sc_move, 0, sindex), 1, putchr);
2378 #else
2379 flush();
2380 _settextposition(sindex+1, 1);
2381 #endif
2382 }
2383
2384 #if MSDOS_COMPILER==MSOFTC || MSDOS_COMPILER==BORLANDC
2385 /*
2386 * Create an alternate screen which is all white.
2387 * This screen is used to create a "flash" effect, by displaying it
2388 * briefly and then switching back to the normal screen.
2389 * {{ Yuck! There must be a better way to get a visual bell. }}
2390 */
create_flash(void)2391 static void create_flash(void)
2392 {
2393 #if MSDOS_COMPILER==MSOFTC
2394 struct videoconfig w;
2395 char *blanks;
2396 int row, col;
2397
2398 _getvideoconfig(&w);
2399 videopages = w.numvideopages;
2400 if (videopages < 2)
2401 {
2402 at_enter(AT_STANDOUT);
2403 at_exit();
2404 } else
2405 {
2406 _setactivepage(1);
2407 at_enter(AT_STANDOUT);
2408 blanks = (char *) ecalloc(w.numtextcols, sizeof(char));
2409 for (col = 0; col < w.numtextcols; col++)
2410 blanks[col] = ' ';
2411 for (row = w.numtextrows; row > 0; row--)
2412 _outmem(blanks, w.numtextcols);
2413 _setactivepage(0);
2414 _setvisualpage(0);
2415 free(blanks);
2416 at_exit();
2417 }
2418 #else
2419 #if MSDOS_COMPILER==BORLANDC
2420 int n;
2421
2422 whitescreen = (unsigned short *)
2423 malloc(sc_width * sc_height * sizeof(short));
2424 if (whitescreen == NULL)
2425 return;
2426 for (n = 0; n < sc_width * sc_height; n++)
2427 whitescreen[n] = 0x7020;
2428 #endif
2429 #endif
2430 flash_created = 1;
2431 }
2432 #endif /* MSDOS_COMPILER */
2433
2434 /*
2435 * Output the "visual bell", if there is one.
2436 */
vbell(void)2437 public void vbell(void)
2438 {
2439 if (no_vbell)
2440 return;
2441 #if !MSDOS_COMPILER
2442 if (*sc_visual_bell == '\0')
2443 return;
2444 ltputs(sc_visual_bell, sc_height, putchr);
2445 #else
2446 #if MSDOS_COMPILER==DJGPPC
2447 ScreenVisualBell();
2448 #else
2449 #if MSDOS_COMPILER==MSOFTC
2450 /*
2451 * Create a flash screen on the second video page.
2452 * Switch to that page, then switch back.
2453 */
2454 if (!flash_created)
2455 create_flash();
2456 if (videopages < 2)
2457 return;
2458 _setvisualpage(1);
2459 delay(100);
2460 _setvisualpage(0);
2461 #else
2462 #if MSDOS_COMPILER==BORLANDC
2463 unsigned short *currscreen;
2464
2465 /*
2466 * Get a copy of the current screen.
2467 * Display the flash screen.
2468 * Then restore the old screen.
2469 */
2470 if (!flash_created)
2471 create_flash();
2472 if (whitescreen == NULL)
2473 return;
2474 currscreen = (unsigned short *)
2475 malloc(sc_width * sc_height * sizeof(short));
2476 if (currscreen == NULL) return;
2477 gettext(1, 1, sc_width, sc_height, currscreen);
2478 puttext(1, 1, sc_width, sc_height, whitescreen);
2479 delay(100);
2480 puttext(1, 1, sc_width, sc_height, currscreen);
2481 free(currscreen);
2482 #else
2483 #if MSDOS_COMPILER==WIN32C
2484 /* paint screen with an inverse color */
2485 lclear();
2486
2487 /* leave it displayed for 100 msec. */
2488 Sleep(100);
2489
2490 /* restore with a redraw */
2491 repaint();
2492 #endif
2493 #endif
2494 #endif
2495 #endif
2496 #endif
2497 }
2498
2499 /*
2500 * Make a noise.
2501 */
lbeep(void)2502 static void lbeep(void)
2503 {
2504 #if !MSDOS_COMPILER
2505 putchr(CONTROL('G'));
2506 #else
2507 #if MSDOS_COMPILER==WIN32C
2508 MessageBeep(0);
2509 #else
2510 write(1, "\7", 1);
2511 #endif
2512 #endif
2513 }
2514
2515 /*
2516 * Ring the terminal bell.
2517 */
lbell(void)2518 public void lbell(void)
2519 {
2520 if (quiet == VERY_QUIET)
2521 vbell();
2522 else
2523 lbeep();
2524 }
2525
2526 /*
2527 * Clear the screen.
2528 */
lclear(void)2529 public void lclear(void)
2530 {
2531 assert_interactive();
2532 suspend_screen();
2533 #if !MSDOS_COMPILER
2534 ltputs(sc_clear, sc_height, putchr);
2535 #else
2536 flush();
2537 #if MSDOS_COMPILER==WIN32C
2538 win32_clear();
2539 #else
2540 _clearscreen(_GCLEARSCREEN);
2541 #endif
2542 #endif
2543 }
2544
2545 /*
2546 * Clear from the cursor to the end of the cursor's line.
2547 * {{ This must not move the cursor. }}
2548 */
clear_eol(void)2549 public void clear_eol(void)
2550 {
2551 /* assert_interactive();*/
2552 #if !MSDOS_COMPILER
2553 ltputs(sc_eol_clear, 1, putchr);
2554 #else
2555 #if MSDOS_COMPILER==MSOFTC
2556 short top, left;
2557 short bot, right;
2558 struct rccoord tpos;
2559
2560 flush();
2561 /*
2562 * Save current state.
2563 */
2564 tpos = _gettextposition();
2565 _gettextwindow(&top, &left, &bot, &right);
2566 /*
2567 * Set a temporary window to the current line,
2568 * from the cursor's position to the right edge of the screen.
2569 * Then clear that window.
2570 */
2571 _settextwindow(tpos.row, tpos.col, tpos.row, sc_width);
2572 _clearscreen(_GWINDOW);
2573 /*
2574 * Restore state.
2575 */
2576 _settextwindow(top, left, bot, right);
2577 _settextposition(tpos.row, tpos.col);
2578 #else
2579 #if MSDOS_COMPILER==BORLANDC || MSDOS_COMPILER==DJGPPC
2580 flush();
2581 clreol();
2582 #else
2583 #if MSDOS_COMPILER==WIN32C
2584 DWORD nchars;
2585 COORD cpos;
2586 CONSOLE_SCREEN_BUFFER_INFO scr;
2587
2588 flush();
2589 memset(&scr, 0, sizeof(scr));
2590 GetConsoleScreenBufferInfo(con_out, &scr);
2591 cpos.X = scr.dwCursorPosition.X;
2592 cpos.Y = scr.dwCursorPosition.Y;
2593 curr_attr = MAKEATTR(nm_fg_color, nm_bg_color);
2594 FillConsoleOutputAttribute(con_out, curr_attr,
2595 scr.dwSize.X - cpos.X, cpos, &nchars);
2596 FillConsoleOutputCharacter(con_out, ' ',
2597 scr.dwSize.X - cpos.X, cpos, &nchars);
2598 #endif
2599 #endif
2600 #endif
2601 #endif
2602 }
2603
2604 /*
2605 * Clear the current line.
2606 * Clear the screen if there's off-screen memory below the display.
2607 */
clear_eol_bot(void)2608 static void clear_eol_bot(void)
2609 {
2610 assert_interactive();
2611 #if MSDOS_COMPILER
2612 clear_eol();
2613 #else
2614 if (below_mem)
2615 ltputs(sc_eos_clear, 1, putchr);
2616 else
2617 ltputs(sc_eol_clear, 1, putchr);
2618 #endif
2619 }
2620
2621 /*
2622 * Clear the bottom line of the display.
2623 * Leave the cursor at the beginning of the bottom line.
2624 */
clear_bot(void)2625 public void clear_bot(void)
2626 {
2627 /*
2628 * If we're in a non-normal attribute mode, temporarily exit
2629 * the mode while we do the clear. Some terminals fill the
2630 * cleared area with the current attribute.
2631 */
2632 if (oldbot)
2633 lower_left();
2634 else
2635 line_left();
2636
2637 if (attrmode == AT_NORMAL)
2638 clear_eol_bot();
2639 else
2640 {
2641 int saved_attrmode = attrmode;
2642
2643 at_exit();
2644 clear_eol_bot();
2645 at_enter(saved_attrmode);
2646 }
2647 }
2648
2649 /*
2650 * Enable or disable bracketed paste mode.
2651 * When enabled, the terminal sends an "open bracket" sequence
2652 * before pasted content and "close bracket" after it.
2653 */
init_bracketed_paste(void)2654 public void init_bracketed_paste(void)
2655 {
2656 #if !MSDOS_COMPILER
2657 ltputs(sc_s_bracketed_paste, 1, putchr);
2658 #endif
2659 }
2660
deinit_bracketed_paste(void)2661 public void deinit_bracketed_paste(void)
2662 {
2663 #if !MSDOS_COMPILER
2664 ltputs(sc_e_bracketed_paste, 1, putchr);
2665 #endif
2666 }
2667
2668 /*
2669 * Color string may be "x[y]" where x and y are 4-bit color chars,
2670 * or "N[.M]" where N and M are decimal integers>
2671 * Any of x,y,N,M may also be "-" to mean "unchanged".
2672 */
2673
2674 /*
2675 * Parse a 4-bit color char.
2676 */
parse_color4(char ch)2677 static int parse_color4(char ch)
2678 {
2679 switch (ch)
2680 {
2681 case 'k': return 0;
2682 case 'r': return CV_RED;
2683 case 'g': return CV_GREEN;
2684 case 'y': return CV_RED|CV_GREEN;
2685 case 'b': return CV_BLUE;
2686 case 'm': return CV_RED|CV_BLUE;
2687 case 'c': return CV_GREEN|CV_BLUE;
2688 case 'w': return CV_RED|CV_GREEN|CV_BLUE;
2689 case 'K': return 0|CV_BRIGHT;
2690 case 'R': return CV_RED|CV_BRIGHT;
2691 case 'G': return CV_GREEN|CV_BRIGHT;
2692 case 'Y': return CV_RED|CV_GREEN|CV_BRIGHT;
2693 case 'B': return CV_BLUE|CV_BRIGHT;
2694 case 'M': return CV_RED|CV_BLUE|CV_BRIGHT;
2695 case 'C': return CV_GREEN|CV_BLUE|CV_BRIGHT;
2696 case 'W': return CV_RED|CV_GREEN|CV_BLUE|CV_BRIGHT;
2697 case '-': return CV_NOCHANGE;
2698 default: return CV_ERROR;
2699 }
2700 }
2701
2702 /*
2703 * Parse a color as a decimal integer.
2704 */
parse_color6(constant char ** ps)2705 static int parse_color6(constant char **ps)
2706 {
2707 if (**ps == '-')
2708 {
2709 (*ps)++;
2710 return CV_NOCHANGE;
2711 } else
2712 {
2713 constant char *os = *ps;
2714 int color = lstrtoic(os, ps, 10);
2715 if (color < 0 || *ps == os)
2716 return CV_ERROR;
2717 return color;
2718 }
2719 }
2720
2721 /*
2722 * Parse a color pair and return the foreground/background/attribute values.
2723 * Return type of color specifier:
2724 * CV_4BIT: fg/bg values are OR of CV_{RGB} bits.
2725 * CV_6BIT: fg/bg values are integers entered by user.
2726 */
parse_color(constant char * str,mutable int * p_fg,mutable int * p_bg,mutable CHAR_ATTR * p_cattr)2727 public COLOR_TYPE parse_color(constant char *str, mutable int *p_fg, mutable int *p_bg, mutable CHAR_ATTR *p_cattr)
2728 {
2729 int fg;
2730 int bg = CV_ERROR;
2731 CHAR_ATTR cattr = CATTR_NULL;
2732 COLOR_TYPE type = CT_NULL;
2733
2734 if (str == NULL || *str == '\0')
2735 return CT_NULL;
2736 if (*str == '+')
2737 str++; /* ignore leading + */
2738
2739 fg = parse_color4(*str);
2740 if (fg != CV_ERROR)
2741 {
2742 if (str[1] == '\0' || strchr("*~_&dsul", str[1]) != NULL)
2743 {
2744 bg = CV_NOCHANGE;
2745 str++; /* skip the fg char */
2746 } else
2747 {
2748 bg = parse_color4(str[1]);
2749 if (bg != CV_ERROR)
2750 str += 2; /* skip both fg and bg chars */
2751 }
2752 }
2753 if (fg != CV_ERROR && bg != CV_ERROR)
2754 type = CT_4BIT;
2755 else
2756 {
2757 fg = (*str == '.') ? CV_NOCHANGE : parse_color6(&str);
2758 if (fg != CV_ERROR)
2759 {
2760 if (*str != '.')
2761 bg = CV_NOCHANGE;
2762 else
2763 {
2764 str++; /* skip the dot */
2765 bg = parse_color6(&str);
2766 }
2767 }
2768 if (fg != CV_ERROR && bg != CV_ERROR)
2769 type = CT_6BIT;
2770 }
2771 if (type != CT_NULL)
2772 {
2773 for (;; str++)
2774 {
2775 if (*str == '*' || *str == 'd')
2776 cattr |= CATTR_BOLD;
2777 else if (*str == '~' || *str == 's')
2778 cattr |= CATTR_STANDOUT;
2779 else if (*str == '_' || *str == 'u')
2780 cattr |= CATTR_UNDERLINE;
2781 else if (*str == '&' || *str == 'l') /* can't use 'k' because of conflict with "black" */
2782 cattr |= CATTR_BLINK;
2783 else
2784 break;
2785 }
2786 if (p_fg != NULL) *p_fg = fg;
2787 if (p_bg != NULL) *p_bg = bg;
2788 if (p_cattr != NULL) *p_cattr = cattr;
2789 }
2790 return type;
2791 }
2792
2793 #if !MSDOS_COMPILER
2794
sgr_color(int color)2795 static int sgr_color(int color)
2796 {
2797 switch (color)
2798 {
2799 case 0: return 30;
2800 case CV_RED: return 31;
2801 case CV_GREEN: return 32;
2802 case CV_RED|CV_GREEN: return 33;
2803 case CV_BLUE: return 34;
2804 case CV_RED|CV_BLUE: return 35;
2805 case CV_GREEN|CV_BLUE: return 36;
2806 case CV_RED|CV_GREEN|CV_BLUE: return 37;
2807
2808 case CV_BRIGHT: return 90;
2809 case CV_RED|CV_BRIGHT: return 91;
2810 case CV_GREEN|CV_BRIGHT: return 92;
2811 case CV_RED|CV_GREEN|CV_BRIGHT: return 93;
2812 case CV_BLUE|CV_BRIGHT: return 94;
2813 case CV_RED|CV_BLUE|CV_BRIGHT: return 95;
2814 case CV_GREEN|CV_BLUE|CV_BRIGHT: return 96;
2815 case CV_RED|CV_GREEN|CV_BLUE|CV_BRIGHT: return 97;
2816
2817 default: return color;
2818 }
2819 }
2820
tput_fmt(constant char * fmt,int color,int (* f_putc)(int))2821 static void tput_fmt(constant char *fmt, int color, int (*f_putc)(int))
2822 {
2823 char buf[INT_STRLEN_BOUND(int)+16];
2824 if (color == attrcolor)
2825 return;
2826 SNPRINTF1(buf, sizeof(buf), fmt, color);
2827 ltputs(buf, 1, f_putc);
2828 attrcolor = color;
2829 }
2830
tput_char_cattr(CHAR_ATTR cattr,int (* f_putc)(int))2831 static void tput_char_cattr(CHAR_ATTR cattr, int (*f_putc)(int))
2832 {
2833 if (cattr & CATTR_UNDERLINE)
2834 ltputs(sc_u_in, 1, f_putc);
2835 if (cattr & CATTR_BOLD)
2836 ltputs(sc_b_in, 1, f_putc);
2837 if (cattr & CATTR_BLINK)
2838 ltputs(sc_bl_in, 1, f_putc);
2839 if (cattr & CATTR_STANDOUT)
2840 ltputs(sc_s_in, 1, f_putc);
2841 }
2842
tput_color(constant char * str,int (* f_putc)(int))2843 static void tput_color(constant char *str, int (*f_putc)(int))
2844 {
2845 int fg;
2846 int bg;
2847 CHAR_ATTR cattr;
2848
2849 if (str != NULL && strcmp(str, "*") == 0)
2850 {
2851 /* Special case: reset to normal */
2852 tput_fmt(ESCS"[m", -1, f_putc);
2853 return;
2854 }
2855 switch (parse_color(str, &fg, &bg, &cattr))
2856 {
2857 case CT_4BIT:
2858 if (fg >= 0)
2859 tput_fmt(ESCS"[%dm", sgr_color(fg), f_putc);
2860 if (bg >= 0)
2861 tput_fmt(ESCS"[%dm", sgr_color(bg)+10, f_putc);
2862 tput_char_cattr(cattr, f_putc);
2863 break;
2864 case CT_6BIT:
2865 if (fg >= 0)
2866 tput_fmt(ESCS"[38;5;%dm", fg, f_putc);
2867 if (bg >= 0)
2868 tput_fmt(ESCS"[48;5;%dm", bg, f_putc);
2869 tput_char_cattr(cattr, f_putc);
2870 break;
2871 default:
2872 break;
2873 }
2874 }
2875
tput_inmode(constant char * mode_str,int attr,int attr_bit,int (* f_putc)(int))2876 static void tput_inmode(constant char *mode_str, int attr, int attr_bit, int (*f_putc)(int))
2877 {
2878 constant char *color_str;
2879 if ((attr & attr_bit) == 0)
2880 return;
2881 color_str = get_color_map(attr_bit);
2882 if (color_str == NULL || *color_str == '\0' || *color_str == '+')
2883 {
2884 ltputs(mode_str, 1, f_putc);
2885 if (color_str == NULL || *color_str++ != '+')
2886 return;
2887 }
2888 /* Color overrides mode string */
2889 tput_color(color_str, f_putc);
2890 }
2891
tput_outmode(constant char * mode_str,int attr_bit,int (* f_putc)(int))2892 static void tput_outmode(constant char *mode_str, int attr_bit, int (*f_putc)(int))
2893 {
2894 if ((attrmode & attr_bit) == 0)
2895 return;
2896 ltputs(mode_str, 1, f_putc);
2897 }
2898
2899 #else /* MSDOS_COMPILER */
2900
2901 #if MSDOS_COMPILER==WIN32C
WIN32put_fmt(constant char * fmt,int color)2902 static lbool WIN32put_fmt(constant char *fmt, int color)
2903 {
2904 char buf[INT_STRLEN_BOUND(int)+16];
2905 int len = (size_t) SNPRINTF1(buf, sizeof(buf), fmt, color);
2906 if (len > 0)
2907 WIN32textout(buf, (size_t) len);
2908 return TRUE;
2909 }
2910
win_set_cattr(CHAR_ATTR cattr)2911 static void win_set_cattr(CHAR_ATTR cattr)
2912 {
2913 if (cattr & CATTR_UNDERLINE)
2914 WIN32textout(ESCS"[4m", 4);
2915 if (cattr & CATTR_BOLD)
2916 WIN32textout(ESCS"[1m", 4);
2917 if (cattr & CATTR_BLINK)
2918 WIN32textout(ESCS"[5m", 4);
2919 if (cattr & CATTR_STANDOUT)
2920 WIN32textout(ESCS"[7m", 4);
2921 }
2922 #endif
2923
win_set_color(int attr)2924 static lbool win_set_color(int attr)
2925 {
2926 int fg;
2927 int bg;
2928 CHAR_ATTR cattr;
2929 lbool out = FALSE;
2930 constant char *str = get_color_map(attr);
2931 if (str == NULL || str[0] == '\0')
2932 return FALSE;
2933 switch (parse_color(str, &fg, &bg, &cattr))
2934 {
2935 case CT_4BIT:
2936 if (fg >= 0 && bg >= 0)
2937 {
2938 SETCOLORS(fg, bg);
2939 out = TRUE;
2940 } else if (fg >= 0)
2941 {
2942 SET_FG_COLOR(fg);
2943 out = TRUE;
2944 } else if (bg >= 0)
2945 {
2946 SET_BG_COLOR(bg);
2947 out = TRUE;
2948 }
2949 #if MSDOS_COMPILER==WIN32C
2950 if (vt_enabled)
2951 win_set_cattr(cattr);
2952 #endif
2953 break;
2954 #if MSDOS_COMPILER==WIN32C
2955 case CT_6BIT:
2956 if (vt_enabled)
2957 {
2958 if (fg > 0)
2959 out = WIN32put_fmt(ESCS"[38;5;%dm", fg);
2960 if (bg > 0)
2961 out = WIN32put_fmt(ESCS"[48;5;%dm", bg);
2962 win_set_cattr(cattr);
2963 }
2964 break;
2965 #endif
2966 default:
2967 break;
2968 }
2969 return out;
2970 }
2971
2972 #endif /* MSDOS_COMPILER */
2973
at_enter(int attr)2974 public void at_enter(int attr)
2975 {
2976 attr = apply_at_specials(attr);
2977 #if !MSDOS_COMPILER
2978 /* The one with the most priority is last. */
2979 tput_inmode(sc_u_in, attr, AT_UNDERLINE, putchr);
2980 tput_inmode(sc_b_in, attr, AT_BOLD, putchr);
2981 tput_inmode(sc_bl_in, attr, AT_BLINK, putchr);
2982 /* Don't use standout and color at the same time. */
2983 if (use_color && (attr & AT_COLOR))
2984 tput_color(get_color_map(attr), putchr);
2985 else
2986 tput_inmode(sc_s_in, attr, AT_STANDOUT, putchr);
2987 #else
2988 flush();
2989 /* The one with the most priority is first. */
2990 if ((attr & AT_COLOR) && use_color)
2991 {
2992 win_set_color(attr);
2993 } else if (attr & AT_STANDOUT)
2994 {
2995 SETCOLORS(so_fg_color, so_bg_color);
2996 } else if (attr & AT_BLINK)
2997 {
2998 SETCOLORS(bl_fg_color, bl_bg_color);
2999 } else if (attr & AT_BOLD)
3000 {
3001 SETCOLORS(bo_fg_color, bo_bg_color);
3002 } else if (attr & AT_UNDERLINE)
3003 {
3004 SETCOLORS(ul_fg_color, ul_bg_color);
3005 }
3006 #endif
3007 attrmode = attr;
3008 }
3009
at_exit(void)3010 public void at_exit(void)
3011 {
3012 #if !MSDOS_COMPILER
3013 /* Undo things in the reverse order we did them. */
3014 tput_color("*", putchr);
3015 tput_outmode(sc_s_out, AT_STANDOUT, putchr);
3016 tput_outmode(sc_bl_out, AT_BLINK, putchr);
3017 tput_outmode(sc_b_out, AT_BOLD, putchr);
3018 tput_outmode(sc_u_out, AT_UNDERLINE, putchr);
3019 #else
3020 flush();
3021 SETCOLORS(nm_fg_color, nm_bg_color);
3022 #endif
3023 attrmode = AT_NORMAL;
3024 }
3025
at_switch(int attr)3026 public void at_switch(int attr)
3027 {
3028 int new_attrmode = apply_at_specials(attr);
3029 int ignore_modes = AT_ANSI;
3030
3031 if ((new_attrmode & ~ignore_modes) != (attrmode & ~ignore_modes))
3032 {
3033 at_exit();
3034 at_enter(attr);
3035 }
3036 }
3037
is_at_equiv(int attr1,int attr2)3038 public lbool is_at_equiv(int attr1, int attr2)
3039 {
3040 attr1 = apply_at_specials(attr1);
3041 attr2 = apply_at_specials(attr2);
3042
3043 return (attr1 == attr2);
3044 }
3045
apply_at_specials(int attr)3046 public int apply_at_specials(int attr)
3047 {
3048 if (attr & AT_BINARY)
3049 attr |= binattr;
3050 if (attr & AT_HILITE)
3051 attr |= AT_STANDOUT;
3052 attr &= ~(AT_BINARY|AT_HILITE);
3053
3054 return attr;
3055 }
3056
3057 /*
3058 * Output a plain backspace, without erasing the previous char.
3059 */
putbs(void)3060 public void putbs(void)
3061 {
3062 if (termcap_debug)
3063 putstr("<bs>");
3064 else
3065 {
3066 #if !MSDOS_COMPILER
3067 ltputs(sc_backspace, 1, putchr);
3068 #else
3069 int row, col;
3070
3071 flush();
3072 {
3073 #if MSDOS_COMPILER==MSOFTC
3074 struct rccoord tpos;
3075 tpos = _gettextposition();
3076 row = tpos.row;
3077 col = tpos.col;
3078 #else
3079 #if MSDOS_COMPILER==BORLANDC || MSDOS_COMPILER==DJGPPC
3080 row = wherey();
3081 col = wherex();
3082 #else
3083 #if MSDOS_COMPILER==WIN32C
3084 CONSOLE_SCREEN_BUFFER_INFO scr;
3085 GetConsoleScreenBufferInfo(con_out, &scr);
3086 row = scr.dwCursorPosition.Y - scr.srWindow.Top + 1;
3087 col = scr.dwCursorPosition.X - scr.srWindow.Left + 1;
3088 #endif
3089 #endif
3090 #endif
3091 }
3092 if (col <= 1)
3093 return;
3094 _settextposition(row, col-1);
3095 #endif /* MSDOS_COMPILER */
3096 }
3097 }
3098
3099 #if MSDOS_COMPILER==WIN32C
3100
3101 #define WIN32_MAX_REPEAT 3
3102 #define LAST_DOWN_COUNT 8
3103 static LWCHAR last_downs[LAST_DOWN_COUNT] = { 0 };
3104 static int last_down_index = 0;
3105 static LWCHAR hi_surr = 0;
3106
3107 typedef struct XINPUT_RECORD {
3108 INPUT_RECORD ir;
3109 LWCHAR ichar; /* because ir...UnicodeChar is only 16 bits */
3110 } XINPUT_RECORD;
3111
3112 typedef struct WIN32_CHAR {
3113 struct WIN32_CHAR *wc_next;
3114 int wc_ch;
3115 } WIN32_CHAR;
3116
3117 static WIN32_CHAR *win32_queue = NULL;
3118
3119 /*
3120 * Is the win32_queue nonempty?
3121 */
win32_queued_char(void)3122 static lbool win32_queued_char(void)
3123 {
3124 return (win32_queue != NULL);
3125 }
3126
3127 /*
3128 * Push a char onto the back of the win32_queue.
3129 */
win32_enqueue(int ch)3130 static void win32_enqueue(int ch)
3131 {
3132 WIN32_CHAR *wch = (WIN32_CHAR *) ecalloc(1, sizeof(WIN32_CHAR));
3133 wch->wc_ch = ch;
3134 wch->wc_next = NULL;
3135 if (win32_queue == NULL)
3136 win32_queue = wch;
3137 else
3138 {
3139 WIN32_CHAR *pch;
3140 for (pch = win32_queue; pch->wc_next != NULL; pch = pch->wc_next)
3141 continue;
3142 pch->wc_next = wch;
3143 }
3144 }
3145
3146 /*
3147 * Push a char onto the front of the win32_queue.
3148 * Makes the next call to WIN32getch return ch.
3149 */
WIN32ungetch(int ch)3150 public void WIN32ungetch(int ch)
3151 {
3152 WIN32_CHAR *wch = (WIN32_CHAR *) ecalloc(1, sizeof(WIN32_CHAR));
3153 wch->wc_ch = ch;
3154 wch->wc_next = win32_queue;
3155 win32_queue = wch;
3156 }
3157
3158 /*
3159 * Get a char from the front of the win32_queue.
3160 */
win32_get_queue(void)3161 static int win32_get_queue(void)
3162 {
3163 WIN32_CHAR *wch = win32_queue;
3164 int ch = wch->wc_ch;
3165 win32_queue = wch->wc_next;
3166 free(wch);
3167 return ch;
3168 }
3169
3170 /*
3171 * Handle a mouse input event.
3172 */
win32_mouse_event(XINPUT_RECORD * xip)3173 static lbool win32_mouse_event(XINPUT_RECORD *xip)
3174 {
3175 char b;
3176
3177 if (!mousecap || xip->ir.EventType != MOUSE_EVENT)
3178 return (FALSE);
3179
3180 /* Generate an X11 mouse sequence from the mouse event. */
3181 /* TODO: switch to the 1006 protocol to allow specific-button-up reports */
3182 switch (xip->ir.Event.MouseEvent.dwEventFlags)
3183 {
3184 case 0: /* press or release */
3185 if (xip->ir.Event.MouseEvent.dwButtonState == 0)
3186 b = X11MOUSE_OFFSET + X11MOUSE_BUTTON_REL;
3187 else if (xip->ir.Event.MouseEvent.dwButtonState == 1) /* leftmost */
3188 b = X11MOUSE_OFFSET + X11MOUSE_BUTTON1;
3189 else if (xip->ir.Event.MouseEvent.dwButtonState == 2) /* rightmost */
3190 b = X11MOUSE_OFFSET + X11MOUSE_BUTTON3;
3191 else if (xip->ir.Event.MouseEvent.dwButtonState == 4) /* middle ("next-to-leftmost") */
3192 b = X11MOUSE_OFFSET + X11MOUSE_BUTTON2;
3193 else /* don't bother to figure out what changed */
3194 return (FALSE);
3195 break;
3196 case MOUSE_WHEELED:
3197 b = X11MOUSE_OFFSET + (((int)xip->ir.Event.MouseEvent.dwButtonState < 0) ? X11MOUSE_WHEEL_DOWN : X11MOUSE_WHEEL_UP);
3198 break;
3199 case MOUSE_MOVED:
3200 if (xip->ir.Event.MouseEvent.dwButtonState != 1)
3201 return (FALSE);
3202 /* Drag with left button down. */
3203 b = X11MOUSE_OFFSET + X11MOUSE_DRAG;
3204 break;
3205 default:
3206 return (FALSE);
3207 }
3208 /* {{ TODO: change to X11 1006 format. }} */
3209 win32_enqueue(ESC);
3210 win32_enqueue('[');
3211 win32_enqueue('M');
3212 win32_enqueue(b);
3213 win32_enqueue(X11MOUSE_OFFSET + xip->ir.Event.MouseEvent.dwMousePosition.X + 1);
3214 win32_enqueue(X11MOUSE_OFFSET + xip->ir.Event.MouseEvent.dwMousePosition.Y + 1);
3215 return (TRUE);
3216 }
3217
set_last_down(LWCHAR ch)3218 static void set_last_down(LWCHAR ch)
3219 {
3220 if (ch == 0) return;
3221 last_downs[last_down_index] = ch;
3222 if (++last_down_index >= LAST_DOWN_COUNT)
3223 last_down_index = 0;
3224 }
3225
find_last_down(LWCHAR ch)3226 static LWCHAR *find_last_down(LWCHAR ch)
3227 {
3228 int i;
3229 for (i = 0; i < LAST_DOWN_COUNT; ++i)
3230 if (last_downs[i] == ch)
3231 return &last_downs[i];
3232 return NULL;
3233 }
3234
3235 /*
3236 * Get an input char from an INPUT_RECORD and store in xip->ichar.
3237 * Handles surrogate chars, and KeyUp without previous corresponding KeyDown.
3238 */
win32_get_ichar(XINPUT_RECORD * xip)3239 static lbool win32_get_ichar(XINPUT_RECORD *xip)
3240 {
3241 LWCHAR ch = xip->ir.Event.KeyEvent.uChar.UnicodeChar;
3242 xip->ichar = ch;
3243 if (!is_ascii_char(ch))
3244 {
3245 int is_down = xip->ir.Event.KeyEvent.bKeyDown;
3246 LWCHAR *last_down = find_last_down(ch);
3247 if (last_down == NULL) { /* key was up */
3248 if (is_down) { /* key was up, now is down */
3249 set_last_down(ch);
3250 } else { /* key up without previous down: pretend this is a down. */
3251 xip->ir.Event.KeyEvent.bKeyDown = 1;
3252 }
3253 } else if (!is_down) { /* key was down, now is up */
3254 *last_down = 0; /* use this last_down only once */
3255 }
3256
3257 if (ch >= 0xD800 && ch < 0xDC00) { /* high surrogate */
3258 hi_surr = 0x10000 + ((ch - 0xD800) << 10);
3259 return (FALSE); /* get next input, which should be the low surrogate */
3260 }
3261 if (ch >= 0xDC00 && ch < 0xE000) { /* low surrogate */
3262 xip->ichar = hi_surr + (ch - 0xDC00);
3263 hi_surr = 0;
3264 }
3265 }
3266 return (TRUE);
3267 }
3268
3269 /*
3270 * Handle a scan code (non-ASCII) key input.
3271 */
win32_scan_code(XINPUT_RECORD * xip)3272 static lbool win32_scan_code(XINPUT_RECORD *xip)
3273 {
3274 int scan = -1;
3275 if (xip->ir.Event.KeyEvent.dwControlKeyState & (LEFT_CTRL_PRESSED | RIGHT_CTRL_PRESSED))
3276 {
3277 switch (xip->ir.Event.KeyEvent.wVirtualScanCode)
3278 {
3279 case PCK_RIGHT: /* right arrow */
3280 scan = PCK_CTL_RIGHT;
3281 break;
3282 case PCK_LEFT: /* left arrow */
3283 scan = PCK_CTL_LEFT;
3284 break;
3285 case PCK_DELETE: /* delete */
3286 scan = PCK_CTL_DELETE;
3287 break;
3288 case PCK_HOME:
3289 scan = PCK_CTL_HOME;
3290 break;
3291 case PCK_END:
3292 scan = PCK_CTL_END;
3293 break;
3294 }
3295 } else if (xip->ir.Event.KeyEvent.dwControlKeyState & SHIFT_PRESSED)
3296 {
3297 if (xip->ichar == '\t')
3298 scan = PCK_SHIFT_TAB;
3299 else
3300 {
3301 switch (xip->ir.Event.KeyEvent.wVirtualScanCode)
3302 {
3303 case PCK_HOME:
3304 scan = PCK_SHIFT_HOME;
3305 break;
3306 case PCK_END:
3307 scan = PCK_SHIFT_END;
3308 break;
3309 }
3310 }
3311 }
3312 if (scan < 0 && xip->ichar == 0)
3313 scan = xip->ir.Event.KeyEvent.wVirtualScanCode;
3314 if (scan < 0)
3315 return (FALSE);
3316 /*
3317 * An extended key returns a 2 byte sequence consisting of
3318 * a zero byte followed by the scan code.
3319 */
3320 win32_enqueue('\0');
3321 win32_enqueue(scan);
3322 return (TRUE);
3323 }
3324
3325 /*
3326 * Handle a key input event.
3327 */
win32_key_event(XINPUT_RECORD * xip)3328 static lbool win32_key_event(XINPUT_RECORD *xip)
3329 {
3330 int repeat;
3331 char utf8[UTF8_MAX_LENGTH];
3332 char *up;
3333
3334 if (xip->ir.EventType != KEY_EVENT ||
3335 ((xip->ir.Event.KeyEvent.dwControlKeyState & (RIGHT_ALT_PRESSED|LEFT_CTRL_PRESSED)) == (RIGHT_ALT_PRESSED|LEFT_CTRL_PRESSED) && xip->ir.Event.KeyEvent.uChar.UnicodeChar == 0) ||
3336 (xip->ir.Event.KeyEvent.wVirtualScanCode == 0 && xip->ir.Event.KeyEvent.uChar.UnicodeChar == 0) ||
3337 xip->ir.Event.KeyEvent.wVirtualScanCode == PCK_CAPS_LOCK ||
3338 xip->ir.Event.KeyEvent.wVirtualScanCode == PCK_NUM_LOCK ||
3339 (xip->ir.Event.KeyEvent.wVirtualKeyCode == VK_MENU && xip->ir.Event.KeyEvent.uChar.UnicodeChar == 0) ||
3340 xip->ir.Event.KeyEvent.wVirtualKeyCode == VK_KANJI ||
3341 xip->ir.Event.KeyEvent.wVirtualKeyCode == VK_SHIFT ||
3342 xip->ir.Event.KeyEvent.wVirtualKeyCode == VK_CONTROL)
3343 return (FALSE);
3344
3345 if (!win32_get_ichar(xip))
3346 return (FALSE);
3347 if (!xip->ir.Event.KeyEvent.bKeyDown)
3348 return (FALSE);
3349
3350 if (win32_scan_code(xip))
3351 return (TRUE);
3352
3353 repeat = xip->ir.Event.KeyEvent.wRepeatCount;
3354 if (repeat > WIN32_MAX_REPEAT)
3355 repeat = WIN32_MAX_REPEAT;
3356 up = utf8;
3357 put_wchar(&up, xip->ichar);
3358 for (; repeat > 0; --repeat)
3359 {
3360 constant char *p;
3361 for (p = utf8; p < up; ++p)
3362 win32_enqueue(*p & 0xFF);
3363 }
3364 return (TRUE);
3365 }
3366
3367 /*
3368 * Handle a window input event.
3369 */
win32_window_event(XINPUT_RECORD * xip)3370 static lbool win32_window_event(XINPUT_RECORD *xip)
3371 {
3372 if (xip->ir.EventType != WINDOW_BUFFER_SIZE_EVENT)
3373 return (FALSE);
3374 win32_enqueue(READ_AGAIN);
3375 return (TRUE);
3376 }
3377
3378 /*
3379 * Determine whether an input character is waiting to be read.
3380 */
win32_kbhit2(lbool no_queued)3381 public lbool win32_kbhit2(lbool no_queued)
3382 {
3383 XINPUT_RECORD xip;
3384
3385 if (!no_queued && win32_queued_char())
3386 return (TRUE);
3387
3388 for (;;)
3389 {
3390 DWORD nread;
3391 DWORD console_input_mode;
3392 /*
3393 * When an input pipe closes, cmd may reset the console mode,
3394 * so set the mode every time we read input.
3395 */
3396 if (GetConsoleMode(tty, &console_input_mode) && console_input_mode != curr_console_input_mode)
3397 SetConsoleMode(tty, curr_console_input_mode);
3398 PeekConsoleInputW(tty, &xip.ir, 1, &nread);
3399 if (nread == 0)
3400 return (FALSE);
3401 ReadConsoleInputW(tty, &xip.ir, 1, &nread);
3402 if (nread == 0)
3403 return (FALSE);
3404 if (win32_mouse_event(&xip) || win32_key_event(&xip) || win32_window_event(&xip))
3405 break;
3406 }
3407 return (TRUE);
3408 }
3409
win32_kbhit(void)3410 public lbool win32_kbhit(void)
3411 {
3412 return win32_kbhit2(FALSE);
3413 }
3414
3415 /*
3416 * Read a character from the keyboard.
3417 */
WIN32getch(void)3418 public int WIN32getch(void)
3419 {
3420 while (!win32_kbhit())
3421 {
3422 Sleep(20);
3423 if (ABORT_SIGS())
3424 return ('\003');
3425 }
3426 return (win32_get_queue());
3427 }
3428
win32_getch_clear(void)3429 public void win32_getch_clear(void)
3430 {
3431 while (win32_kbhit())
3432 (void) WIN32getch();
3433 }
3434
3435 #endif /* MSDOS_COMPILER==WIN32C */
3436
3437 #if MSDOS_COMPILER
3438 /*
3439 */
WIN32setcolors(int fg,int bg)3440 public void WIN32setcolors(int fg, int bg)
3441 {
3442 SETCOLORS(fg, bg);
3443 }
3444
3445 /*
3446 */
WIN32textout(constant char * text,size_t len)3447 public void WIN32textout(constant char *text, size_t len)
3448 {
3449 #if MSDOS_COMPILER==WIN32C
3450 DWORD written;
3451 if (utf_mode == 2)
3452 {
3453 /*
3454 * We've got UTF-8 text in a non-UTF-8 console. Convert it to
3455 * wide and use WriteConsoleW.
3456 * Biggest input len is OUTBUF_SIZE of obuf from win_flush,
3457 * which is also the biggest output count if it's ASCII.
3458 * "static" wtext is not a state - only avoid 16K on stack.
3459 */
3460 static WCHAR wtext[OUTBUF_SIZE];
3461 len = MultiByteToWideChar(CP_UTF8, 0, text, len, wtext, countof(wtext));
3462 WriteConsoleW(con_out, wtext, len, &written, NULL);
3463 } else
3464 WriteConsole(con_out, text, (DWORD) len, &written, NULL);
3465 #else
3466 char buf[2048];
3467 if (len >= sizeof(buf))
3468 len = sizeof(buf) - 1;
3469 memcpy(buf, text, len);
3470 buf[len] = 0;
3471 cputs(buf);
3472 #endif
3473 }
3474 #endif
3475