Add trunc and truncf.
[dragonfly.git] / contrib / less-403 / screen.c
1 /*
2  * Copyright (C) 1984-2007  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 about less, or for information on how to 
8  * contact the author, see the README file.
9  */
10
11
12 /*
13  * Routines which deal with the characteristics of the terminal.
14  * Uses termcap to be as terminal-independent as possible.
15  */
16
17 #include "less.h"
18 #include "cmd.h"
19
20 #if MSDOS_COMPILER
21 #include "pckeys.h"
22 #if MSDOS_COMPILER==MSOFTC
23 #include <graph.h>
24 #else
25 #if MSDOS_COMPILER==BORLANDC || MSDOS_COMPILER==DJGPPC
26 #include <conio.h>
27 #if MSDOS_COMPILER==DJGPPC
28 #include <pc.h>
29 extern int fd0;
30 #endif
31 #else
32 #if MSDOS_COMPILER==WIN32C
33 #include <windows.h>
34 #endif
35 #endif
36 #endif
37 #include <time.h>
38
39 #else
40
41 #if HAVE_SYS_IOCTL_H
42 #include <sys/ioctl.h>
43 #endif
44
45 #if HAVE_TERMIOS_H && HAVE_TERMIOS_FUNCS
46 #include <termios.h>
47 #else
48 #if HAVE_TERMIO_H
49 #include <termio.h>
50 #else
51 #if HAVE_SGSTAT_H
52 #include <sgstat.h>
53 #else
54 #include <sgtty.h>
55 #endif
56 #endif
57 #endif
58
59 #if HAVE_TERMCAP_H
60 #include <termcap.h>
61 #endif
62 #ifdef _OSK
63 #include <signal.h>
64 #endif
65 #if OS2
66 #include <sys/signal.h>
67 #include "pckeys.h"
68 #endif
69 #if HAVE_SYS_STREAM_H
70 #include <sys/stream.h>
71 #endif
72 #if HAVE_SYS_PTEM_H
73 #include <sys/ptem.h>
74 #endif
75
76 #endif /* MSDOS_COMPILER */
77
78 /*
79  * Check for broken termios package that forces you to manually
80  * set the line discipline.
81  */
82 #ifdef __ultrix__
83 #define MUST_SET_LINE_DISCIPLINE 1
84 #else
85 #define MUST_SET_LINE_DISCIPLINE 0
86 #endif
87
88 #if OS2
89 #define DEFAULT_TERM            "ansi"
90 static char *windowid;
91 #else
92 #define DEFAULT_TERM            "unknown"
93 #endif
94
95 #if MSDOS_COMPILER==MSOFTC
96 static int videopages;
97 static long msec_loops;
98 static int flash_created = 0;
99 #define SETCOLORS(fg,bg)        { _settextcolor(fg); _setbkcolor(bg); }
100 #endif
101
102 #if MSDOS_COMPILER==BORLANDC
103 static unsigned short *whitescreen;
104 static int flash_created = 0;
105 #endif
106 #if MSDOS_COMPILER==BORLANDC || MSDOS_COMPILER==DJGPPC
107 #define _settextposition(y,x)   gotoxy(x,y)
108 #define _clearscreen(m)         clrscr()
109 #define _outtext(s)             cputs(s)
110 #define SETCOLORS(fg,bg)        { textcolor(fg); textbackground(bg); }
111 extern int sc_height;
112 #endif
113
114 #if MSDOS_COMPILER==WIN32C
115 struct keyRecord
116 {
117         int ascii;
118         int scan;
119 } currentKey;
120
121 static int keyCount = 0;
122 static WORD curr_attr;
123 static int pending_scancode = 0;
124 static WORD *whitescreen;
125
126 static HANDLE con_out_save = INVALID_HANDLE_VALUE; /* previous console */
127 static HANDLE con_out_ours = INVALID_HANDLE_VALUE; /* our own */
128 HANDLE con_out = INVALID_HANDLE_VALUE;             /* current console */
129
130 extern int quitting;
131 static void win32_init_term();
132 static void win32_deinit_term();
133
134 #define FG_COLORS       (FOREGROUND_RED | FOREGROUND_GREEN | FOREGROUND_BLUE | FOREGROUND_INTENSITY)
135 #define BG_COLORS       (BACKGROUND_RED | BACKGROUND_GREEN | BACKGROUND_BLUE | BACKGROUND_INTENSITY)
136 #define MAKEATTR(fg,bg)         ((WORD)((fg)|((bg)<<4)))
137 #define SETCOLORS(fg,bg)        { curr_attr = MAKEATTR(fg,bg); \
138                                 if (SetConsoleTextAttribute(con_out, curr_attr) == 0) \
139                                 error("SETCOLORS failed"); }
140 #endif
141
142 #if MSDOS_COMPILER
143 public int nm_fg_color;         /* Color of normal text */
144 public int nm_bg_color;
145 public int bo_fg_color;         /* Color of bold text */
146 public int bo_bg_color;
147 public int ul_fg_color;         /* Color of underlined text */
148 public int ul_bg_color;
149 public int so_fg_color;         /* Color of standout text */
150 public int so_bg_color;
151 public int bl_fg_color;         /* Color of blinking text */
152 public int bl_bg_color;
153 static int sy_fg_color;         /* Color of system text (before less) */
154 static int sy_bg_color;
155
156 #else
157
158 /*
159  * Strings passed to tputs() to do various terminal functions.
160  */
161 static char
162         *sc_pad,                /* Pad string */
163         *sc_home,               /* Cursor home */
164         *sc_addline,            /* Add line, scroll down following lines */
165         *sc_lower_left,         /* Cursor to last line, first column */
166         *sc_return,             /* Cursor to beginning of current line */
167         *sc_move,               /* General cursor positioning */
168         *sc_clear,              /* Clear screen */
169         *sc_eol_clear,          /* Clear to end of line */
170         *sc_eos_clear,          /* Clear to end of screen */
171         *sc_s_in,               /* Enter standout (highlighted) mode */
172         *sc_s_out,              /* Exit standout mode */
173         *sc_u_in,               /* Enter underline mode */
174         *sc_u_out,              /* Exit underline mode */
175         *sc_b_in,               /* Enter bold mode */
176         *sc_b_out,              /* Exit bold mode */
177         *sc_bl_in,              /* Enter blink mode */
178         *sc_bl_out,             /* Exit blink mode */
179         *sc_visual_bell,        /* Visual bell (flash screen) sequence */
180         *sc_backspace,          /* Backspace cursor */
181         *sc_s_keypad,           /* Start keypad mode */
182         *sc_e_keypad,           /* End keypad mode */
183         *sc_init,               /* Startup terminal initialization */
184         *sc_deinit;             /* Exit terminal de-initialization */
185 #endif
186
187 static int init_done = 0;
188
189 public int auto_wrap;           /* Terminal does \r\n when write past margin */
190 public int ignaw;               /* Terminal ignores \n immediately after wrap */
191 public int erase_char;          /* The user's erase char */
192 public int erase2_char;         /* The user's other erase char */
193 public int kill_char;           /* The user's line-kill char */
194 public int werase_char;         /* The user's word-erase char */
195 public int sc_width, sc_height; /* Height & width of screen */
196 public int bo_s_width, bo_e_width;      /* Printing width of boldface seq */
197 public int ul_s_width, ul_e_width;      /* Printing width of underline seq */
198 public int so_s_width, so_e_width;      /* Printing width of standout seq */
199 public int bl_s_width, bl_e_width;      /* Printing width of blink seq */
200 public int above_mem, below_mem;        /* Memory retained above/below screen */
201 public int can_goto_line;               /* Can move cursor to any line */
202 public int clear_bg;            /* Clear fills with background color */
203 public int missing_cap = 0;     /* Some capability is missing */
204
205 static int attrmode = AT_NORMAL;
206 extern int binattr;
207
208 #if !MSDOS_COMPILER
209 static char *cheaper();
210 static void tmodes();
211 #endif
212
213 /*
214  * These two variables are sometimes defined in,
215  * and needed by, the termcap library.
216  */
217 #if MUST_DEFINE_OSPEED
218 extern short ospeed;    /* Terminal output baud rate */
219 extern char PC;         /* Pad character */
220 #endif
221 #ifdef _OSK
222 short ospeed;
223 char PC_, *UP, *BC;
224 #endif
225
226 extern int quiet;               /* If VERY_QUIET, use visual bell for bell */
227 extern int no_back_scroll;
228 extern int swindow;
229 extern int no_init;
230 extern int no_keypad;
231 extern int sigs;
232 extern int wscroll;
233 extern int screen_trashed;
234 extern int tty;
235 extern int top_scroll;
236 extern int oldbot;
237 #if HILITE_SEARCH
238 extern int hilite_search;
239 #endif
240
241 extern char *tgetstr();
242 extern char *tgoto();
243
244
245 /*
246  * Change terminal to "raw mode", or restore to "normal" mode.
247  * "Raw mode" means 
248  *      1. An outstanding read will complete on receipt of a single keystroke.
249  *      2. Input is not echoed.  
250  *      3. On output, \n is mapped to \r\n.
251  *      4. \t is NOT expanded into spaces.
252  *      5. Signal-causing characters such as ctrl-C (interrupt),
253  *         etc. are NOT disabled.
254  * It doesn't matter whether an input \n is mapped to \r, or vice versa.
255  */
256         public void
257 raw_mode(on)
258         int on;
259 {
260         static int curr_on = 0;
261
262         if (on == curr_on)
263                 return;
264         erase2_char = '\b'; /* in case OS doesn't know about erase2 */
265 #if HAVE_TERMIOS_H && HAVE_TERMIOS_FUNCS
266     {
267         struct termios s;
268         static struct termios save_term;
269         static int saved_term = 0;
270
271         if (on) 
272         {
273                 /*
274                  * Get terminal modes.
275                  */
276                 tcgetattr(tty, &s);
277
278                 /*
279                  * Save modes and set certain variables dependent on modes.
280                  */
281                 if (!saved_term)
282                 {
283                         save_term = s;
284                         saved_term = 1;
285                 }
286 #if HAVE_OSPEED
287                 switch (cfgetospeed(&s))
288                 {
289 #ifdef B0
290                 case B0: ospeed = 0; break;
291 #endif
292 #ifdef B50
293                 case B50: ospeed = 1; break;
294 #endif
295 #ifdef B75
296                 case B75: ospeed = 2; break;
297 #endif
298 #ifdef B110
299                 case B110: ospeed = 3; break;
300 #endif
301 #ifdef B134
302                 case B134: ospeed = 4; break;
303 #endif
304 #ifdef B150
305                 case B150: ospeed = 5; break;
306 #endif
307 #ifdef B200
308                 case B200: ospeed = 6; break;
309 #endif
310 #ifdef B300
311                 case B300: ospeed = 7; break;
312 #endif
313 #ifdef B600
314                 case B600: ospeed = 8; break;
315 #endif
316 #ifdef B1200
317                 case B1200: ospeed = 9; break;
318 #endif
319 #ifdef B1800
320                 case B1800: ospeed = 10; break;
321 #endif
322 #ifdef B2400
323                 case B2400: ospeed = 11; break;
324 #endif
325 #ifdef B4800
326                 case B4800: ospeed = 12; break;
327 #endif
328 #ifdef B9600
329                 case B9600: ospeed = 13; break;
330 #endif
331 #ifdef EXTA
332                 case EXTA: ospeed = 14; break;
333 #endif
334 #ifdef EXTB
335                 case EXTB: ospeed = 15; break;
336 #endif
337 #ifdef B57600
338                 case B57600: ospeed = 16; break;
339 #endif
340 #ifdef B115200
341                 case B115200: ospeed = 17; break;
342 #endif
343                 default: ;
344                 }
345 #endif
346                 erase_char = s.c_cc[VERASE];
347 #ifdef VERASE2
348                 erase2_char = s.c_cc[VERASE2];
349 #endif
350                 kill_char = s.c_cc[VKILL];
351 #ifdef VWERASE
352                 werase_char = s.c_cc[VWERASE];
353 #else
354                 werase_char = CONTROL('W');
355 #endif
356
357                 /*
358                  * Set the modes to the way we want them.
359                  */
360                 s.c_lflag &= ~(0
361 #ifdef ICANON
362                         | ICANON
363 #endif
364 #ifdef ECHO
365                         | ECHO
366 #endif
367 #ifdef ECHOE
368                         | ECHOE
369 #endif
370 #ifdef ECHOK
371                         | ECHOK
372 #endif
373 #if ECHONL
374                         | ECHONL
375 #endif
376                 );
377
378                 s.c_oflag |= (0
379 #ifdef OXTABS
380                         | OXTABS
381 #else
382 #ifdef TAB3
383                         | TAB3
384 #else
385 #ifdef XTABS
386                         | XTABS
387 #endif
388 #endif
389 #endif
390 #ifdef OPOST
391                         | OPOST
392 #endif
393 #ifdef ONLCR
394                         | ONLCR
395 #endif
396                 );
397
398                 s.c_oflag &= ~(0
399 #ifdef ONOEOT
400                         | ONOEOT
401 #endif
402 #ifdef OCRNL
403                         | OCRNL
404 #endif
405 #ifdef ONOCR
406                         | ONOCR
407 #endif
408 #ifdef ONLRET
409                         | ONLRET
410 #endif
411                 );
412                 s.c_cc[VMIN] = 1;
413                 s.c_cc[VTIME] = 0;
414 #ifdef VLNEXT
415                 s.c_cc[VLNEXT] = 0;
416 #endif
417 #ifdef VDSUSP
418                 s.c_cc[VDSUSP] = 0;
419 #endif
420 #if MUST_SET_LINE_DISCIPLINE
421                 /*
422                  * System's termios is broken; need to explicitly 
423                  * request TERMIODISC line discipline.
424                  */
425                 s.c_line = TERMIODISC;
426 #endif
427         } else
428         {
429                 /*
430                  * Restore saved modes.
431                  */
432                 s = save_term;
433         }
434 #if HAVE_FSYNC
435         fsync(tty);
436 #endif
437         tcsetattr(tty, TCSADRAIN, &s);
438 #if MUST_SET_LINE_DISCIPLINE
439         if (!on)
440         {
441                 /*
442                  * Broken termios *ignores* any line discipline
443                  * except TERMIODISC.  A different old line discipline
444                  * is therefore not restored, yet.  Restore the old
445                  * line discipline by hand.
446                  */
447                 ioctl(tty, TIOCSETD, &save_term.c_line);
448         }
449 #endif
450     }
451 #else
452 #ifdef TCGETA
453     {
454         struct termio s;
455         static struct termio save_term;
456         static int saved_term = 0;
457
458         if (on)
459         {
460                 /*
461                  * Get terminal modes.
462                  */
463                 ioctl(tty, TCGETA, &s);
464
465                 /*
466                  * Save modes and set certain variables dependent on modes.
467                  */
468                 if (!saved_term)
469                 {
470                         save_term = s;
471                         saved_term = 1;
472                 }
473 #if HAVE_OSPEED
474                 ospeed = s.c_cflag & CBAUD;
475 #endif
476                 erase_char = s.c_cc[VERASE];
477                 kill_char = s.c_cc[VKILL];
478 #ifdef VWERASE
479                 werase_char = s.c_cc[VWERASE];
480 #else
481                 werase_char = CONTROL('W');
482 #endif
483
484                 /*
485                  * Set the modes to the way we want them.
486                  */
487                 s.c_lflag &= ~(ICANON|ECHO|ECHOE|ECHOK|ECHONL);
488                 s.c_oflag |=  (OPOST|ONLCR|TAB3);
489                 s.c_oflag &= ~(OCRNL|ONOCR|ONLRET);
490                 s.c_cc[VMIN] = 1;
491                 s.c_cc[VTIME] = 0;
492         } else
493         {
494                 /*
495                  * Restore saved modes.
496                  */
497                 s = save_term;
498         }
499         ioctl(tty, TCSETAW, &s);
500     }
501 #else
502 #ifdef TIOCGETP
503     {
504         struct sgttyb s;
505         static struct sgttyb save_term;
506         static int saved_term = 0;
507
508         if (on)
509         {
510                 /*
511                  * Get terminal modes.
512                  */
513                 ioctl(tty, TIOCGETP, &s);
514
515                 /*
516                  * Save modes and set certain variables dependent on modes.
517                  */
518                 if (!saved_term)
519                 {
520                         save_term = s;
521                         saved_term = 1;
522                 }
523 #if HAVE_OSPEED
524                 ospeed = s.sg_ospeed;
525 #endif
526                 erase_char = s.sg_erase;
527                 kill_char = s.sg_kill;
528                 werase_char = CONTROL('W');
529
530                 /*
531                  * Set the modes to the way we want them.
532                  */
533                 s.sg_flags |= CBREAK;
534                 s.sg_flags &= ~(ECHO|XTABS);
535         } else
536         {
537                 /*
538                  * Restore saved modes.
539                  */
540                 s = save_term;
541         }
542         ioctl(tty, TIOCSETN, &s);
543     }
544 #else
545 #ifdef _OSK
546     {
547         struct sgbuf s;
548         static struct sgbuf save_term;
549         static int saved_term = 0;
550
551         if (on)
552         {
553                 /*
554                  * Get terminal modes.
555                  */
556                 _gs_opt(tty, &s);
557
558                 /*
559                  * Save modes and set certain variables dependent on modes.
560                  */
561                 if (!saved_term)
562                 {
563                         save_term = s;
564                         saved_term = 1;
565                 }
566                 erase_char = s.sg_bspch;
567                 kill_char = s.sg_dlnch;
568                 werase_char = CONTROL('W');
569
570                 /*
571                  * Set the modes to the way we want them.
572                  */
573                 s.sg_echo = 0;
574                 s.sg_eofch = 0;
575                 s.sg_pause = 0;
576                 s.sg_psch = 0;
577         } else
578         {
579                 /*
580                  * Restore saved modes.
581                  */
582                 s = save_term;
583         }
584         _ss_opt(tty, &s);
585     }
586 #else
587         /* MS-DOS, Windows, or OS2 */
588 #if OS2
589         /* OS2 */
590         LSIGNAL(SIGINT, SIG_IGN);
591 #endif
592         erase_char = '\b';
593 #if MSDOS_COMPILER==DJGPPC
594         kill_char = CONTROL('U');
595         /*
596          * So that when we shell out or run another program, its
597          * stdin is in cooked mode.  We do not switch stdin to binary 
598          * mode if fd0 is zero, since that means we were called before
599          * tty was reopened in open_getchr, in which case we would be
600          * changing the original stdin device outside less.
601          */
602         if (fd0 != 0)
603                 setmode(0, on ? O_BINARY : O_TEXT);
604 #else
605         kill_char = ESC;
606 #endif
607         werase_char = CONTROL('W');
608 #endif
609 #endif
610 #endif
611 #endif
612         curr_on = on;
613 }
614
615 #if !MSDOS_COMPILER
616 /*
617  * Some glue to prevent calling termcap functions if tgetent() failed.
618  */
619 static int hardcopy;
620
621         static char *
622 ltget_env(capname)
623         char *capname;
624 {
625         char name[16];
626
627         strcpy(name, "LESS_TERMCAP_");
628         strcat(name, capname);
629         return (lgetenv(name));
630 }
631
632         static int
633 ltgetflag(capname)
634         char *capname;
635 {
636         char *s;
637
638         if ((s = ltget_env(capname)) != NULL)
639                 return (*s != '\0' && *s != '0');
640         if (hardcopy)
641                 return (0);
642         return (tgetflag(capname));
643 }
644
645         static int
646 ltgetnum(capname)
647         char *capname;
648 {
649         char *s;
650
651         if ((s = ltget_env(capname)) != NULL)
652                 return (atoi(s));
653         if (hardcopy)
654                 return (-1);
655         return (tgetnum(capname));
656 }
657
658         static char *
659 ltgetstr(capname, pp)
660         char *capname;
661         char **pp;
662 {
663         char *s;
664
665         if ((s = ltget_env(capname)) != NULL)
666                 return (s);
667         if (hardcopy)
668                 return (NULL);
669         return (tgetstr(capname, pp));
670 }
671 #endif /* MSDOS_COMPILER */
672
673 /*
674  * Get size of the output screen.
675  */
676         public void
677 scrsize()
678 {
679         register char *s;
680         int sys_height;
681         int sys_width;
682 #if !MSDOS_COMPILER
683         int n;
684 #endif
685
686 #define DEF_SC_WIDTH    80
687 #if MSDOS_COMPILER
688 #define DEF_SC_HEIGHT   25
689 #else
690 #define DEF_SC_HEIGHT   24
691 #endif
692
693
694         sys_width = sys_height = 0;
695
696 #if MSDOS_COMPILER==MSOFTC
697         {
698                 struct videoconfig w;
699                 _getvideoconfig(&w);
700                 sys_height = w.numtextrows;
701                 sys_width = w.numtextcols;
702         }
703 #else
704 #if MSDOS_COMPILER==BORLANDC || MSDOS_COMPILER==DJGPPC
705         {
706                 struct text_info w;
707                 gettextinfo(&w);
708                 sys_height = w.screenheight;
709                 sys_width = w.screenwidth;
710         }
711 #else
712 #if MSDOS_COMPILER==WIN32C
713         {
714                 CONSOLE_SCREEN_BUFFER_INFO scr;
715                 GetConsoleScreenBufferInfo(con_out, &scr);
716                 sys_height = scr.srWindow.Bottom - scr.srWindow.Top + 1;
717                 sys_width = scr.srWindow.Right - scr.srWindow.Left + 1;
718         }
719 #else
720 #if OS2
721         {
722                 int s[2];
723                 _scrsize(s);
724                 sys_width = s[0];
725                 sys_height = s[1];
726                 /*
727                  * When using terminal emulators for XFree86/OS2, the
728                  * _scrsize function does not work well.
729                  * Call the scrsize.exe program to get the window size.
730                  */
731                 windowid = getenv("WINDOWID");
732                 if (windowid != NULL)
733                 {
734                         FILE *fd = popen("scrsize", "rt");
735                         if (fd != NULL)
736                         {
737                                 int w, h;
738                                 fscanf(fd, "%i %i", &w, &h);
739                                 if (w > 0 && h > 0)
740                                 {
741                                         sys_width = w;
742                                         sys_height = h;
743                                 }
744                                 pclose(fd);
745                         }
746                 }
747         }
748 #else
749 #ifdef TIOCGWINSZ
750         {
751                 struct winsize w;
752                 if (ioctl(2, TIOCGWINSZ, &w) == 0)
753                 {
754                         if (w.ws_row > 0)
755                                 sys_height = w.ws_row;
756                         if (w.ws_col > 0)
757                                 sys_width = w.ws_col;
758                 }
759         }
760 #else
761 #ifdef WIOCGETD
762         {
763                 struct uwdata w;
764                 if (ioctl(2, WIOCGETD, &w) == 0)
765                 {
766                         if (w.uw_height > 0)
767                                 sys_height = w.uw_height / w.uw_vs;
768                         if (w.uw_width > 0)
769                                 sys_width = w.uw_width / w.uw_hs;
770                 }
771         }
772 #endif
773 #endif
774 #endif
775 #endif
776 #endif
777 #endif
778
779         if (sys_height > 0)
780                 sc_height = sys_height;
781         else if ((s = lgetenv("LINES")) != NULL)
782                 sc_height = atoi(s);
783 #if !MSDOS_COMPILER
784         else if ((n = ltgetnum("li")) > 0)
785                 sc_height = n;
786 #endif
787         else
788                 sc_height = DEF_SC_HEIGHT;
789
790         if (sys_width > 0)
791                 sc_width = sys_width;
792         else if ((s = lgetenv("COLUMNS")) != NULL)
793                 sc_width = atoi(s);
794 #if !MSDOS_COMPILER
795         else if ((n = ltgetnum("co")) > 0)
796                 sc_width = n;
797 #endif
798         else
799                 sc_width = DEF_SC_WIDTH;
800 }
801
802 #if MSDOS_COMPILER==MSOFTC
803 /*
804  * Figure out how many empty loops it takes to delay a millisecond.
805  */
806         static void
807 get_clock()
808 {
809         clock_t start;
810         
811         /*
812          * Get synchronized at the start of a tick.
813          */
814         start = clock();
815         while (clock() == start)
816                 ;
817         /*
818          * Now count loops till the next tick.
819          */
820         start = clock();
821         msec_loops = 0;
822         while (clock() == start)
823                 msec_loops++;
824         /*
825          * Convert from (loops per clock) to (loops per millisecond).
826          */
827         msec_loops *= CLOCKS_PER_SEC;
828         msec_loops /= 1000;
829 }
830
831 /*
832  * Delay for a specified number of milliseconds.
833  */
834         static void
835 dummy_func()
836 {
837         static long delay_dummy = 0;
838         delay_dummy++;
839 }
840
841         static void
842 delay(msec)
843         int msec;
844 {
845         long i;
846         
847         while (msec-- > 0)
848         {
849                 for (i = 0;  i < msec_loops;  i++)
850                 {
851                         /*
852                          * Make it look like we're doing something here,
853                          * so the optimizer doesn't remove the whole loop.
854                          */
855                         dummy_func();
856                 }
857         }
858 }
859 #endif
860
861 /*
862  * Return the characters actually input by a "special" key.
863  */
864         public char *
865 special_key_str(key)
866         int key;
867 {
868         static char tbuf[40];
869         char *s;
870 #if MSDOS_COMPILER || OS2
871         static char k_right[]           = { '\340', PCK_RIGHT, 0 };
872         static char k_left[]            = { '\340', PCK_LEFT, 0  };
873         static char k_ctl_right[]       = { '\340', PCK_CTL_RIGHT, 0  };
874         static char k_ctl_left[]        = { '\340', PCK_CTL_LEFT, 0  };
875         static char k_insert[]          = { '\340', PCK_INSERT, 0  };
876         static char k_delete[]          = { '\340', PCK_DELETE, 0  };
877         static char k_ctl_delete[]      = { '\340', PCK_CTL_DELETE, 0  };
878         static char k_ctl_backspace[]   = { '\177', 0 };
879         static char k_home[]            = { '\340', PCK_HOME, 0 };
880         static char k_end[]             = { '\340', PCK_END, 0 };
881         static char k_up[]              = { '\340', PCK_UP, 0 };
882         static char k_down[]            = { '\340', PCK_DOWN, 0 };
883         static char k_backtab[]         = { '\340', PCK_SHIFT_TAB, 0 };
884         static char k_pagedown[]        = { '\340', PCK_PAGEDOWN, 0 };
885         static char k_pageup[]          = { '\340', PCK_PAGEUP, 0 };
886         static char k_f1[]              = { '\340', PCK_F1, 0 };
887 #endif
888 #if !MSDOS_COMPILER
889         char *sp = tbuf;
890 #endif
891
892         switch (key)
893         {
894 #if OS2
895         /*
896          * If windowid is not NULL, assume less is executed in 
897          * the XFree86 environment.
898          */
899         case SK_RIGHT_ARROW:
900                 s = windowid ? ltgetstr("kr", &sp) : k_right;
901                 break;
902         case SK_LEFT_ARROW:
903                 s = windowid ? ltgetstr("kl", &sp) : k_left;
904                 break;
905         case SK_UP_ARROW:
906                 s = windowid ? ltgetstr("ku", &sp) : k_up;
907                 break;
908         case SK_DOWN_ARROW:
909                 s = windowid ? ltgetstr("kd", &sp) : k_down;
910                 break;
911         case SK_PAGE_UP:
912                 s = windowid ? ltgetstr("kP", &sp) : k_pageup;
913                 break;
914         case SK_PAGE_DOWN:
915                 s = windowid ? ltgetstr("kN", &sp) : k_pagedown;
916                 break;
917         case SK_HOME:
918                 s = windowid ? ltgetstr("kh", &sp) : k_home;
919                 break;
920         case SK_END:
921                 s = windowid ? ltgetstr("@7", &sp) : k_end;
922                 break;
923         case SK_DELETE:
924                 if (windowid)
925                 {
926                         s = ltgetstr("kD", &sp);
927                         if (s == NULL)
928                         {
929                                 tbuf[0] = '\177';
930                                 tbuf[1] = '\0';
931                                 s = tbuf;
932                         }
933                 } else
934                         s = k_delete;
935                 break;
936 #endif
937 #if MSDOS_COMPILER
938         case SK_RIGHT_ARROW:
939                 s = k_right;
940                 break;
941         case SK_LEFT_ARROW:
942                 s = k_left;
943                 break;
944         case SK_UP_ARROW:
945                 s = k_up;
946                 break;
947         case SK_DOWN_ARROW:
948                 s = k_down;
949                 break;
950         case SK_PAGE_UP:
951                 s = k_pageup;
952                 break;
953         case SK_PAGE_DOWN:
954                 s = k_pagedown;
955                 break;
956         case SK_HOME:
957                 s = k_home;
958                 break;
959         case SK_END:
960                 s = k_end;
961                 break;
962         case SK_DELETE:
963                 s = k_delete;
964                 break;
965 #endif
966 #if MSDOS_COMPILER || OS2
967         case SK_INSERT:
968                 s = k_insert;
969                 break;
970         case SK_CTL_LEFT_ARROW:
971                 s = k_ctl_left;
972                 break;
973         case SK_CTL_RIGHT_ARROW:
974                 s = k_ctl_right;
975                 break;
976         case SK_CTL_BACKSPACE:
977                 s = k_ctl_backspace;
978                 break;
979         case SK_CTL_DELETE:
980                 s = k_ctl_delete;
981                 break;
982         case SK_F1:
983                 s = k_f1;
984                 break;
985         case SK_BACKTAB:
986                 s = k_backtab;
987                 break;
988 #else
989         case SK_RIGHT_ARROW:
990                 s = ltgetstr("kr", &sp);
991                 break;
992         case SK_LEFT_ARROW:
993                 s = ltgetstr("kl", &sp);
994                 break;
995         case SK_UP_ARROW:
996                 s = ltgetstr("ku", &sp);
997                 break;
998         case SK_DOWN_ARROW:
999                 s = ltgetstr("kd", &sp);
1000                 break;
1001         case SK_PAGE_UP:
1002                 s = ltgetstr("kP", &sp);
1003                 break;
1004         case SK_PAGE_DOWN:
1005                 s = ltgetstr("kN", &sp);
1006                 break;
1007         case SK_HOME:
1008                 s = ltgetstr("kh", &sp);
1009                 break;
1010         case SK_END:
1011                 s = ltgetstr("@7", &sp);
1012                 break;
1013         case SK_DELETE:
1014                 s = ltgetstr("kD", &sp);
1015                 if (s == NULL)
1016                 {
1017                         tbuf[0] = '\177';
1018                         tbuf[1] = '\0';
1019                         s = tbuf;
1020                 }
1021                 break;
1022 #endif
1023         case SK_CONTROL_K:
1024                 tbuf[0] = CONTROL('K');
1025                 tbuf[1] = '\0';
1026                 s = tbuf;
1027                 break;
1028         default:
1029                 return (NULL);
1030         }
1031         return (s);
1032 }
1033
1034 /*
1035  * Get terminal capabilities via termcap.
1036  */
1037         public void
1038 get_term()
1039 {
1040 #if MSDOS_COMPILER
1041         auto_wrap = 1;
1042         ignaw = 0;
1043         can_goto_line = 1;
1044         clear_bg = 1;
1045         /*
1046          * Set up default colors.
1047          * The xx_s_width and xx_e_width vars are already initialized to 0.
1048          */
1049 #if MSDOS_COMPILER==MSOFTC
1050         sy_bg_color = _getbkcolor();
1051         sy_fg_color = _gettextcolor();
1052         get_clock();
1053 #else
1054 #if MSDOS_COMPILER==BORLANDC || MSDOS_COMPILER==DJGPPC
1055     {
1056         struct text_info w;
1057         gettextinfo(&w);
1058         sy_bg_color = (w.attribute >> 4) & 0x0F;
1059         sy_fg_color = (w.attribute >> 0) & 0x0F;
1060     }
1061 #else
1062 #if MSDOS_COMPILER==WIN32C
1063     {
1064         DWORD nread;
1065         CONSOLE_SCREEN_BUFFER_INFO scr;
1066
1067         con_out_save = con_out = GetStdHandle(STD_OUTPUT_HANDLE);
1068         /*
1069          * Always open stdin in binary. Note this *must* be done
1070          * before any file operations have been done on fd0.
1071          */
1072         SET_BINARY(0);
1073         GetConsoleScreenBufferInfo(con_out, &scr);
1074         ReadConsoleOutputAttribute(con_out, &curr_attr, 
1075                                         1, scr.dwCursorPosition, &nread);
1076         sy_bg_color = (curr_attr & BG_COLORS) >> 4; /* normalize */
1077         sy_fg_color = curr_attr & FG_COLORS;
1078     }
1079 #endif
1080 #endif
1081 #endif
1082         nm_fg_color = sy_fg_color;
1083         nm_bg_color = sy_bg_color;
1084         bo_fg_color = 11;
1085         bo_bg_color = 0;
1086         ul_fg_color = 9;
1087         ul_bg_color = 0;
1088         so_fg_color = 15;
1089         so_bg_color = 9;
1090         bl_fg_color = 15;
1091         bl_bg_color = 0;
1092
1093         /*
1094          * Get size of the screen.
1095          */
1096         scrsize();
1097         pos_init();
1098
1099
1100 #else /* !MSDOS_COMPILER */
1101
1102         char *sp;
1103         register char *t1, *t2;
1104         char *term;
1105         char termbuf[TERMBUF_SIZE];
1106
1107         static char sbuf[TERMSBUF_SIZE];
1108
1109 #if OS2
1110         /*
1111          * Make sure the termcap database is available.
1112          */
1113         sp = lgetenv("TERMCAP");
1114         if (sp == NULL || *sp == '\0')
1115         {
1116                 char *termcap;
1117                 if ((sp = homefile("termcap.dat")) != NULL)
1118                 {
1119                         termcap = (char *) ecalloc(strlen(sp)+9, sizeof(char));
1120                         sprintf(termcap, "TERMCAP=%s", sp);
1121                         free(sp);
1122                         putenv(termcap);
1123                 }
1124         }
1125 #endif
1126         /*
1127          * Find out what kind of terminal this is.
1128          */
1129         if ((term = lgetenv("TERM")) == NULL)
1130                 term = DEFAULT_TERM;
1131         hardcopy = 0;
1132         if (tgetent(termbuf, term) != TGETENT_OK)
1133                 hardcopy = 1;
1134         if (ltgetflag("hc"))
1135                 hardcopy = 1;
1136
1137         /*
1138          * Get size of the screen.
1139          */
1140         scrsize();
1141         pos_init();
1142
1143         auto_wrap = ltgetflag("am");
1144         ignaw = ltgetflag("xn");
1145         above_mem = ltgetflag("da");
1146         below_mem = ltgetflag("db");
1147         clear_bg = ltgetflag("ut");
1148
1149         /*
1150          * Assumes termcap variable "sg" is the printing width of:
1151          * the standout sequence, the end standout sequence,
1152          * the underline sequence, the end underline sequence,
1153          * the boldface sequence, and the end boldface sequence.
1154          */
1155         if ((so_s_width = ltgetnum("sg")) < 0)
1156                 so_s_width = 0;
1157         so_e_width = so_s_width;
1158
1159         bo_s_width = bo_e_width = so_s_width;
1160         ul_s_width = ul_e_width = so_s_width;
1161         bl_s_width = bl_e_width = so_s_width;
1162
1163 #if HILITE_SEARCH
1164         if (so_s_width > 0 || so_e_width > 0)
1165                 /*
1166                  * Disable highlighting by default on magic cookie terminals.
1167                  * Turning on highlighting might change the displayed width
1168                  * of a line, causing the display to get messed up.
1169                  * The user can turn it back on with -g, 
1170                  * but she won't like the results.
1171                  */
1172                 hilite_search = 0;
1173 #endif
1174
1175         /*
1176          * Get various string-valued capabilities.
1177          */
1178         sp = sbuf;
1179
1180 #if HAVE_OSPEED
1181         sc_pad = ltgetstr("pc", &sp);
1182         if (sc_pad != NULL)
1183                 PC = *sc_pad;
1184 #endif
1185
1186         sc_s_keypad = ltgetstr("ks", &sp);
1187         if (sc_s_keypad == NULL)
1188                 sc_s_keypad = "";
1189         sc_e_keypad = ltgetstr("ke", &sp);
1190         if (sc_e_keypad == NULL)
1191                 sc_e_keypad = "";
1192                 
1193         sc_init = ltgetstr("ti", &sp);
1194         if (sc_init == NULL)
1195                 sc_init = "";
1196
1197         sc_deinit= ltgetstr("te", &sp);
1198         if (sc_deinit == NULL)
1199                 sc_deinit = "";
1200
1201         sc_eol_clear = ltgetstr("ce", &sp);
1202         if (sc_eol_clear == NULL || *sc_eol_clear == '\0')
1203         {
1204                 missing_cap = 1;
1205                 sc_eol_clear = "";
1206         }
1207
1208         sc_eos_clear = ltgetstr("cd", &sp);
1209         if (below_mem && (sc_eos_clear == NULL || *sc_eos_clear == '\0'))
1210         {
1211                 missing_cap = 1;
1212                 sc_eos_clear = "";
1213         }
1214
1215         sc_clear = ltgetstr("cl", &sp);
1216         if (sc_clear == NULL || *sc_clear == '\0')
1217         {
1218                 missing_cap = 1;
1219                 sc_clear = "\n\n";
1220         }
1221
1222         sc_move = ltgetstr("cm", &sp);
1223         if (sc_move == NULL || *sc_move == '\0')
1224         {
1225                 /*
1226                  * This is not an error here, because we don't 
1227                  * always need sc_move.
1228                  * We need it only if we don't have home or lower-left.
1229                  */
1230                 sc_move = "";
1231                 can_goto_line = 0;
1232         } else
1233                 can_goto_line = 1;
1234
1235         tmodes("so", "se", &sc_s_in, &sc_s_out, "", "", &sp);
1236         tmodes("us", "ue", &sc_u_in, &sc_u_out, sc_s_in, sc_s_out, &sp);
1237         tmodes("md", "me", &sc_b_in, &sc_b_out, sc_s_in, sc_s_out, &sp);
1238         tmodes("mb", "me", &sc_bl_in, &sc_bl_out, sc_s_in, sc_s_out, &sp);
1239
1240         sc_visual_bell = ltgetstr("vb", &sp);
1241         if (sc_visual_bell == NULL)
1242                 sc_visual_bell = "";
1243
1244         if (ltgetflag("bs"))
1245                 sc_backspace = "\b";
1246         else
1247         {
1248                 sc_backspace = ltgetstr("bc", &sp);
1249                 if (sc_backspace == NULL || *sc_backspace == '\0')
1250                         sc_backspace = "\b";
1251         }
1252
1253         /*
1254          * Choose between using "ho" and "cm" ("home" and "cursor move")
1255          * to move the cursor to the upper left corner of the screen.
1256          */
1257         t1 = ltgetstr("ho", &sp);
1258         if (t1 == NULL)
1259                 t1 = "";
1260         if (*sc_move == '\0')
1261                 t2 = "";
1262         else
1263         {
1264                 strcpy(sp, tgoto(sc_move, 0, 0));
1265                 t2 = sp;
1266                 sp += strlen(sp) + 1;
1267         }
1268         sc_home = cheaper(t1, t2, "|\b^");
1269
1270         /*
1271          * Choose between using "ll" and "cm"  ("lower left" and "cursor move")
1272          * to move the cursor to the lower left corner of the screen.
1273          */
1274         t1 = ltgetstr("ll", &sp);
1275         if (t1 == NULL)
1276                 t1 = "";
1277         if (*sc_move == '\0')
1278                 t2 = "";
1279         else
1280         {
1281                 strcpy(sp, tgoto(sc_move, 0, sc_height-1));
1282                 t2 = sp;
1283                 sp += strlen(sp) + 1;
1284         }
1285         sc_lower_left = cheaper(t1, t2, "\r");
1286
1287         /*
1288          * Get carriage return string.
1289          */
1290         sc_return = ltgetstr("cr", &sp);
1291         if (sc_return == NULL)
1292                 sc_return = "\r";
1293
1294         /*
1295          * Choose between using "al" or "sr" ("add line" or "scroll reverse")
1296          * to add a line at the top of the screen.
1297          */
1298         t1 = ltgetstr("al", &sp);
1299         if (t1 == NULL)
1300                 t1 = "";
1301         t2 = ltgetstr("sr", &sp);
1302         if (t2 == NULL)
1303                 t2 = "";
1304 #if OS2
1305         if (*t1 == '\0' && *t2 == '\0')
1306                 sc_addline = "";
1307         else
1308 #endif
1309         if (above_mem)
1310                 sc_addline = t1;
1311         else
1312                 sc_addline = cheaper(t1, t2, "");
1313         if (*sc_addline == '\0')
1314         {
1315                 /*
1316                  * Force repaint on any backward movement.
1317                  */
1318                 no_back_scroll = 1;
1319         }
1320 #endif /* MSDOS_COMPILER */
1321 }
1322
1323 #if !MSDOS_COMPILER
1324 /*
1325  * Return the cost of displaying a termcap string.
1326  * We use the trick of calling tputs, but as a char printing function
1327  * we give it inc_costcount, which just increments "costcount".
1328  * This tells us how many chars would be printed by using this string.
1329  * {{ Couldn't we just use strlen? }}
1330  */
1331 static int costcount;
1332
1333 /*ARGSUSED*/
1334         static int
1335 inc_costcount(c)
1336         int c;
1337 {
1338         costcount++;
1339         return (c);
1340 }
1341
1342         static int
1343 cost(t)
1344         char *t;
1345 {
1346         costcount = 0;
1347         tputs(t, sc_height, inc_costcount);
1348         return (costcount);
1349 }
1350
1351 /*
1352  * Return the "best" of the two given termcap strings.
1353  * The best, if both exist, is the one with the lower 
1354  * cost (see cost() function).
1355  */
1356         static char *
1357 cheaper(t1, t2, def)
1358         char *t1, *t2;
1359         char *def;
1360 {
1361         if (*t1 == '\0' && *t2 == '\0')
1362         {
1363                 missing_cap = 1;
1364                 return (def);
1365         }
1366         if (*t1 == '\0')
1367                 return (t2);
1368         if (*t2 == '\0')
1369                 return (t1);
1370         if (cost(t1) < cost(t2))
1371                 return (t1);
1372         return (t2);
1373 }
1374
1375         static void
1376 tmodes(incap, outcap, instr, outstr, def_instr, def_outstr, spp)
1377         char *incap;
1378         char *outcap;
1379         char **instr;
1380         char **outstr;
1381         char *def_instr;
1382         char *def_outstr;
1383         char **spp;
1384 {
1385         *instr = ltgetstr(incap, spp);
1386         if (*instr == NULL)
1387         {
1388                 /* Use defaults. */
1389                 *instr = def_instr;
1390                 *outstr = def_outstr;
1391                 return;
1392         }
1393
1394         *outstr = ltgetstr(outcap, spp);
1395         if (*outstr == NULL)
1396                 /* No specific out capability; use "me". */
1397                 *outstr = ltgetstr("me", spp);
1398         if (*outstr == NULL)
1399                 /* Don't even have "me"; use a null string. */
1400                 *outstr = "";
1401 }
1402
1403 #endif /* MSDOS_COMPILER */
1404
1405
1406 /*
1407  * Below are the functions which perform all the 
1408  * terminal-specific screen manipulation.
1409  */
1410
1411
1412 #if MSDOS_COMPILER
1413
1414 #if MSDOS_COMPILER==WIN32C
1415         static void
1416 _settextposition(int row, int col)
1417 {
1418         COORD cpos;
1419         CONSOLE_SCREEN_BUFFER_INFO csbi;
1420
1421         GetConsoleScreenBufferInfo(con_out, &csbi);
1422         cpos.X = csbi.srWindow.Left + (col - 1);
1423         cpos.Y = csbi.srWindow.Top + (row - 1);
1424         SetConsoleCursorPosition(con_out, cpos);
1425 }
1426 #endif
1427
1428 /*
1429  * Initialize the screen to the correct color at startup.
1430  */
1431         static void
1432 initcolor()
1433 {
1434         SETCOLORS(nm_fg_color, nm_bg_color);
1435 #if 0
1436         /*
1437          * This clears the screen at startup.  This is different from
1438          * the behavior of other versions of less.  Disable it for now.
1439          */
1440         char *blanks;
1441         int row;
1442         int col;
1443         
1444         /*
1445          * Create a complete, blank screen using "normal" colors.
1446          */
1447         SETCOLORS(nm_fg_color, nm_bg_color);
1448         blanks = (char *) ecalloc(width+1, sizeof(char));
1449         for (col = 0;  col < sc_width;  col++)
1450                 blanks[col] = ' ';
1451         blanks[sc_width] = '\0';
1452         for (row = 0;  row < sc_height;  row++)
1453                 _outtext(blanks);
1454         free(blanks);
1455 #endif
1456 }
1457 #endif
1458
1459 #if MSDOS_COMPILER==WIN32C
1460
1461 /*
1462  * Termcap-like init with a private win32 console.
1463  */
1464         static void
1465 win32_init_term()
1466 {
1467         CONSOLE_SCREEN_BUFFER_INFO scr;
1468         COORD size;
1469
1470         if (con_out_save == INVALID_HANDLE_VALUE)
1471                 return;
1472
1473         GetConsoleScreenBufferInfo(con_out_save, &scr);
1474
1475         if (con_out_ours == INVALID_HANDLE_VALUE)
1476         {
1477                 /*
1478                  * Create our own screen buffer, so that we
1479                  * may restore the original when done.
1480                  */
1481                 con_out_ours = CreateConsoleScreenBuffer(
1482                         GENERIC_WRITE | GENERIC_READ,
1483                         FILE_SHARE_WRITE | FILE_SHARE_READ,
1484                         (LPSECURITY_ATTRIBUTES) NULL,
1485                         CONSOLE_TEXTMODE_BUFFER,
1486                         (LPVOID) NULL);
1487         }
1488
1489         size.X = scr.srWindow.Right - scr.srWindow.Left + 1;
1490         size.Y = scr.srWindow.Bottom - scr.srWindow.Top + 1;
1491         SetConsoleScreenBufferSize(con_out_ours, size);
1492         SetConsoleActiveScreenBuffer(con_out_ours);
1493         con_out = con_out_ours;
1494 }
1495
1496 /*
1497  * Restore the startup console.
1498  */
1499 static void
1500 win32_deinit_term()
1501 {
1502         if (con_out_save == INVALID_HANDLE_VALUE)
1503                 return;
1504         if (quitting)
1505                 (void) CloseHandle(con_out_ours);
1506         SetConsoleActiveScreenBuffer(con_out_save);
1507         con_out = con_out_save;
1508 }
1509
1510 #endif
1511
1512 /*
1513  * Initialize terminal
1514  */
1515         public void
1516 init()
1517 {
1518 #if !MSDOS_COMPILER
1519         if (!no_init)
1520                 tputs(sc_init, sc_height, putchr);
1521         if (!no_keypad)
1522                 tputs(sc_s_keypad, sc_height, putchr);
1523         if (top_scroll) 
1524         {
1525                 int i;
1526
1527                 /*
1528                  * This is nice to terminals with no alternate screen,
1529                  * but with saved scrolled-off-the-top lines.  This way,
1530                  * no previous line is lost, but we start with a whole
1531                  * screen to ourself.
1532                  */
1533                 for (i = 1; i < sc_height; i++)
1534                         putchr('\n');
1535         }
1536 #else
1537 #if MSDOS_COMPILER==WIN32C
1538         if (!no_init)
1539                 win32_init_term();
1540 #endif
1541         initcolor();
1542         flush();
1543 #endif
1544         init_done = 1;
1545 }
1546
1547 /*
1548  * Deinitialize terminal
1549  */
1550         public void
1551 deinit()
1552 {
1553         if (!init_done)
1554                 return;
1555 #if !MSDOS_COMPILER
1556         if (!no_keypad)
1557                 tputs(sc_e_keypad, sc_height, putchr);
1558         if (!no_init)
1559                 tputs(sc_deinit, sc_height, putchr);
1560 #else
1561         /* Restore system colors. */
1562         SETCOLORS(sy_fg_color, sy_bg_color);
1563 #if MSDOS_COMPILER==WIN32C
1564         if (!no_init)
1565                 win32_deinit_term();
1566 #else
1567         /* Need clreol to make SETCOLORS take effect. */
1568         clreol();
1569 #endif
1570 #endif
1571         init_done = 0;
1572 }
1573
1574 /*
1575  * Home cursor (move to upper left corner of screen).
1576  */
1577         public void
1578 home()
1579 {
1580 #if !MSDOS_COMPILER
1581         tputs(sc_home, 1, putchr);
1582 #else
1583         flush();
1584         _settextposition(1,1);
1585 #endif
1586 }
1587
1588 /*
1589  * Add a blank line (called with cursor at home).
1590  * Should scroll the display down.
1591  */
1592         public void
1593 add_line()
1594 {
1595 #if !MSDOS_COMPILER
1596         tputs(sc_addline, sc_height, putchr);
1597 #else
1598         flush();
1599 #if MSDOS_COMPILER==MSOFTC
1600         _scrolltextwindow(_GSCROLLDOWN);
1601         _settextposition(1,1);
1602 #else
1603 #if MSDOS_COMPILER==BORLANDC || MSDOS_COMPILER==DJGPPC
1604         movetext(1,1, sc_width,sc_height-1, 1,2);
1605         gotoxy(1,1);
1606         clreol();
1607 #else
1608 #if MSDOS_COMPILER==WIN32C
1609     {
1610         CHAR_INFO fillchar;
1611         SMALL_RECT rcSrc, rcClip;
1612         COORD new_org;
1613         CONSOLE_SCREEN_BUFFER_INFO csbi;
1614
1615         GetConsoleScreenBufferInfo(con_out,&csbi);
1616
1617         /* The clip rectangle is the entire visible screen. */
1618         rcClip.Left = csbi.srWindow.Left;
1619         rcClip.Top = csbi.srWindow.Top;
1620         rcClip.Right = csbi.srWindow.Right;
1621         rcClip.Bottom = csbi.srWindow.Bottom;
1622
1623         /* The source rectangle is the visible screen minus the last line. */
1624         rcSrc = rcClip;
1625         rcSrc.Bottom--;
1626
1627         /* Move the top left corner of the source window down one row. */
1628         new_org.X = rcSrc.Left;
1629         new_org.Y = rcSrc.Top + 1;
1630
1631         /* Fill the right character and attributes. */
1632         fillchar.Char.AsciiChar = ' ';
1633         curr_attr = MAKEATTR(nm_fg_color, nm_bg_color);
1634         fillchar.Attributes = curr_attr;
1635         ScrollConsoleScreenBuffer(con_out, &rcSrc, &rcClip, new_org, &fillchar);
1636         _settextposition(1,1);
1637     }
1638 #endif
1639 #endif
1640 #endif
1641 #endif
1642 }
1643
1644 #if 0
1645 /*
1646  * Remove the n topmost lines and scroll everything below it in the 
1647  * window upward.  This is needed to stop leaking the topmost line 
1648  * into the scrollback buffer when we go down-one-line (in WIN32).
1649  */
1650         public void
1651 remove_top(n)
1652         int n;
1653 {
1654 #if MSDOS_COMPILER==WIN32C
1655         SMALL_RECT rcSrc, rcClip;
1656         CHAR_INFO fillchar;
1657         COORD new_org;
1658         CONSOLE_SCREEN_BUFFER_INFO csbi; /* to get buffer info */
1659
1660         if (n >= sc_height - 1)
1661         {
1662                 clear();
1663                 home();
1664                 return;
1665         }
1666
1667         flush();
1668
1669         GetConsoleScreenBufferInfo(con_out, &csbi);
1670
1671         /* Get the extent of all-visible-rows-but-the-last. */
1672         rcSrc.Left    = csbi.srWindow.Left;
1673         rcSrc.Top     = csbi.srWindow.Top + n;
1674         rcSrc.Right   = csbi.srWindow.Right;
1675         rcSrc.Bottom  = csbi.srWindow.Bottom;
1676
1677         /* Get the clip rectangle. */
1678         rcClip.Left   = rcSrc.Left;
1679         rcClip.Top    = csbi.srWindow.Top;
1680         rcClip.Right  = rcSrc.Right;
1681         rcClip.Bottom = rcSrc.Bottom ;
1682
1683         /* Move the source window up n rows. */
1684         new_org.X = rcSrc.Left;
1685         new_org.Y = rcSrc.Top - n;
1686
1687         /* Fill the right character and attributes. */
1688         fillchar.Char.AsciiChar = ' ';
1689         curr_attr = MAKEATTR(nm_fg_color, nm_bg_color);
1690         fillchar.Attributes = curr_attr;
1691
1692         ScrollConsoleScreenBuffer(con_out, &rcSrc, &rcClip, new_org, &fillchar);
1693
1694         /* Position cursor on first blank line. */
1695         goto_line(sc_height - n - 1);
1696 #endif
1697 }
1698 #endif
1699
1700 #if MSDOS_COMPILER==WIN32C
1701 /*
1702  * Clear the screen.
1703  */
1704         static void
1705 win32_clear()
1706 {
1707         /*
1708          * This will clear only the currently visible rows of the NT
1709          * console buffer, which means none of the precious scrollback
1710          * rows are touched making for faster scrolling.  Note that, if
1711          * the window has fewer columns than the console buffer (i.e.
1712          * there is a horizontal scrollbar as well), the entire width
1713          * of the visible rows will be cleared.
1714          */
1715         COORD topleft;
1716         DWORD nchars;
1717         DWORD winsz;
1718         CONSOLE_SCREEN_BUFFER_INFO csbi;
1719
1720         /* get the number of cells in the current buffer */
1721         GetConsoleScreenBufferInfo(con_out, &csbi);
1722         winsz = csbi.dwSize.X * (csbi.srWindow.Bottom - csbi.srWindow.Top + 1);
1723         topleft.X = 0;
1724         topleft.Y = csbi.srWindow.Top;
1725
1726         curr_attr = MAKEATTR(nm_fg_color, nm_bg_color);
1727         FillConsoleOutputCharacter(con_out, ' ', winsz, topleft, &nchars);
1728         FillConsoleOutputAttribute(con_out, curr_attr, winsz, topleft, &nchars);
1729 }
1730
1731 /*
1732  * Remove the n topmost lines and scroll everything below it in the 
1733  * window upward.
1734  */
1735         public void
1736 win32_scroll_up(n)
1737         int n;
1738 {
1739         SMALL_RECT rcSrc, rcClip;
1740         CHAR_INFO fillchar;
1741         COORD topleft;
1742         COORD new_org;
1743         DWORD nchars;
1744         DWORD size;
1745         CONSOLE_SCREEN_BUFFER_INFO csbi;
1746
1747         if (n <= 0)
1748                 return;
1749
1750         if (n >= sc_height - 1)
1751         {
1752                 win32_clear();
1753                 _settextposition(1,1);
1754                 return;
1755         }
1756
1757         /* Get the extent of what will remain visible after scrolling. */
1758         GetConsoleScreenBufferInfo(con_out, &csbi);
1759         rcSrc.Left    = csbi.srWindow.Left;
1760         rcSrc.Top     = csbi.srWindow.Top + n;
1761         rcSrc.Right   = csbi.srWindow.Right;
1762         rcSrc.Bottom  = csbi.srWindow.Bottom;
1763
1764         /* Get the clip rectangle. */
1765         rcClip.Left   = rcSrc.Left;
1766         rcClip.Top    = csbi.srWindow.Top;
1767         rcClip.Right  = rcSrc.Right;
1768         rcClip.Bottom = rcSrc.Bottom ;
1769
1770         /* Move the source text to the top of the screen. */
1771         new_org.X = rcSrc.Left;
1772         new_org.Y = 0;
1773
1774         /* Fill the right character and attributes. */
1775         fillchar.Char.AsciiChar = ' ';
1776         fillchar.Attributes = MAKEATTR(nm_fg_color, nm_bg_color);
1777
1778         /* Scroll the window. */
1779         SetConsoleTextAttribute(con_out, fillchar.Attributes);
1780         ScrollConsoleScreenBuffer(con_out, &rcSrc, &rcClip, new_org, &fillchar);
1781
1782         /* Clear remaining lines at bottom. */
1783         topleft.X = csbi.dwCursorPosition.X;
1784         topleft.Y = rcSrc.Bottom - n;
1785         size = (n * csbi.dwSize.X) + (rcSrc.Right - topleft.X);
1786         FillConsoleOutputCharacter(con_out, ' ', size, topleft,
1787                 &nchars);
1788         FillConsoleOutputAttribute(con_out, fillchar.Attributes, size, topleft,
1789                 &nchars);
1790         SetConsoleTextAttribute(con_out, curr_attr);
1791
1792         /* Move cursor n lines up from where it was. */
1793         csbi.dwCursorPosition.Y -= n;
1794         SetConsoleCursorPosition(con_out, csbi.dwCursorPosition);
1795 }
1796 #endif
1797
1798 /*
1799  * Move cursor to lower left corner of screen.
1800  */
1801         public void
1802 lower_left()
1803 {
1804 #if !MSDOS_COMPILER
1805         tputs(sc_lower_left, 1, putchr);
1806 #else
1807         flush();
1808         _settextposition(sc_height, 1);
1809 #endif
1810 }
1811
1812 /*
1813  * Move cursor to left position of current line.
1814  */
1815         public void
1816 line_left()
1817 {
1818 #if !MSDOS_COMPILER
1819         tputs(sc_return, 1, putchr);
1820 #else
1821         int row;
1822         flush();
1823 #if MSDOS_COMPILER==WIN32C
1824         {
1825                 CONSOLE_SCREEN_BUFFER_INFO scr;
1826                 GetConsoleScreenBufferInfo(con_out, &scr);
1827                 row = scr.dwCursorPosition.Y - scr.srWindow.Top + 1;
1828         }
1829 #else
1830         {
1831                 struct rccoord tpos = _gettextposition();
1832                 row = tpos.row;
1833         }
1834 #endif
1835         _settextposition(row, 1);
1836 #endif
1837 }
1838
1839 /*
1840  * Check if the console size has changed and reset internals 
1841  * (in lieu of SIGWINCH for WIN32).
1842  */
1843         public void
1844 check_winch()
1845 {
1846 #if MSDOS_COMPILER==WIN32C
1847         CONSOLE_SCREEN_BUFFER_INFO scr;
1848         COORD size;
1849
1850         if (con_out == INVALID_HANDLE_VALUE)
1851                 return;
1852  
1853         flush();
1854         GetConsoleScreenBufferInfo(con_out, &scr);
1855         size.Y = scr.srWindow.Bottom - scr.srWindow.Top + 1;
1856         size.X = scr.srWindow.Right - scr.srWindow.Left + 1;
1857         if (size.Y != sc_height || size.X != sc_width)
1858         {
1859                 sc_height = size.Y;
1860                 sc_width = size.X;
1861                 if (!no_init && con_out_ours == con_out)
1862                         SetConsoleScreenBufferSize(con_out, size);
1863                 pos_init();
1864                 wscroll = (sc_height + 1) / 2;
1865                 screen_trashed = 1;
1866         }
1867 #endif
1868 }
1869
1870 /*
1871  * Goto a specific line on the screen.
1872  */
1873         public void
1874 goto_line(slinenum)
1875         int slinenum;
1876 {
1877 #if !MSDOS_COMPILER
1878         tputs(tgoto(sc_move, 0, slinenum), 1, putchr);
1879 #else
1880         flush();
1881         _settextposition(slinenum+1, 1);
1882 #endif
1883 }
1884
1885 #if MSDOS_COMPILER==MSOFTC || MSDOS_COMPILER==BORLANDC
1886 /*
1887  * Create an alternate screen which is all white.
1888  * This screen is used to create a "flash" effect, by displaying it
1889  * briefly and then switching back to the normal screen.
1890  * {{ Yuck!  There must be a better way to get a visual bell. }}
1891  */
1892         static void
1893 create_flash()
1894 {
1895 #if MSDOS_COMPILER==MSOFTC
1896         struct videoconfig w;
1897         char *blanks;
1898         int row, col;
1899         
1900         _getvideoconfig(&w);
1901         videopages = w.numvideopages;
1902         if (videopages < 2)
1903         {
1904                 at_enter(AT_STANDOUT);
1905                 at_exit();
1906         } else
1907         {
1908                 _setactivepage(1);
1909                 at_enter(AT_STANDOUT);
1910                 blanks = (char *) ecalloc(w.numtextcols, sizeof(char));
1911                 for (col = 0;  col < w.numtextcols;  col++)
1912                         blanks[col] = ' ';
1913                 for (row = w.numtextrows;  row > 0;  row--)
1914                         _outmem(blanks, w.numtextcols);
1915                 _setactivepage(0);
1916                 _setvisualpage(0);
1917                 free(blanks);
1918                 at_exit();
1919         }
1920 #else
1921 #if MSDOS_COMPILER==BORLANDC
1922         register int n;
1923
1924         whitescreen = (unsigned short *) 
1925                 malloc(sc_width * sc_height * sizeof(short));
1926         if (whitescreen == NULL)
1927                 return;
1928         for (n = 0;  n < sc_width * sc_height;  n++)
1929                 whitescreen[n] = 0x7020;
1930 #else
1931 #if MSDOS_COMPILER==WIN32C
1932         register int n;
1933
1934         whitescreen = (WORD *)
1935                 malloc(sc_height * sc_width * sizeof(WORD));
1936         if (whitescreen == NULL)
1937                 return;
1938         /* Invert the standard colors. */
1939         for (n = 0;  n < sc_width * sc_height;  n++)
1940                 whitescreen[n] = (WORD)((nm_fg_color << 4) | nm_bg_color);
1941 #endif
1942 #endif
1943 #endif
1944         flash_created = 1;
1945 }
1946 #endif /* MSDOS_COMPILER */
1947
1948 /*
1949  * Output the "visual bell", if there is one.
1950  */
1951         public void
1952 vbell()
1953 {
1954 #if !MSDOS_COMPILER
1955         if (*sc_visual_bell == '\0')
1956                 return;
1957         tputs(sc_visual_bell, sc_height, putchr);
1958 #else
1959 #if MSDOS_COMPILER==DJGPPC
1960         ScreenVisualBell();
1961 #else
1962 #if MSDOS_COMPILER==MSOFTC
1963         /*
1964          * Create a flash screen on the second video page.
1965          * Switch to that page, then switch back.
1966          */
1967         if (!flash_created)
1968                 create_flash();
1969         if (videopages < 2)
1970                 return;
1971         _setvisualpage(1);
1972         delay(100);
1973         _setvisualpage(0);
1974 #else
1975 #if MSDOS_COMPILER==BORLANDC
1976         unsigned short *currscreen;
1977
1978         /*
1979          * Get a copy of the current screen.
1980          * Display the flash screen.
1981          * Then restore the old screen.
1982          */
1983         if (!flash_created)
1984                 create_flash();
1985         if (whitescreen == NULL)
1986                 return;
1987         currscreen = (unsigned short *) 
1988                 malloc(sc_width * sc_height * sizeof(short));
1989         if (currscreen == NULL) return;
1990         gettext(1, 1, sc_width, sc_height, currscreen);
1991         puttext(1, 1, sc_width, sc_height, whitescreen);
1992         delay(100);
1993         puttext(1, 1, sc_width, sc_height, currscreen);
1994         free(currscreen);
1995 #else
1996 #if MSDOS_COMPILER==WIN32C
1997         /* paint screen with an inverse color */
1998         clear();
1999
2000         /* leave it displayed for 100 msec. */
2001         Sleep(100);
2002
2003         /* restore with a redraw */
2004         repaint();
2005 #endif
2006 #endif
2007 #endif
2008 #endif
2009 #endif
2010 }
2011
2012 /*
2013  * Make a noise.
2014  */
2015         static void
2016 beep()
2017 {
2018 #if !MSDOS_COMPILER
2019         putchr(CONTROL('G'));
2020 #else
2021 #if MSDOS_COMPILER==WIN32C
2022         MessageBeep(0);
2023 #else
2024         write(1, "\7", 1);
2025 #endif
2026 #endif
2027 }
2028
2029 /*
2030  * Ring the terminal bell.
2031  */
2032         public void
2033 bell()
2034 {
2035         if (quiet == VERY_QUIET)
2036                 vbell();
2037         else
2038                 beep();
2039 }
2040
2041 /*
2042  * Clear the screen.
2043  */
2044         public void
2045 clear()
2046 {
2047 #if !MSDOS_COMPILER
2048         tputs(sc_clear, sc_height, putchr);
2049 #else
2050         flush();
2051 #if MSDOS_COMPILER==WIN32C
2052         win32_clear();
2053 #else
2054         _clearscreen(_GCLEARSCREEN);
2055 #endif
2056 #endif
2057 }
2058
2059 /*
2060  * Clear from the cursor to the end of the cursor's line.
2061  * {{ This must not move the cursor. }}
2062  */
2063         public void
2064 clear_eol()
2065 {
2066 #if !MSDOS_COMPILER
2067         tputs(sc_eol_clear, 1, putchr);
2068 #else
2069 #if MSDOS_COMPILER==MSOFTC
2070         short top, left;
2071         short bot, right;
2072         struct rccoord tpos;
2073         
2074         flush();
2075         /*
2076          * Save current state.
2077          */
2078         tpos = _gettextposition();
2079         _gettextwindow(&top, &left, &bot, &right);
2080         /*
2081          * Set a temporary window to the current line,
2082          * from the cursor's position to the right edge of the screen.
2083          * Then clear that window.
2084          */
2085         _settextwindow(tpos.row, tpos.col, tpos.row, sc_width);
2086         _clearscreen(_GWINDOW);
2087         /*
2088          * Restore state.
2089          */
2090         _settextwindow(top, left, bot, right);
2091         _settextposition(tpos.row, tpos.col);
2092 #else
2093 #if MSDOS_COMPILER==BORLANDC || MSDOS_COMPILER==DJGPPC
2094         flush();
2095         clreol();
2096 #else
2097 #if MSDOS_COMPILER==WIN32C
2098         DWORD           nchars;
2099         COORD           cpos;
2100         CONSOLE_SCREEN_BUFFER_INFO scr;
2101
2102         flush();
2103         memset(&scr, 0, sizeof(scr));
2104         GetConsoleScreenBufferInfo(con_out, &scr);
2105         cpos.X = scr.dwCursorPosition.X;
2106         cpos.Y = scr.dwCursorPosition.Y;
2107         curr_attr = MAKEATTR(nm_fg_color, nm_bg_color);
2108         FillConsoleOutputAttribute(con_out, curr_attr,
2109                 scr.dwSize.X - cpos.X, cpos, &nchars);
2110         FillConsoleOutputCharacter(con_out, ' ',
2111                 scr.dwSize.X - cpos.X, cpos, &nchars);
2112 #endif
2113 #endif
2114 #endif
2115 #endif
2116 }
2117
2118 /*
2119  * Clear the current line.
2120  * Clear the screen if there's off-screen memory below the display.
2121  */
2122         static void
2123 clear_eol_bot()
2124 {
2125 #if MSDOS_COMPILER
2126         clear_eol();
2127 #else
2128         if (below_mem)
2129                 tputs(sc_eos_clear, 1, putchr);
2130         else
2131                 tputs(sc_eol_clear, 1, putchr);
2132 #endif
2133 }
2134
2135 /*
2136  * Clear the bottom line of the display.
2137  * Leave the cursor at the beginning of the bottom line.
2138  */
2139         public void
2140 clear_bot()
2141 {
2142         /*
2143          * If we're in a non-normal attribute mode, temporarily exit
2144          * the mode while we do the clear.  Some terminals fill the
2145          * cleared area with the current attribute.
2146          */
2147         if (oldbot)
2148                 lower_left();
2149         else
2150                 line_left();
2151
2152         if (attrmode == AT_NORMAL)
2153                 clear_eol_bot();
2154         else
2155         {
2156                 int saved_attrmode = attrmode;
2157
2158                 at_exit();
2159                 clear_eol_bot();
2160                 at_enter(saved_attrmode);
2161         }
2162 }
2163
2164         public void
2165 at_enter(attr)
2166         int attr;
2167 {
2168         attr = apply_at_specials(attr);
2169
2170 #if !MSDOS_COMPILER
2171         /* The one with the most priority is last.  */
2172         if (attr & AT_UNDERLINE)
2173                 tputs(sc_u_in, 1, putchr);
2174         if (attr & AT_BOLD)
2175                 tputs(sc_b_in, 1, putchr);
2176         if (attr & AT_BLINK)
2177                 tputs(sc_bl_in, 1, putchr);
2178         if (attr & AT_STANDOUT)
2179                 tputs(sc_s_in, 1, putchr);
2180 #else
2181         flush();
2182         /* The one with the most priority is first.  */
2183         if (attr & AT_STANDOUT)
2184         {
2185                 SETCOLORS(so_fg_color, so_bg_color);
2186         } else if (attr & AT_BLINK)
2187         {
2188                 SETCOLORS(bl_fg_color, bl_bg_color);
2189         }
2190         else if (attr & AT_BOLD)
2191         {
2192                 SETCOLORS(bo_fg_color, bo_bg_color);
2193         }
2194         else if (attr & AT_UNDERLINE)
2195         {
2196                 SETCOLORS(ul_fg_color, ul_bg_color);
2197         }
2198 #endif
2199
2200         attrmode = attr;
2201 }
2202
2203         public void
2204 at_exit()
2205 {
2206 #if !MSDOS_COMPILER
2207         /* Undo things in the reverse order we did them.  */
2208         if (attrmode & AT_STANDOUT)
2209                 tputs(sc_s_out, 1, putchr);
2210         if (attrmode & AT_BLINK)
2211                 tputs(sc_bl_out, 1, putchr);
2212         if (attrmode & AT_BOLD)
2213                 tputs(sc_b_out, 1, putchr);
2214         if (attrmode & AT_UNDERLINE)
2215                 tputs(sc_u_out, 1, putchr);
2216 #else
2217         flush();
2218         SETCOLORS(nm_fg_color, nm_bg_color);
2219 #endif
2220
2221         attrmode = AT_NORMAL;
2222 }
2223
2224         public void
2225 at_switch(attr)
2226         int attr;
2227 {
2228         int new_attrmode = apply_at_specials(attr);
2229         int ignore_modes = AT_ANSI;
2230
2231         if ((new_attrmode & ~ignore_modes) != (attrmode & ~ignore_modes))
2232         {
2233                 at_exit();
2234                 at_enter(attr);
2235         }
2236 }
2237
2238         public int
2239 is_at_equiv(attr1, attr2)
2240         int attr1;
2241         int attr2;
2242 {
2243         attr1 = apply_at_specials(attr1);
2244         attr2 = apply_at_specials(attr2);
2245
2246         return (attr1 == attr2);
2247 }
2248
2249         public int
2250 apply_at_specials(attr)
2251         int attr;
2252 {
2253         if (attr & AT_BINARY)
2254                 attr |= binattr;
2255         if (attr & AT_HILITE)
2256                 attr |= AT_STANDOUT;
2257         attr &= ~(AT_BINARY|AT_HILITE);
2258
2259         return attr;
2260 }
2261
2262 #if 0 /* No longer used */
2263 /*
2264  * Erase the character to the left of the cursor 
2265  * and move the cursor left.
2266  */
2267         public void
2268 backspace()
2269 {
2270 #if !MSDOS_COMPILER
2271         /* 
2272          * Erase the previous character by overstriking with a space.
2273          */
2274         tputs(sc_backspace, 1, putchr);
2275         putchr(' ');
2276         tputs(sc_backspace, 1, putchr);
2277 #else
2278 #if MSDOS_COMPILER==MSOFTC
2279         struct rccoord tpos;
2280         
2281         flush();
2282         tpos = _gettextposition();
2283         if (tpos.col <= 1)
2284                 return;
2285         _settextposition(tpos.row, tpos.col-1);
2286         _outtext(" ");
2287         _settextposition(tpos.row, tpos.col-1);
2288 #else
2289 #if MSDOS_COMPILER==BORLANDC || MSDOS_COMPILER==DJGPPC
2290         cputs("\b");
2291 #else
2292 #if MSDOS_COMPILER==WIN32C
2293         COORD cpos;
2294         DWORD cChars;
2295         CONSOLE_SCREEN_BUFFER_INFO scr;
2296
2297         flush();
2298         GetConsoleScreenBufferInfo(con_out, &scr);
2299         cpos = scr.dwCursorPosition;
2300         if (cpos.X <= 0)
2301                 return;
2302         cpos.X--;
2303         SetConsoleCursorPosition(con_out, cpos);
2304         FillConsoleOutputCharacter(con_out, (TCHAR)' ', 1, cpos, &cChars);
2305         SetConsoleCursorPosition(con_out, cpos);
2306 #endif
2307 #endif
2308 #endif
2309 #endif
2310 }
2311 #endif /* 0 */
2312
2313 /*
2314  * Output a plain backspace, without erasing the previous char.
2315  */
2316         public void
2317 putbs()
2318 {
2319 #if !MSDOS_COMPILER
2320         tputs(sc_backspace, 1, putchr);
2321 #else
2322         int row, col;
2323
2324         flush();
2325         {
2326 #if MSDOS_COMPILER==MSOFTC
2327                 struct rccoord tpos;
2328                 tpos = _gettextposition();
2329                 row = tpos.row;
2330                 col = tpos.col;
2331 #else
2332 #if MSDOS_COMPILER==BORLANDC || MSDOS_COMPILER==DJGPPC
2333                 row = wherey();
2334                 col = wherex();
2335 #else
2336 #if MSDOS_COMPILER==WIN32C
2337                 CONSOLE_SCREEN_BUFFER_INFO scr;
2338                 GetConsoleScreenBufferInfo(con_out, &scr);
2339                 row = scr.dwCursorPosition.Y - scr.srWindow.Top + 1;
2340                 col = scr.dwCursorPosition.X - scr.srWindow.Left + 1;
2341 #endif
2342 #endif
2343 #endif
2344         }
2345         if (col <= 1)
2346                 return;
2347         _settextposition(row, col-1);
2348 #endif /* MSDOS_COMPILER */
2349 }
2350
2351 #if MSDOS_COMPILER==WIN32C
2352 /*
2353  * Determine whether an input character is waiting to be read.
2354  */
2355         static int
2356 win32_kbhit(tty)
2357         HANDLE tty;
2358 {
2359         INPUT_RECORD ip;
2360         DWORD read;
2361
2362         if (keyCount > 0)
2363                 return (TRUE);
2364
2365         currentKey.ascii = 0;
2366         currentKey.scan = 0;
2367
2368         /*
2369          * Wait for a real key-down event, but
2370          * ignore SHIFT and CONTROL key events.
2371          */
2372         do
2373         {
2374                 PeekConsoleInput(tty, &ip, 1, &read);
2375                 if (read == 0)
2376                         return (FALSE);
2377                 ReadConsoleInput(tty, &ip, 1, &read);
2378         } while (ip.EventType != KEY_EVENT ||
2379                 ip.Event.KeyEvent.bKeyDown != TRUE ||
2380                 ip.Event.KeyEvent.wVirtualScanCode == 0 ||
2381                 ip.Event.KeyEvent.wVirtualKeyCode == VK_SHIFT ||
2382                 ip.Event.KeyEvent.wVirtualKeyCode == VK_CONTROL ||
2383                 ip.Event.KeyEvent.wVirtualKeyCode == VK_MENU);
2384                 
2385         currentKey.ascii = ip.Event.KeyEvent.uChar.AsciiChar;
2386         currentKey.scan = ip.Event.KeyEvent.wVirtualScanCode;
2387         keyCount = ip.Event.KeyEvent.wRepeatCount;
2388
2389         if (ip.Event.KeyEvent.dwControlKeyState & 
2390                 (LEFT_ALT_PRESSED | RIGHT_ALT_PRESSED))
2391         {
2392                 switch (currentKey.scan)
2393                 {
2394                 case PCK_ALT_E:     /* letter 'E' */
2395                         currentKey.ascii = 0;
2396                         break;
2397                 }
2398         } else if (ip.Event.KeyEvent.dwControlKeyState & 
2399                 (LEFT_CTRL_PRESSED | RIGHT_CTRL_PRESSED))
2400         {
2401                 switch (currentKey.scan)
2402                 {
2403                 case PCK_RIGHT: /* right arrow */
2404                         currentKey.scan = PCK_CTL_RIGHT;
2405                         break;
2406                 case PCK_LEFT: /* left arrow */
2407                         currentKey.scan = PCK_CTL_LEFT;
2408                         break;
2409                 case PCK_DELETE: /* delete */
2410                         currentKey.scan = PCK_CTL_DELETE;
2411                         break;
2412                 }
2413         }
2414         return (TRUE);
2415 }
2416
2417 /*
2418  * Read a character from the keyboard.
2419  */
2420         public char
2421 WIN32getch(tty)
2422         int tty;
2423 {
2424         int ascii;
2425
2426         if (pending_scancode)
2427         {
2428                 pending_scancode = 0;
2429                 return ((char)(currentKey.scan & 0x00FF));
2430         }
2431
2432         while (win32_kbhit((HANDLE)tty) == FALSE)
2433         {
2434                 Sleep(20);
2435                 if (ABORT_SIGS())
2436                         return ('\003');
2437                 continue;
2438         }
2439         keyCount --;
2440         ascii = currentKey.ascii;
2441         /*
2442          * On PC's, the extended keys return a 2 byte sequence beginning 
2443          * with '00', so if the ascii code is 00, the next byte will be 
2444          * the lsb of the scan code.
2445          */
2446         pending_scancode = (ascii == 0x00);
2447         return ((char)ascii);
2448 }
2449 #endif