]> asedeno.scripts.mit.edu Git - PuTTY.git/blob - terminal.c
d62c8cd5bdd77410e3010bd8c6789689535dc909
[PuTTY.git] / terminal.c
1 #include <windows.h>
2
3 #include <stdio.h>
4 #include <stdlib.h>
5
6 #include "putty.h"
7
8 #define CL_ANSIMIN      0x0001  /* Codes in all ANSI like terminals. */
9 #define CL_VT100        0x0002  /* VT100 */
10 #define CL_VT100AVO     0x0004  /* VT100 +AVO; 132x24 (not 132x14) & attrs */
11 #define CL_VT102        0x0008  /* VT102 */
12 #define CL_VT220        0x0010  /* VT220 */
13 #define CL_VT320        0x0020  /* VT320 */
14 #define CL_VT420        0x0040  /* VT420 */
15 #define CL_VT510        0x0080  /* VT510, NB VT510 includes ANSI */
16 #define CL_VT340TEXT    0x0100  /* VT340 extensions that appear in the VT420 */
17 #define CL_SCOANSI      0x1000  /* SCOANSI not in ANSIMIN. */
18 #define CL_ANSI         0x2000  /* ANSI ECMA-48 not in the VT100..VT420 */
19 #define CL_OTHER        0x4000  /* Others, Xterm, linux, putty, dunno, etc */
20
21 #define TM_ANSIMIN      (CL_ANSIMIN)
22 #define TM_VT100        (CL_ANSIMIN|CL_VT100)
23 #define TM_VT100AVO     (TM_VT100|CL_VT100AVO)
24 #define TM_VT102        (TM_VT100AVO|CL_VT102)
25 #define TM_VT220        (TM_VT102|CL_VT220)
26 #define TM_VTXXX        (TM_VT220|CL_VT340TEXT|CL_VT510|CL_VT420|CL_VT320)
27 #define TM_SCOANSI      (CL_ANSIMIN|CL_SCOANSI)
28
29 #define TM_PUTTY        (0xFFFF)
30
31 #define compatibility(x) \
32     if ( ((CL_##x)&compatibility_level) == 0 ) {        \
33        termstate=TOPLEVEL;                              \
34        break;                                           \
35     }
36 #define compatibility2(x,y) \
37     if ( ((CL_##x|CL_##y)&compatibility_level) == 0 ) { \
38        termstate=TOPLEVEL;                              \
39        break;                                           \
40     }
41
42 #define has_compat(x) ( ((CL_##x)&compatibility_level) != 0 )
43
44 static int compatibility_level = TM_PUTTY;
45
46
47 static unsigned long *text;            /* buffer of text on terminal screen */
48 static unsigned long *scrtop;          /* top of working screen */
49 static unsigned long *disptop;         /* top of displayed screen */
50 static unsigned long *sbtop;           /* top of scrollback */
51 static unsigned long *sbbot;           /* furthest extent of scrollback */
52 static unsigned long *cpos;            /* cursor position (convenience) */
53 static unsigned long *disptext;        /* buffer of text on real screen */
54 static unsigned long *wanttext;        /* buffer of text we want on screen */
55 static unsigned long *alttext;         /* buffer of text on alt. screen */
56
57 static unsigned char *selspace;        /* buffer for building selections in */
58
59 #define TSIZE (sizeof(*text))
60 #define fix_cpos  do { cpos = scrtop + curs_y * (cols+1) + curs_x; } while(0)
61
62 static unsigned long curr_attr, save_attr;
63 static unsigned long erase_char = ERASE_CHAR;
64
65 static int curs_x, curs_y;             /* cursor */
66 static int save_x, save_y;             /* saved cursor position */
67 static int marg_t, marg_b;             /* scroll margins */
68 static int dec_om;                     /* DEC origin mode flag */
69 static int wrap, wrapnext;             /* wrap flags */
70 static int insert;                     /* insert-mode flag */
71 static int cset;                       /* 0 or 1: which char set */
72 static int save_cset, save_csattr;     /* saved with cursor position */
73 static int rvideo;                     /* global reverse video flag */
74 static int cursor_on;                  /* cursor enabled flag */
75 static int reset_132;                  /* Flag ESC c resets to 80 cols */
76 static int use_bce;                    /* Use Background coloured erase */
77 static int blinker;                    /* When blinking is the cursor on ? */
78 static int tblinker;                   /* When the blinking text is on */
79 static int blink_is_real;              /* Actually blink blinking text */
80
81 static unsigned long cset_attr[2];
82
83 /*
84  * Saved settings on the alternate screen.
85  */
86 static int alt_x, alt_y, alt_om, alt_wrap, alt_wnext, alt_ins, alt_cset;
87 static int alt_t, alt_b;
88 static int alt_which;
89
90 #define ARGS_MAX 32                    /* max # of esc sequence arguments */
91 #define ARG_DEFAULT 0                  /* if an arg isn't specified */
92 #define def(a,d) ( (a) == ARG_DEFAULT ? (d) : (a) )
93 static int esc_args[ARGS_MAX];
94 static int esc_nargs;
95 static int esc_query;
96 #define ANSI(x,y)       ((x)+((y)<<8))
97 #define ANSI_QUE(x)     ANSI(x,TRUE)
98
99 #define OSC_STR_MAX 2048
100 static int osc_strlen;
101 static char osc_string[OSC_STR_MAX+1];
102 static int osc_w;
103
104 static char id_string[1024] = "\033[?6c";
105
106 static unsigned char *tabs;
107
108 static enum {
109     TOPLEVEL,
110     SEEN_ESC,
111     SEEN_CSI,
112     SEEN_OSC,
113     SEEN_OSC_W,
114
115     DO_CTRLS,
116
117     IGNORE_NEXT,
118     SET_GL, SET_GR,
119     SEEN_OSC_P,
120     OSC_STRING, OSC_MAYBE_ST,
121     SEEN_ESCHASH,
122     VT52_ESC,
123     VT52_Y1,
124     VT52_Y2
125 } termstate;
126
127 static enum {
128     NO_SELECTION, ABOUT_TO, DRAGGING, SELECTED
129 } selstate;
130 static enum {
131     SM_CHAR, SM_WORD, SM_LINE
132 } selmode;
133 static unsigned long *selstart, *selend, *selanchor;
134
135 static short wordness[256] = {
136     0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, /* 01 */
137     0,1,2,1,1,1,1,1,1,1,1,1,1,2,2,2, 2,2,2,2,2,2,2,2,2,2,1,1,1,1,1,1, /* 23 */
138     1,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2, 2,2,2,2,2,2,2,2,2,2,2,1,1,1,1,2, /* 45 */
139     1,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2, 2,2,2,2,2,2,2,2,2,2,2,1,1,1,1,1, /* 67 */
140     1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1, 1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1, /* 89 */
141     1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1, 1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1, /* AB */
142     2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2, 2,2,2,2,2,2,2,1,2,2,2,2,2,2,2,2, /* CD */
143     2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2, 2,2,2,2,2,2,2,1,2,2,2,2,2,2,2,2, /* EF */
144 };
145
146 static unsigned char sel_nl[] = SEL_NL;
147 static char * paste_buffer = 0;
148 static int paste_len, paste_pos, paste_hold;
149
150 /*
151  * Internal prototypes.
152  */
153 static void do_paint (Context, int);
154 static void erase_lots (int, int, int);
155 static void swap_screen (int);
156 static void update_sbar (void);
157 static void deselect (void);
158
159 /*
160  * Set up power-on settings for the terminal.
161  */
162 static void power_on(void) {
163     curs_x = curs_y = alt_x = alt_y = save_x = save_y = 0;
164     alt_t = marg_t = 0;
165     if (rows != -1)
166         alt_b = marg_b = rows - 1;
167     else
168         alt_b = marg_b = 0;
169     if (cols != -1) {
170         int i;
171         for (i = 0; i < cols; i++)
172             tabs[i] = (i % 8 == 0 ? TRUE : FALSE);
173     }
174     alt_om = dec_om = cfg.dec_om;
175     alt_wnext = wrapnext = alt_ins = insert = FALSE;
176     alt_wrap = wrap = cfg.wrap_mode;
177     alt_cset = cset = 0;
178     cset_attr[0] = cset_attr[1] = ATTR_ASCII;
179     rvideo = 0;
180     cursor_on = 1;
181     save_attr = curr_attr = ATTR_DEFAULT;
182     app_cursor_keys = cfg.app_cursor;
183     app_keypad_keys = cfg.app_keypad;
184     use_bce = cfg.bce;
185     blink_is_real = cfg.blinktext;
186     erase_char = ERASE_CHAR;
187     alt_which = 0;
188     {
189         int i;
190         for (i = 0; i < 256; i++)
191             wordness[i] = cfg.wordness[i];
192     }
193     if (text) {
194         swap_screen (1);
195         erase_lots (FALSE, TRUE, TRUE);
196         swap_screen (0);
197         erase_lots (FALSE, TRUE, TRUE);
198     }
199 }
200
201 /*
202  * Force a screen update.
203  */
204 void term_update(void) {
205     Context ctx;
206     ctx = get_ctx();
207     if (ctx) {
208         if ( (seen_key_event && (cfg.scroll_on_key)) ||
209              (seen_disp_event && (!cfg.scroll_on_key)) ) {
210             disptop = scrtop;
211             seen_disp_event = seen_key_event = 0;
212         }
213         do_paint (ctx, TRUE);
214         free_ctx (ctx);
215     }
216 }
217
218 /*
219  * Same as power_on(), but an external function.
220  */
221 void term_pwron(void) {
222     power_on();
223     fix_cpos;
224     disptop = scrtop;
225     deselect();
226     term_update();
227 }
228
229 /*
230  * Clear the scrollback.
231  */
232 void term_clrsb(void) {
233     disptop = sbtop = scrtop;
234     update_sbar();
235 }
236
237 /*
238  * Initialise the terminal.
239  */
240 void term_init(void) {
241     text = sbtop = sbbot = scrtop = disptop = cpos = NULL;
242     disptext = wanttext = NULL;
243     tabs = NULL;
244     selspace = NULL;
245     deselect();
246     rows = cols = -1;
247     power_on();
248 }
249
250 /*
251  * Set up the terminal for a given size.
252  */
253 void term_size(int newrows, int newcols, int newsavelines) {
254     unsigned long *newtext, *newdisp, *newwant, *newalt;
255     int i, j, crows, ccols;
256
257     int save_alt_which = alt_which;
258
259     if (newrows == rows && newcols == cols && newsavelines == savelines)
260         return;                        /* nothing to do */
261
262     deselect();
263     swap_screen(0);
264
265     alt_t = marg_t = 0;
266     alt_b = marg_b = newrows - 1;
267
268     newtext = smalloc ((newrows+newsavelines)*(newcols+1)*TSIZE);
269     sbbot = newtext + newsavelines*(newcols+1);
270     for (i=0; i<(newrows+newsavelines)*(newcols+1); i++)
271         newtext[i] = erase_char;
272     if (rows != -1) {
273         crows = rows + (scrtop - sbtop) / (cols+1);
274         if (crows > newrows+newsavelines)
275             crows = newrows+newsavelines;
276         if (newrows>crows)
277             disptop = newtext;
278         else
279             disptop = newtext + (crows-newrows)*(newcols+1);
280         ccols = (cols < newcols ? cols : newcols);
281         for (i=0; i<crows; i++) {
282             int oldidx = (rows - crows + i) * (cols+1);
283             int newidx = (newrows - crows + i) * (newcols+1);
284
285             for (j=0; j<ccols; j++)
286                 disptop[newidx+j] = scrtop[oldidx+j];
287             disptop[newidx+newcols] =
288                 (cols == newcols ? scrtop[oldidx+cols] 
289                                  : (scrtop[oldidx+cols]&LATTR_MODE));
290         }
291         sbtop = newtext;
292     } else {
293         sbtop = disptop = newtext;
294     }
295     scrtop = disptop;
296     sfree (text);
297     text = newtext;
298
299     newdisp = smalloc (newrows*(newcols+1)*TSIZE);
300     for (i=0; i<newrows*(newcols+1); i++)
301         newdisp[i] = ATTR_INVALID;
302     sfree (disptext);
303     disptext = newdisp;
304
305     newwant = smalloc (newrows*(newcols+1)*TSIZE);
306     for (i=0; i<newrows*(newcols+1); i++)
307         newwant[i] = ATTR_INVALID;
308     sfree (wanttext);
309     wanttext = newwant;
310
311     newalt = smalloc (newrows*(newcols+1)*TSIZE);
312     for (i=0; i<newrows*(newcols+1); i++)
313         newalt[i] = erase_char;
314     sfree (alttext);
315     alttext = newalt;
316
317     sfree (selspace);
318     selspace = smalloc ( (newrows+newsavelines) * (newcols+sizeof(sel_nl)) );
319
320     tabs = srealloc (tabs, newcols*sizeof(*tabs));
321     {
322         int i;
323         for (i = (cols > 0 ? cols : 0); i < newcols; i++)
324             tabs[i] = (i % 8 == 0 ? TRUE : FALSE);
325     }
326
327     if (rows > 0)
328         curs_y += newrows - rows;
329     if (curs_y < 0)
330         curs_y = 0;
331     if (curs_y >= newrows)
332         curs_y = newrows-1;
333     if (curs_x >= newcols)
334         curs_x = newcols-1;
335     alt_x = alt_y = 0;
336     wrapnext = alt_wnext = FALSE;
337
338     rows = newrows;
339     cols = newcols;
340     savelines = newsavelines;
341     fix_cpos;
342
343     swap_screen(save_alt_which);
344
345     update_sbar();
346     term_update();
347 }
348
349 /*
350  * Swap screens.
351  */
352 static void swap_screen (int which) {
353     int t;
354     unsigned long tt;
355
356     if (which == alt_which)
357         return;
358
359     alt_which = which;
360
361     for (t=0; t<rows*(cols+1); t++) {
362         tt = scrtop[t]; scrtop[t] = alttext[t]; alttext[t] = tt;
363     }
364
365     t = curs_x; curs_x = alt_x; alt_x = t;
366     t = curs_y; curs_y = alt_y; alt_y = t;
367     t = marg_t; marg_t = alt_t; alt_t = t;
368     t = marg_b; marg_b = alt_b; alt_b = t;
369     t = dec_om; dec_om = alt_om; alt_om = t;
370     t = wrap; wrap = alt_wrap; alt_wrap = t;
371     t = wrapnext; wrapnext = alt_wnext; alt_wnext = t;
372     t = insert; insert = alt_ins; alt_ins = t;
373     t = cset; cset = alt_cset; alt_cset = t;
374
375     fix_cpos;
376 }
377
378 /*
379  * Update the scroll bar.
380  */
381 static void update_sbar(void) {
382     int min;
383
384     min = (sbtop - text) / (cols+1);
385     set_sbar ((scrtop - text) / (cols+1) + rows - min,
386               (disptop - text) / (cols+1) - min,
387               rows);
388 }
389
390 /*
391  * Check whether the region bounded by the two pointers intersects
392  * the scroll region, and de-select the on-screen selection if so.
393  */
394 static void check_selection (unsigned long *from, unsigned long *to) {
395     if (from < selend && selstart < to)
396         deselect();
397 }
398
399 /*
400  * Scroll the screen. (`lines' is +ve for scrolling forward, -ve
401  * for backward.) `sb' is TRUE if the scrolling is permitted to
402  * affect the scrollback buffer.
403  */
404 static void scroll (int topline, int botline, int lines, int sb) {
405     unsigned long *scroll_top;
406     unsigned long *newscr;
407     int scroll_size, size, i;
408     int scrtop_is_disptop = (scrtop==disptop);
409 static int recursive = 0;
410
411     /* Only scroll more than the window if we're doing a 10% scroll */
412     if (!recursive && lines > botline - topline + 1)
413         lines = botline - topline + 1;
414
415     scroll_top = scrtop + topline*(cols+1);
416     size = (lines < 0 ? -lines : lines) * (cols+1);
417     scroll_size = (botline - topline + 1) * (cols+1) - size;
418
419     if (lines > 0 && topline == 0 && alt_which == 0 && sb) {
420         /*
421          * Since we're going to scroll the top line and we're on the 
422          * scrolling screen let's also effect the scrollback buffer.
423          *
424          * This is normally done by moving the position the screen
425          * painter reads from to reduce the amount of memory copying
426          * required.
427          */
428         if (scroll_size >= 0 && !recursive) {
429             newscr = scrtop + lines * (cols+1);
430
431             if (newscr > sbbot && botline == rows-1) {
432                 /* We've hit the bottom of memory, so we have to do a 
433                  * physical scroll. But instead of just 1 line do it
434                  * by 10% of the available memory.
435                  *
436                  * If the scroll region isn't the whole screen then we can't
437                  * do this as it stands. We would need to recover the bottom
438                  * of the screen from the scroll buffer after being sure that
439                  * it doesn't get deleted.
440                  */
441
442                 i = (rows+savelines)/10;
443
444                 /* Make it simple and ensure safe recursion */
445                 if ( i<savelines-1) {
446                     recursive ++;
447                     scroll(topline, botline, i, sb);
448                     recursive --;
449
450                     newscr = scrtop - i * (cols+1);
451                     if (scrtop_is_disptop) disptop = newscr;
452                     scrtop = newscr;
453                 }
454
455                 newscr = scrtop + lines * (cols+1);
456             }
457
458             if (newscr <= sbbot) {
459                 if (scrtop_is_disptop) disptop = newscr;
460                 scrtop = newscr;
461
462                 if (botline == rows-1 )
463                     for (i = 0; i < size; i++)
464                         scrtop[i+scroll_size] = erase_char;
465
466                 update_sbar();
467                 fix_cpos;
468
469                 if (botline != rows-1) {
470                     /* This fastscroll only works for full window scrolls. 
471                      * If the caller wanted a partial one we have to reverse
472                      * scroll the bottom of the screen.
473                      */
474                     scroll(botline-lines+1, rows-1, -lines, 0);
475                 }
476                 return ;
477             }
478
479             /* If we can't scroll by memory remapping do it physically.
480              * But rather than expensivly doing the scroll buffer just
481              * scroll the screen. All it means is that sometimes we choose
482              * to not add lines from a scroll region to the scroll buffer.
483              */
484
485             if (savelines <= 400) {
486                 sbtop -= lines * (cols+1);
487                 if (sbtop < text)
488                     sbtop = text;
489                 scroll_size += scroll_top - sbtop;
490                 scroll_top = sbtop;
491     
492                 update_sbar();
493             }
494         } else { 
495             /* Ho hum, expensive scroll required. */
496
497             sbtop -= lines * (cols+1);
498             if (sbtop < text)
499                 sbtop = text;
500             scroll_size += scroll_top - sbtop;
501             scroll_top = sbtop;
502
503             update_sbar();
504         }
505     }
506
507     if (scroll_size < 0) {
508         size += scroll_size;
509         scroll_size = 0;
510     }
511
512     if (lines > 0) {
513         if (scroll_size)
514             memmove (scroll_top, scroll_top + size, scroll_size*TSIZE);
515         for (i = 0; i < size; i++)
516             scroll_top[i+scroll_size] = erase_char;
517         if (selstart > scroll_top &&
518             selstart < scroll_top + size + scroll_size) {
519             selstart -= size;
520             if (selstart < scroll_top)
521                 selstart = scroll_top;
522         }
523         if (selend > scroll_top &&
524             selend < scroll_top + size + scroll_size) {
525             selend -= size;
526             if (selend < scroll_top)
527                 selend = scroll_top;
528         }
529         if (scrtop_is_disptop)
530             disptop = scrtop;
531         else
532             if (disptop > scroll_top &&
533                 disptop < scroll_top + size + scroll_size) {
534                 disptop -= size;
535                 if (disptop < scroll_top)
536                     disptop = scroll_top;
537         }
538     } else {
539         if (scroll_size)
540             memmove (scroll_top + size, scroll_top, scroll_size*TSIZE);
541         for (i = 0; i < size; i++)
542             scroll_top[i] = erase_char;
543         if (selstart > scroll_top &&
544             selstart < scroll_top + size + scroll_size) {
545             selstart += size;
546             if (selstart > scroll_top + size + scroll_size)
547                 selstart = scroll_top + size + scroll_size;
548         }
549         if (selend > scroll_top &&
550             selend < scroll_top + size + scroll_size) {
551             selend += size;
552             if (selend > scroll_top + size + scroll_size)
553                 selend = scroll_top + size + scroll_size;
554         }
555         if (scrtop_is_disptop)
556             disptop = scrtop;
557         else if (disptop > scroll_top &&
558                 disptop < scroll_top + size + scroll_size) {
559                 disptop += size;
560                 if (disptop > scroll_top + size + scroll_size)
561                     disptop = scroll_top + size + scroll_size;
562         }
563     }
564 }
565
566 /*
567  * Move the cursor to a given position, clipping at boundaries. We
568  * may or may not want to clip at the scroll margin: marg_clip is 0
569  * not to, 1 to disallow _passing_ the margins, and 2 to disallow
570  * even _being_ outside the margins.
571  */
572 static void move (int x, int y, int marg_clip) {
573     if (x < 0)
574         x = 0;
575     if (x >= cols)
576         x = cols-1;
577     if (marg_clip) {
578         if ((curs_y >= marg_t || marg_clip == 2) && y < marg_t)
579             y = marg_t;
580         if ((curs_y <= marg_b || marg_clip == 2) && y > marg_b)
581             y = marg_b;
582     }
583     if (y < 0)
584         y = 0;
585     if (y >= rows)
586         y = rows-1;
587     curs_x = x;
588     curs_y = y;
589     fix_cpos;
590     wrapnext = FALSE;
591 }
592
593 /*
594  * Save or restore the cursor and SGR mode.
595  */
596 static void save_cursor(int save) {
597     if (save) {
598         save_x = curs_x;
599         save_y = curs_y;
600         save_attr = curr_attr;
601         save_cset = cset;
602         save_csattr = cset_attr[cset];
603     } else {
604         curs_x = save_x;
605         curs_y = save_y;
606         /* Make sure the window hasn't shrunk since the save */
607         if (curs_x >= cols) curs_x = cols-1;
608         if (curs_y >= rows) curs_y = rows-1;
609
610         curr_attr = save_attr;
611         cset = save_cset;
612         cset_attr[cset] = save_csattr;
613         fix_cpos;
614         if (use_bce) erase_char = (' ' |(curr_attr&(ATTR_FGMASK|ATTR_BGMASK)));
615     }
616 }
617
618 /*
619  * Erase a large portion of the screen: the whole screen, or the
620  * whole line, or parts thereof.
621  */
622 static void erase_lots (int line_only, int from_begin, int to_end) {
623     unsigned long *startpos, *endpos;
624
625     if (line_only) {
626         startpos = cpos - curs_x;
627         endpos = startpos + cols;
628         /* I've removed the +1 so that the Wide screen stuff is not
629          * removed when it shouldn't be.
630          */
631     } else {
632         startpos = scrtop;
633         endpos = startpos + rows * (cols+1);
634     }
635     if (!from_begin)
636         startpos = cpos;
637     if (!to_end)
638         endpos = cpos+1;
639     check_selection (startpos, endpos);
640
641     /* Clear screen also forces a full window redraw, just in case. */
642     if (startpos == scrtop && endpos == scrtop + rows * (cols+1))
643        term_invalidate();
644
645     while (startpos < endpos)
646         *startpos++ = erase_char;
647 }
648
649 /*
650  * Insert or delete characters within the current line. n is +ve if
651  * insertion is desired, and -ve for deletion.
652  */
653 static void insch (int n) {
654     int dir = (n < 0 ? -1 : +1);
655     int m;
656
657     n = (n < 0 ? -n : n);
658     if (n > cols - curs_x)
659         n = cols - curs_x;
660     m = cols - curs_x - n;
661     check_selection (cpos, cpos+n);
662     if (dir < 0) {
663         memmove (cpos, cpos+n, m*TSIZE);
664         while (n--)
665             cpos[m++] = erase_char;
666     } else {
667         memmove (cpos+n, cpos, m*TSIZE);
668         while (n--)
669             cpos[n] = erase_char;
670     }
671 }
672
673 /*
674  * Toggle terminal mode `mode' to state `state'. (`query' indicates
675  * whether the mode is a DEC private one or a normal one.)
676  */
677 static void toggle_mode (int mode, int query, int state) {
678     if (query) switch (mode) {
679       case 1:                          /* application cursor keys */
680         app_cursor_keys = state;
681         break;
682       case 2:                          /* VT52 mode */
683         vt52_mode = !state;
684         break;
685       case 3:                          /* 80/132 columns */
686         deselect();
687         request_resize (state ? 132 : 80, rows, 1);
688         reset_132 = state;
689         break;
690       case 5:                          /* reverse video */
691         rvideo = state;
692         seen_disp_event = TRUE;
693         if (state) term_update();
694         break;
695       case 6:                          /* DEC origin mode */
696         dec_om = state;
697         break;
698       case 7:                          /* auto wrap */
699         wrap = state;
700         break;
701       case 8:                          /* auto key repeat */
702         repeat_off = !state;
703         break;
704       case 25:                         /* enable/disable cursor */
705         compatibility(VT220);
706         cursor_on = state;
707         seen_disp_event = TRUE;
708         break;
709       case 47:                         /* alternate screen */
710         compatibility(OTHER);
711         deselect();
712         swap_screen (state);
713         disptop = scrtop;
714         break;
715     } else switch (mode) {
716       case 4:                          /* set insert mode */
717         compatibility(VT102);
718         insert = state;
719         break;
720       case 12:                         /* set echo mode */
721         /* 
722          * This may be very good in smcup and rmcup (or smkx & rmkx) if you
723          * have a long RTT and the telnet client/daemon doesn't understand
724          * linemode.
725          *
726          * DONT send TS_RECHO/TS_LECHO; the telnet daemon tries to fix the
727          * tty and _really_ confuses some programs.
728          */
729         compatibility(VT220);
730         ldisc = (state? &ldisc_simple : &ldisc_term);
731         break;
732       case 20:                         /* Return sends ... */
733         cr_lf_return = state;
734         break;
735     }
736 }
737
738 /*
739  * Process an OSC sequence: set window title or icon name.
740  */
741 static void do_osc(void) {
742     if (osc_w) {
743         while (osc_strlen--)
744             wordness[(unsigned char)osc_string[osc_strlen]] = esc_args[0];
745     } else {
746         osc_string[osc_strlen] = '\0';
747         switch (esc_args[0]) {
748           case 0:
749           case 1:
750             set_icon (osc_string);
751             if (esc_args[0] == 1)
752                 break;
753             /* fall through: parameter 0 means set both */
754           case 2:
755           case 21:
756             set_title (osc_string);
757             break;
758         }
759     }
760 }
761
762 /*
763  * Remove everything currently in `inbuf' and stick it up on the
764  * in-memory display. There's a big state machine in here to
765  * process escape sequences...
766  */
767 void term_out(void) {
768     int c, inbuf_reap;
769
770 static int beep_overload = 0;
771     int beep_count = 0;
772
773     for(inbuf_reap = 0; inbuf_reap < inbuf_head; inbuf_reap++)
774     {
775         c = inbuf[inbuf_reap];
776
777         /*
778          * Optionally log the session traffic to a file. Useful for
779          * debugging and possibly also useful for actual logging.
780          */
781         if (logfile) {
782             static FILE *fp = NULL;
783             if (!fp) fp = fopen(logfile, "wb");
784             if (fp) fputc (c, fp);
785         }
786         /* Note only VT220+ are 8-bit VT102 is seven bit, it shouldn't even
787          * be able to display 8-bit characters, but I'll let that go 'cause
788          * of i18n.
789          */
790         if( ( (c&0x60) == 0 || c == '\177') && 
791              termstate < DO_CTRLS &&
792             ( (c&0x80) == 0 || has_compat(VT220))) {
793             switch (c) {
794               case '\005':             /* terminal type query */
795                 /* Strictly speaking this is VT100 but a VT100 defaults to
796                  * no response. Other terminals respond at their option.
797                  *
798                  * Don't put a CR in the default string as this tends to
799                  * upset some weird software.
800                  *
801                  * An xterm returns "xterm" (5 characters)
802                  */
803                 compatibility(OTHER);
804                 ldisc->send ("PuTTY", 5);
805                 break;
806               case '\007':
807                 beep_count++; 
808                 if(beep_count>6) beep_overload=1;
809                 disptop = scrtop;
810                 break;
811               case '\b':
812                 if (curs_x == 0 && curs_y == 0)
813                     ;
814                 else if (curs_x == 0 && curs_y > 0)
815                     curs_x = cols-1, curs_y--;
816                 else if (wrapnext)
817                     wrapnext = FALSE;
818                 else
819                     curs_x--;
820                 fix_cpos;
821                 seen_disp_event = TRUE;
822                 break;
823               case '\016':
824                 compatibility(VT100);
825                 cset = 1;
826                 break;
827               case '\017':
828                 compatibility(VT100);
829                 cset = 0;
830                 break;
831               case '\033':
832                 if (vt52_mode) 
833                    termstate = VT52_ESC;
834                 else {
835                     compatibility(ANSIMIN);
836                     termstate = SEEN_ESC;
837                 }
838                 break;
839               case 0233:
840                 compatibility(VT220);
841                 termstate = SEEN_CSI;
842                 esc_nargs = 1;
843                 esc_args[0] = ARG_DEFAULT;
844                 esc_query = FALSE;
845                 break;
846               case 0235:
847                 compatibility(VT220);
848                 termstate = SEEN_OSC;
849                 esc_args[0] = 0;
850                 break;
851               case '\r':
852                 curs_x = 0;
853                 wrapnext = FALSE;
854                 fix_cpos;
855                 seen_disp_event = TRUE;
856                 paste_hold = 0;
857                 break;
858               case '\013':
859               case '\014':
860                 compatibility(VT100);
861               case '\n':
862                 if (curs_y == marg_b)
863                     scroll (marg_t, marg_b, 1, TRUE);
864                 else if (curs_y < rows-1)
865                     curs_y++;
866                 if (cfg.lfhascr)
867                     curs_x = 0;
868                 fix_cpos;
869                 wrapnext = FALSE;
870                 seen_disp_event = 1;
871                 paste_hold = 0;
872                 break;
873               case '\t':
874                 {
875                     unsigned long *old_cpos = cpos;
876                     unsigned long *p = scrtop + curs_y * (cols+1) + cols;
877
878                     do {
879                         curs_x++;
880                     } while (curs_x < cols-1 && !tabs[curs_x]);
881
882                     if ((*p & LATTR_MODE) != LATTR_NORM)
883                     {
884                         if (curs_x >= cols/2)
885                             curs_x = cols/2-1;
886                     }
887                     else
888                     {
889                         if (curs_x >= cols)
890                             curs_x = cols-1;
891                     }
892
893                     fix_cpos;
894                     check_selection (old_cpos, cpos);
895                 }
896                 seen_disp_event = TRUE;
897                 break;
898             }
899         }
900         else switch (termstate) {
901           case TOPLEVEL:
902           /* Only graphic characters get this far, ctrls are stripped above */
903             if (wrapnext) {
904                 cpos[1] |= ATTR_WRAPPED;
905                 if (curs_y == marg_b)
906                     scroll (marg_t, marg_b, 1, TRUE);
907                 else if (curs_y < rows-1)
908                     curs_y++;
909                 curs_x = 0;
910                 fix_cpos;
911                 wrapnext = FALSE;
912             }
913             if (insert)
914                 insch (1);
915             if (selstate != NO_SELECTION)
916                 check_selection (cpos, cpos+1);
917             switch (cset_attr[cset]) {
918                 /* Linedraw characters are different from 'ESC ( B' only 
919                  * for a small range, for ones outside that range make sure 
920                  * we use the same font as well as the same encoding.
921                  */
922             case ATTR_LINEDRW:
923                 if (c<0x60 || c>0x7F)
924                     *cpos++ = xlat_tty2scr((unsigned char)c) | curr_attr |
925                               ATTR_ASCII;
926                 else
927                     *cpos++ = ((unsigned char)c) | curr_attr | ATTR_LINEDRW;
928                 break;
929             default:
930                 *cpos++ = xlat_tty2scr((unsigned char)c) | curr_attr |
931                     (c <= 0x7F ? cset_attr[cset] : ATTR_ASCII);
932                 break;
933             }
934             curs_x++;
935             if (curs_x == cols) {
936                 cpos--;
937                 curs_x--;
938                 wrapnext = wrap;
939             }
940             seen_disp_event = 1;
941             break;
942
943           case IGNORE_NEXT:
944             termstate = TOPLEVEL;
945             break;
946           case OSC_MAYBE_ST:
947             /*
948              * This state is virtually identical to SEEN_ESC, with the
949              * exception that we have an OSC sequence in the pipeline,
950              * and _if_ we see a backslash, we process it.
951              */
952             if (c == '\\') {
953                 do_osc();
954                 termstate = TOPLEVEL;
955                 break;
956             }
957             /* else fall through */
958           case SEEN_ESC:
959             termstate = TOPLEVEL;
960             switch (c) {
961               case ' ':                /* some weird sequence? */
962                 compatibility(VT220);
963                 termstate = IGNORE_NEXT;
964                 break;
965               case '[':                /* enter CSI mode */
966                 termstate = SEEN_CSI;
967                 esc_nargs = 1;
968                 esc_args[0] = ARG_DEFAULT;
969                 esc_query = FALSE;
970                 break;
971               case ']':                /* xterm escape sequences */
972                 /* Compatibility is nasty here, xterm, linux, decterm yuk! */
973                 compatibility(OTHER);
974                 termstate = SEEN_OSC;
975                 esc_args[0] = 0;
976                 break;
977               case '(':                /* should set GL */
978                 compatibility(VT100);
979                 termstate = SET_GL;
980                 break;
981               case ')':                /* should set GR */
982                 compatibility(VT100);
983                 termstate = SET_GR;
984                 break;
985               case '7':                /* save cursor */
986                 compatibility(VT100);
987                 save_cursor (TRUE);
988                 break;
989               case '8':                /* restore cursor */
990                 compatibility(VT100);
991                 save_cursor (FALSE);
992                 seen_disp_event = TRUE;
993                 break;
994               case '=':
995                 compatibility(VT100);
996                 app_keypad_keys = TRUE;
997                 break;
998               case '>':
999                 compatibility(VT100);
1000                 app_keypad_keys = FALSE;
1001                 break;
1002               case 'D':                /* exactly equivalent to LF */
1003                 compatibility(VT100);
1004                 if (curs_y == marg_b)
1005                     scroll (marg_t, marg_b, 1, TRUE);
1006                 else if (curs_y < rows-1)
1007                     curs_y++;
1008                 fix_cpos;
1009                 wrapnext = FALSE;
1010                 seen_disp_event = TRUE;
1011                 break;
1012               case 'E':                /* exactly equivalent to CR-LF */
1013                 compatibility(VT100);
1014                 curs_x = 0;
1015                 if (curs_y == marg_b)
1016                     scroll (marg_t, marg_b, 1, TRUE);
1017                 else if (curs_y < rows-1)
1018                     curs_y++;
1019                 fix_cpos;
1020                 wrapnext = FALSE;
1021                 seen_disp_event = TRUE;
1022                 break;
1023               case 'M':                /* reverse index - backwards LF */
1024                 compatibility(VT100);
1025                 if (curs_y == marg_t)
1026                     scroll (marg_t, marg_b, -1, TRUE);
1027                 else if (curs_y > 0)
1028                     curs_y--;
1029                 fix_cpos;
1030                 wrapnext = FALSE;
1031                 seen_disp_event = TRUE;
1032                 break;
1033               case 'Z':                /* terminal type query */
1034                 compatibility(VT100);
1035                 ldisc->send (id_string, strlen(id_string));
1036                 break;
1037               case 'c':                /* restore power-on settings */
1038                 compatibility(VT100);
1039                 power_on();
1040                 if (reset_132) {
1041                     request_resize (80, rows, 1);
1042                     reset_132 = 0;
1043                 }
1044                 fix_cpos;
1045                 disptop = scrtop;
1046                 seen_disp_event = TRUE;
1047                 break;
1048               case '#':                /* ESC # 8 fills screen with Es :-) */
1049                 compatibility(VT100);
1050                 termstate = SEEN_ESCHASH;
1051                 break;
1052               case 'H':                /* set a tab */
1053                 compatibility(VT100);
1054                 tabs[curs_x] = TRUE;
1055                 break;
1056             }
1057             break;
1058           case SEEN_CSI:
1059             termstate = TOPLEVEL;      /* default */
1060             if( isdigit(c) )
1061             {
1062                 if (esc_nargs <= ARGS_MAX) {
1063                     if (esc_args[esc_nargs-1] == ARG_DEFAULT)
1064                         esc_args[esc_nargs-1] = 0;
1065                     esc_args[esc_nargs-1] =
1066                         10 * esc_args[esc_nargs-1] + c - '0';
1067                 }
1068                 termstate = SEEN_CSI;
1069             }
1070             else if( c == ';' )
1071             {
1072                 if (++esc_nargs <= ARGS_MAX)
1073                     esc_args[esc_nargs-1] = ARG_DEFAULT;
1074                 termstate = SEEN_CSI;
1075             }
1076             else if( c < '@' )
1077             {
1078                 if( esc_query )     esc_query = -1;
1079                 else if( c == '?' ) esc_query = TRUE;
1080                 else                esc_query = c;
1081                 termstate = SEEN_CSI;
1082             }
1083             else switch (ANSI(c,esc_query)) {
1084               case 'A':                /* move up N lines */
1085                 move (curs_x, curs_y - def(esc_args[0], 1), 1);
1086                 seen_disp_event = TRUE;
1087                 break;
1088               case 'e':      /* move down N lines */
1089                 compatibility(ANSI);
1090               case 'B':
1091                 move (curs_x, curs_y + def(esc_args[0], 1), 1);
1092                 seen_disp_event = TRUE;
1093                 break;
1094               case 'a':      /* move right N cols */
1095                 compatibility(ANSI);
1096               case 'C':
1097                 move (curs_x + def(esc_args[0], 1), curs_y, 1);
1098                 seen_disp_event = TRUE;
1099                 break;
1100               case 'D':                /* move left N cols */
1101                 move (curs_x - def(esc_args[0], 1), curs_y, 1);
1102                 seen_disp_event = TRUE;
1103                 break;
1104               case 'E':                /* move down N lines and CR */
1105                 compatibility(ANSI);
1106                 move (0, curs_y + def(esc_args[0], 1), 1);
1107                 seen_disp_event = TRUE;
1108                 break;
1109               case 'F':                /* move up N lines and CR */
1110                 compatibility(ANSI);
1111                 move (0, curs_y - def(esc_args[0], 1), 1);
1112                 seen_disp_event = TRUE;
1113                 break;
1114               case 'G': case '`':      /* set horizontal posn */
1115                 compatibility(ANSI);
1116                 move (def(esc_args[0], 1) - 1, curs_y, 0);
1117                 seen_disp_event = TRUE;
1118                 break;
1119               case 'd':                /* set vertical posn */
1120                 compatibility(ANSI);
1121                 move (curs_x, (dec_om ? marg_t : 0) + def(esc_args[0], 1) - 1,
1122                       (dec_om ? 2 : 0));
1123                 seen_disp_event = TRUE;
1124                 break;
1125               case 'H': case 'f':      /* set horz and vert posns at once */
1126                 if (esc_nargs < 2)
1127                     esc_args[1] = ARG_DEFAULT;
1128                 move (def(esc_args[1], 1) - 1,
1129                       (dec_om ? marg_t : 0) + def(esc_args[0], 1) - 1,
1130                       (dec_om ? 2 : 0));
1131                 seen_disp_event = TRUE;
1132                 break;
1133               case 'J':                /* erase screen or parts of it */
1134                 {
1135                     unsigned int i = def(esc_args[0], 0) + 1;
1136                     if (i > 3)
1137                         i = 0;
1138                     erase_lots(FALSE, !!(i & 2), !!(i & 1));
1139                 }
1140                 disptop = scrtop;
1141                 seen_disp_event = TRUE;
1142                 break;
1143               case 'K':                /* erase line or parts of it */
1144                 {
1145                     unsigned int i = def(esc_args[0], 0) + 1;
1146                     if (i > 3)
1147                         i = 0;
1148                     erase_lots(TRUE, !!(i & 2), !!(i & 1));
1149                 }
1150                 seen_disp_event = TRUE;
1151                 break;
1152               case 'L':                /* insert lines */
1153                 compatibility(VT102);
1154                 if (curs_y <= marg_b)
1155                     scroll (curs_y, marg_b, -def(esc_args[0], 1), FALSE);
1156                 seen_disp_event = TRUE;
1157                 break;
1158               case 'M':                /* delete lines */
1159                 compatibility(VT102);
1160                 if (curs_y <= marg_b)
1161                     scroll (curs_y, marg_b, def(esc_args[0], 1), TRUE);
1162                 seen_disp_event = TRUE;
1163                 break;
1164               case '@':                /* insert chars */
1165                 /* XXX VTTEST says this is vt220, vt510 manual says vt102 */
1166                 compatibility(VT102);   
1167                 insch (def(esc_args[0], 1));
1168                 seen_disp_event = TRUE;
1169                 break;
1170               case 'P':                /* delete chars */
1171                 compatibility(VT102);   
1172                 insch (-def(esc_args[0], 1));
1173                 seen_disp_event = TRUE;
1174                 break;
1175               case 'c':                /* terminal type query */
1176                 compatibility(VT100);
1177                 /* This is the response for a VT102 */
1178                 ldisc->send (id_string, strlen(id_string));
1179                 break;
1180               case 'n':                /* cursor position query */
1181                 if (esc_args[0] == 6) {
1182                     char buf[32];
1183                     sprintf (buf, "\033[%d;%dR", curs_y + 1, curs_x + 1);
1184                     ldisc->send (buf, strlen(buf));
1185                 }
1186                 else if (esc_args[0] == 5) {
1187                     ldisc->send ("\033[0n", 4);
1188                 }
1189                 break;
1190               case 'h':                /* toggle modes to high */
1191               case ANSI_QUE('h'):
1192                 compatibility(VT100);
1193                 {
1194                     int i;
1195                     for (i=0; i<esc_nargs; i++)
1196                         toggle_mode (esc_args[i], esc_query, TRUE);
1197                 }
1198                 break;
1199               case 'l':                /* toggle modes to low */
1200               case ANSI_QUE('l'):
1201                 compatibility(VT100);
1202                 {
1203                     int i;
1204                     for (i=0; i<esc_nargs; i++)
1205                         toggle_mode (esc_args[i], esc_query, FALSE);
1206                 }
1207                 break;
1208               case 'g':                /* clear tabs */
1209                 compatibility(VT100);
1210                 if (esc_nargs == 1) {
1211                     if (esc_args[0] == 0) {
1212                         tabs[curs_x] = FALSE;
1213                     } else if (esc_args[0] == 3) {
1214                         int i;
1215                         for (i = 0; i < cols; i++)
1216                             tabs[i] = FALSE;
1217                     }
1218                 }
1219                 break;
1220               case 'r':                /* set scroll margins */
1221                 compatibility(VT100);
1222                 if (esc_nargs <= 2) {
1223                     int top, bot;
1224                     top = def(esc_args[0], 1) - 1;
1225                     bot = (esc_nargs <= 1 || esc_args[1] == 0 ? rows :
1226                            def(esc_args[1], rows)) - 1;
1227                     if (bot >= rows)
1228                         bot = rows-1;
1229                     /* VTTEST Bug 9 - if region is less than 2 lines
1230                      * don't change region.
1231                      */
1232                     if (bot-top > 1) {
1233                         marg_t = top;
1234                         marg_b = bot;
1235                         curs_x = 0;
1236                         /*
1237                          * I used to think the cursor should be
1238                          * placed at the top of the newly marginned
1239                          * area. Apparently not: VMS TPU falls over
1240                          * if so.
1241                          *
1242                          * Well actually it should for Origin mode - RDB
1243                          */
1244                         curs_y = (dec_om ? marg_t : 0);
1245                         fix_cpos;
1246                         seen_disp_event = TRUE;
1247                     }
1248                 }
1249                 break;
1250               case 'm':                /* set graphics rendition */
1251                 {
1252                     /* 
1253                      * A VT100 without the AVO only had one attribute, either
1254                      * underline or reverse video depending on the cursor type,
1255                      * this was selected by CSI 7m.
1256                      *
1257                      * case 2:
1258                      *  This is DIM on the VT100-AVO and VT102
1259                      * case 5:
1260                      *  This is BLINK on the VT100-AVO and VT102+
1261                      * case 8:
1262                      *  This is INVIS on the VT100-AVO and VT102
1263                      * case 21:
1264                      *  This like 22 disables BOLD, DIM and INVIS
1265                      *
1266                      * The ANSI colours appear on any terminal that has colour
1267                      * (obviously) but the interaction between sgr0 and the
1268                      * colours varies but is usually related to the background
1269                      * colour erase item.
1270                      * The interaction between colour attributes and the mono
1271                      * ones is also very implementation dependent.
1272                      *
1273                      * The 39 and 49 attributes are likely to be unimplemented.
1274                      */
1275                     int i;
1276                     for (i=0; i<esc_nargs; i++) {
1277                         switch (def(esc_args[i], 0)) {
1278                           case 0:      /* restore defaults */
1279                             curr_attr = ATTR_DEFAULT; break;
1280                           case 1:      /* enable bold */
1281                             compatibility(VT100AVO);
1282                             curr_attr |= ATTR_BOLD; break;
1283                           case 21:     /* (enable double underline) */
1284                             compatibility(OTHER);
1285                           case 4:      /* enable underline */
1286                             compatibility(VT100AVO);
1287                             curr_attr |= ATTR_UNDER; break;
1288                           case 5:      /* enable blink */
1289                             compatibility(VT100AVO);
1290                             curr_attr |= ATTR_BLINK; break;
1291                           case 7:      /* enable reverse video */
1292                             curr_attr |= ATTR_REVERSE; break;
1293                           case 22:     /* disable bold */
1294                             compatibility(VT220);
1295                             curr_attr &= ~ATTR_BOLD; break;
1296                           case 24:     /* disable underline */
1297                             compatibility(VT220);
1298                             curr_attr &= ~ATTR_UNDER; break;
1299                           case 25:     /* disable blink */
1300                             compatibility(VT220);
1301                             curr_attr &= ~ATTR_BLINK; break;
1302                           case 27:     /* disable reverse video */
1303                             compatibility(VT220);
1304                             curr_attr &= ~ATTR_REVERSE; break;
1305                           case 30: case 31: case 32: case 33:
1306                           case 34: case 35: case 36: case 37:
1307                             /* foreground */
1308                             curr_attr &= ~ATTR_FGMASK;
1309                             curr_attr |= (esc_args[i] - 30) << ATTR_FGSHIFT;
1310                             break;
1311                           case 39:     /* default-foreground */
1312                             curr_attr &= ~ATTR_FGMASK;
1313                             curr_attr |= ATTR_DEFFG;
1314                             break;
1315                           case 40: case 41: case 42: case 43:
1316                           case 44: case 45: case 46: case 47:
1317                             /* background */
1318                             curr_attr &= ~ATTR_BGMASK;
1319                             curr_attr |= (esc_args[i] - 40) << ATTR_BGSHIFT;
1320                             break;
1321                           case 49:     /* default-background */
1322                             curr_attr &= ~ATTR_BGMASK;
1323                             curr_attr |= ATTR_DEFBG;
1324                             break;
1325                         }
1326                     }
1327                     if (use_bce) 
1328                        erase_char = 
1329                             (' '|
1330                               (curr_attr&(ATTR_FGMASK|ATTR_BGMASK|ATTR_BLINK))
1331                             );
1332                 }
1333                 break;
1334               case 's':                /* save cursor */
1335                 save_cursor (TRUE);
1336                 break;
1337               case 'u':                /* restore cursor */
1338                 save_cursor (FALSE);
1339                 seen_disp_event = TRUE;
1340                 break;
1341               case 't':                /* set page size - ie window height */
1342                 /*
1343                  * VT340/VT420 sequence DECSLPP, DEC only allows values
1344                  *  24/25/36/48/72/144 other emulators (eg dtterm) use
1345                  * illegal values (eg first arg 1..9) for window changing 
1346                  * and reports.
1347                  */
1348                 compatibility(VT340TEXT);
1349                 if (esc_nargs<=1 && (esc_args[0]<1 || esc_args[0]>=24)) {
1350                     request_resize (cols, def(esc_args[0], 24), 0);
1351                     deselect();
1352                 }
1353                 break;
1354               case ANSI('|', '*'):
1355                 /* VT420 sequence DECSNLS
1356                  * Set number of lines on screen
1357                  * VT420 uses VGA like hardware and can support any size in
1358                  * reasonable range (24..49 AIUI) with no default specified.
1359                  */
1360                 compatibility(VT420);
1361                 if (esc_nargs==1 && esc_args[0]>0) {
1362                     request_resize (cols, def(esc_args[0], cfg.height), 0);
1363                     deselect();
1364                 }
1365                 break;
1366               case ANSI('|', '$'):
1367                 /* VT340/VT420 sequence DECSCPP
1368                  * Set number of columns per page
1369                  * Docs imply range is only 80 or 132, but I'll allow any.
1370                  */
1371                 compatibility(VT340TEXT);
1372                 if (esc_nargs<=1) {
1373                     request_resize (def(esc_args[0], cfg.width), rows, 0);
1374                     deselect();
1375                 }
1376                 break;
1377               case 'X':                /* write N spaces w/o moving cursor */
1378                 /* XXX VTTEST says this is vt220, vt510 manual says vt100 */
1379                 compatibility(ANSIMIN);
1380                 {
1381                     int n = def(esc_args[0], 1);
1382                     unsigned long *p = cpos;
1383                     if (n > cols - curs_x)
1384                         n = cols - curs_x;
1385                     check_selection (cpos, cpos+n);
1386                     while (n--)
1387                         *p++ = erase_char;
1388                     seen_disp_event = TRUE;
1389                 }
1390                 break;
1391               case 'x':                /* report terminal characteristics */
1392                 compatibility(VT100);
1393                 {
1394                     char buf[32];
1395                     int i = def(esc_args[0], 0);
1396                     if (i == 0 || i == 1) {
1397                         strcpy (buf, "\033[2;1;1;112;112;1;0x");
1398                         buf[2] += i;
1399                         ldisc->send (buf, 20);
1400                     }
1401                 }
1402                 break;
1403               case ANSI('L','='):
1404                 compatibility(OTHER);
1405                 use_bce = (esc_args[0]<=0);
1406                 erase_char = ERASE_CHAR;
1407                 if (use_bce)
1408                     erase_char = (' '|(curr_attr&(ATTR_FGMASK|ATTR_BGMASK)));
1409                 break;
1410               case ANSI('E','='):
1411                 compatibility(OTHER);
1412                 blink_is_real = (esc_args[0]>=1);
1413                 break;
1414               case ANSI('p','"'):
1415                 /* Allow the host to make this emulator a 'perfect' VT102.
1416                  * This first appeared in the VT220, but we do need to get 
1417                  * back to PuTTY mode so I won't check it.
1418                  *
1419                  * The arg == 60 is a PuTTY extension.
1420                  * The 2nd arg, 8bit vs 7bit is not obeyed.
1421                  *
1422                  * Setting VT102 mode should also change the Fkeys to
1423                  * generate PF* codes as a real VT102 has no Fkeys.
1424                  * The VT220 does this, F11..F13 become ESC,BS,LF other Fkeys
1425                  * send nothing.
1426                  *
1427                  * Note ESC c will NOT change this!
1428                  */
1429
1430                 if (esc_args[0] == 61)      compatibility_level = TM_VT102;
1431                 else if (esc_args[0] == 60) compatibility_level = TM_ANSIMIN;
1432                 else                        compatibility_level = TM_PUTTY;
1433                 break;
1434             }
1435             break;
1436           case SET_GL:
1437           case SET_GR:
1438             /* VT100 only here, checked above */
1439             switch (c) {
1440               case 'A':
1441                 cset_attr[termstate == SET_GL ? 0 : 1] = ATTR_GBCHR;
1442                 break;
1443               case '0':
1444                 cset_attr[termstate == SET_GL ? 0 : 1] = ATTR_LINEDRW;
1445                 break;
1446               case 'B':
1447               default:                 /* specifically, 'B' */
1448                 cset_attr[termstate == SET_GL ? 0 : 1] = ATTR_ASCII;
1449                 break;
1450             }
1451             if( !has_compat(VT220) || c != '%' )
1452                 termstate = TOPLEVEL;
1453             break;
1454           case SEEN_OSC:
1455             osc_w = FALSE;
1456             switch (c) {
1457               case 'P':                /* Linux palette sequence */
1458                 termstate = SEEN_OSC_P;
1459                 osc_strlen = 0;
1460                 break;
1461               case 'R':                /* Linux palette reset */
1462                 palette_reset();
1463                 term_invalidate();
1464                 termstate = TOPLEVEL;
1465                 break;
1466               case 'W':                /* word-set */
1467                 termstate = SEEN_OSC_W;
1468                 osc_w = TRUE;
1469                 break;
1470               case '0': case '1': case '2': case '3': case '4':
1471               case '5': case '6': case '7': case '8': case '9':
1472                 esc_args[0] = 10 * esc_args[0] + c - '0';
1473                 break;
1474               case 'L':
1475                 /*
1476                  * Grotty hack to support xterm and DECterm title
1477                  * sequences concurrently.
1478                  */
1479                 if (esc_args[0] == 2) {
1480                     esc_args[0] = 1;
1481                     break;
1482                 }
1483                 /* else fall through */
1484               default:
1485                 termstate = OSC_STRING;
1486                 osc_strlen = 0;
1487             }
1488             break;
1489           case OSC_STRING:
1490             /*
1491              * This OSC stuff is EVIL. It takes just one character to get into
1492              * sysline mode and it's not initially obvious how to get out.
1493              * So I've added CR and LF as string aborts.
1494              * This shouldn't effect compatibility as I believe embedded 
1495              * control characters are supposed to be interpreted (maybe?) 
1496              * and they don't display anything useful anyway.
1497              *
1498              * -- RDB
1499              */
1500             if (c == '\n' || c == '\r') {
1501                 termstate = TOPLEVEL;
1502             } else if (c == 0234 || c == '\007' ) {
1503                 /*
1504                  * These characters terminate the string; ST and BEL
1505                  * terminate the sequence and trigger instant
1506                  * processing of it, whereas ESC goes back to SEEN_ESC
1507                  * mode unless it is followed by \, in which case it is
1508                  * synonymous with ST in the first place.
1509                  */
1510                 do_osc();
1511                 termstate = TOPLEVEL;
1512             } else if (c == '\033')
1513                     termstate = OSC_MAYBE_ST;
1514             else if (osc_strlen < OSC_STR_MAX)
1515                 osc_string[osc_strlen++] = c;
1516             break;
1517           case SEEN_OSC_P:
1518             {
1519                 int max = (osc_strlen == 0 ? 21 : 16);
1520                 int val;
1521                 if (c >= '0' && c <= '9')
1522                     val = c - '0';
1523                 else if (c >= 'A' && c <= 'A'+max-10)
1524                     val = c - 'A' + 10;
1525                 else if (c >= 'a' && c <= 'a'+max-10)
1526                     val = c - 'a' + 10;
1527                 else
1528                     termstate = TOPLEVEL;
1529                 osc_string[osc_strlen++] = val;
1530                 if (osc_strlen >= 7) {
1531                     palette_set (osc_string[0],
1532                                  osc_string[1] * 16 + osc_string[2],
1533                                  osc_string[3] * 16 + osc_string[4],
1534                                  osc_string[5] * 16 + osc_string[6]);
1535                     term_invalidate();
1536                     termstate = TOPLEVEL;
1537                 }
1538             }
1539             break;
1540           case SEEN_OSC_W:
1541             switch (c) {
1542               case '0': case '1': case '2': case '3': case '4':
1543               case '5': case '6': case '7': case '8': case '9':
1544                 esc_args[0] = 10 * esc_args[0] + c - '0';
1545                 break;
1546               default:
1547                 termstate = OSC_STRING;
1548                 osc_strlen = 0;
1549             }
1550             break;
1551           case SEEN_ESCHASH:
1552             {
1553                 unsigned long *p;
1554                 unsigned long nlattr;
1555                 int n;
1556
1557                 switch (c) {
1558                 case '8':
1559                     p = scrtop;
1560                     n = rows * (cols+1);
1561                     while (n--)
1562                         *p++ = ATTR_DEFAULT | 'E';
1563                     disptop = scrtop;
1564                     seen_disp_event = TRUE;
1565                     check_selection (scrtop, scrtop + rows * (cols+1));
1566                     break;
1567
1568                 case '3': nlattr = LATTR_TOP;     if(0) {
1569                 case '4': nlattr = LATTR_BOT;   } if(0) {
1570                 case '5': nlattr = LATTR_NORM;  } if(0) {
1571                 case '6': nlattr = LATTR_WIDE;  }
1572
1573                     p = scrtop + curs_y * (cols+1) + cols;
1574                     *p &= ~LATTR_MODE;
1575                     *p |=  nlattr;
1576                 }
1577             }
1578             termstate = TOPLEVEL;
1579             break;
1580           case VT52_ESC:
1581             termstate = TOPLEVEL;
1582             seen_disp_event = TRUE;
1583             switch (c) {
1584               case 'A':
1585                 move (curs_x, curs_y - 1, 1);
1586                 break;
1587               case 'B':
1588                 move (curs_x, curs_y + 1, 1);
1589                 break;
1590               case 'C':
1591                 move (curs_x + 1, curs_y, 1);
1592                 break;
1593               case 'D':
1594                 move (curs_x - 1, curs_y, 1);
1595                 break;
1596               case 'F':
1597                 cset_attr[cset=0] = ATTR_LINEDRW;
1598                 break;
1599               case 'G':
1600                 cset_attr[cset=0] = ATTR_ASCII;
1601                 break;
1602               case 'H':
1603                 move (0, 0, 0);
1604                 break;
1605               case 'I':
1606                 if (curs_y == 0)
1607                     scroll (0, rows-1, -1, TRUE);
1608                 else if (curs_y > 0)
1609                     curs_y--;
1610                 fix_cpos;
1611                 wrapnext = FALSE;
1612                 break;
1613               case 'J':
1614                 erase_lots(FALSE, FALSE, TRUE);
1615                 disptop = scrtop;
1616                 break;
1617               case 'K':
1618                 erase_lots(TRUE, FALSE, TRUE);
1619                 break;
1620               case 'V':
1621                 /* XXX Print cursor line */
1622                 break;
1623               case 'W':
1624                 /* XXX Start controller mode */
1625                 break;
1626               case 'X':
1627                 /* XXX Stop controller mode */
1628                 break;
1629               case 'Y':
1630                 termstate = VT52_Y1;
1631                 break;
1632               case 'Z':
1633                 ldisc->send ("\033/Z", 3);
1634                 break;
1635               case '=':
1636                 app_cursor_keys = TRUE;
1637                 break;
1638               case '>':
1639                 app_cursor_keys = FALSE;
1640                 break;
1641               case '<':
1642                 /* XXX This should switch to VT100 mode not current or default
1643                  *     VT mode. But this will only have effect in a VT220+
1644                  *     emulation.
1645                  */
1646                 vt52_mode = FALSE;
1647                 break;
1648               case '^':
1649                 /* XXX Enter auto print mode */
1650                 break;
1651               case '_':
1652                 /* XXX Exit auto print mode */
1653                 break;
1654               case ']':
1655                 /* XXX Print screen */
1656                 break;
1657             }
1658             break;
1659           case VT52_Y1:
1660             termstate = VT52_Y2;
1661             move(curs_x, c-' ', 0);
1662             break;
1663           case VT52_Y2:
1664             termstate = TOPLEVEL;
1665             move(c-' ', curs_y, 0);
1666             break;
1667         }
1668         if (selstate != NO_SELECTION)
1669             check_selection (cpos, cpos+1);
1670     }
1671     inbuf_head = 0;
1672
1673     if (beep_overload)
1674     {
1675        if(!beep_count) beep_overload=0;
1676     }
1677     else if(beep_count && beep_count<5 && cfg.beep)
1678        beep(beep_count/3);
1679 }
1680
1681 /*
1682  * Compare two lines to determine whether they are sufficiently
1683  * alike to scroll-optimise one to the other. Return the degree of
1684  * similarity.
1685  */
1686 static int linecmp (unsigned long *a, unsigned long *b) {
1687     int i, n;
1688
1689     for (i=n=0; i < cols; i++)
1690         n += (*a++ == *b++);
1691     return n;
1692 }
1693
1694 /*
1695  * Given a context, update the window. Out of paranoia, we don't
1696  * allow WM_PAINT responses to do scrolling optimisations.
1697  */
1698 static void do_paint (Context ctx, int may_optimise){ 
1699     int i, j, start, our_curs_y;
1700     unsigned long attr, rv, cursor;
1701     char ch[1024];
1702
1703     if (cursor_on) {
1704         if (has_focus) {
1705             if (blinker || !cfg.blink_cur)
1706                 cursor = ATTR_ACTCURS;
1707             else
1708                 cursor = 0;
1709         }
1710         else
1711             cursor = ATTR_PASCURS;
1712     }
1713     else           cursor = 0;
1714     rv = (rvideo ? ATTR_REVERSE : 0);
1715     our_curs_y = curs_y + (scrtop - disptop) / (cols+1);
1716
1717     for (i=0; i<rows; i++) {
1718         int idx = i*(cols+1);
1719         int lattr = (disptop[idx+cols] & LATTR_MODE);
1720         for (j=0; j<=cols; j++,idx++) {
1721             unsigned long *d = disptop+idx;
1722             wanttext[idx] = lattr | ((*d ^ rv
1723                               ^ (selstart <= d && d < selend ?
1724                                  ATTR_REVERSE : 0)) |
1725                              (i==our_curs_y && j==curs_x ? cursor : 0));
1726
1727             if (blink_is_real) {
1728                 if (has_focus && tblinker && (wanttext[idx]&ATTR_BLINK) )
1729                 {
1730                     wanttext[idx] &= ATTR_MASK;
1731                     wanttext[idx] += ' ';
1732                 }
1733                 wanttext[idx] &= ~ATTR_BLINK;
1734             }
1735         }
1736     }
1737
1738     /*
1739      * We would perform scrolling optimisations in here, if they
1740      * didn't have a nasty tendency to cause the whole sodding
1741      * program to hang for a second at speed-critical moments.
1742      * We'll leave it well alone...
1743      */
1744
1745     for (i=0; i<rows; i++) {
1746         int idx = i*(cols+1);
1747         int lattr = (wanttext[idx+cols] & LATTR_MODE);
1748         start = -1;
1749         for (j=0; j<=cols; j++,idx++) {
1750             unsigned long t = wanttext[idx];
1751             int needs_update = (j < cols && t != disptext[idx]);
1752             int keep_going = (start != -1 && needs_update &&
1753                               (t & ATTR_MASK) == attr &&
1754                               j-start < sizeof(ch));
1755             if (start != -1 && !keep_going) {
1756                 do_text (ctx, start, i, ch, j-start, attr, lattr);
1757                 start = -1;
1758             }
1759             if (needs_update) {
1760                 if (start == -1) {
1761                     start = j;
1762                     attr = t & ATTR_MASK;
1763                 }
1764                 ch[j-start] = (char) (t & CHAR_MASK);
1765             }
1766             disptext[idx] = t;
1767         }
1768     }
1769 }
1770
1771 /*
1772  * Flick the switch that says if blinking things should be shown or hidden.
1773  */
1774
1775 void term_blink(int flg) {
1776 static long last_blink = 0;
1777 static long last_tblink = 0;
1778     long now, blink_diff;
1779
1780     now = GetTickCount();
1781     blink_diff = now-last_tblink;
1782
1783     /* Make sure the text blinks no more than 2Hz */
1784     if (blink_diff<0 || blink_diff>450)
1785     {
1786         last_tblink = now;
1787         tblinker = !tblinker;
1788     }
1789
1790     if (flg) {
1791         blinker = 1;
1792         last_blink = now;
1793         return;
1794     } 
1795
1796     blink_diff = now-last_blink;
1797
1798     /* Make sure the cursor blinks no more than 2Hz */
1799     if (blink_diff>=0 && blink_diff<450)
1800        return;
1801  
1802     last_blink = now;
1803     blinker = !blinker;
1804 }
1805
1806 /*
1807  * Invalidate the whole screen so it will be repainted in full.
1808  */
1809 void term_invalidate(void) {
1810     int i;
1811
1812     for (i=0; i<rows*(cols+1); i++)
1813         disptext[i] = ATTR_INVALID;
1814 }
1815
1816 /*
1817  * Paint the window in response to a WM_PAINT message.
1818  */
1819 void term_paint (Context ctx, int l, int t, int r, int b) {
1820     int i, j, left, top, right, bottom;
1821
1822     left = l / font_width;
1823     right = (r - 1) / font_width;
1824     top = t / font_height;
1825     bottom = (b - 1) / font_height;
1826     for (i = top; i <= bottom && i < rows ; i++)
1827     {
1828         if ( (disptext[i*(cols+1)+cols]&LATTR_MODE) == LATTR_NORM)
1829             for (j = left; j <= right && j < cols ; j++)
1830                 disptext[i*(cols+1)+j] = ATTR_INVALID;
1831         else
1832             for (j = left/2; j <= right/2+1 && j < cols ; j++)
1833                 disptext[i*(cols+1)+j] = ATTR_INVALID;
1834     }
1835
1836     /* This should happen soon enough, also for some reason it sometimes 
1837      * fails to actually do anything when re-sizing ... painting the wrong
1838      * window perhaps ?
1839     do_paint (ctx, FALSE);
1840     */
1841 }
1842
1843 /*
1844  * Attempt to scroll the scrollback. The second parameter gives the
1845  * position we want to scroll to; the first is +1 to denote that
1846  * this position is relative to the beginning of the scrollback, -1
1847  * to denote it is relative to the end, and 0 to denote that it is
1848  * relative to the current position.
1849  */
1850 void term_scroll (int rel, int where) {
1851     int n = where * (cols+1);
1852
1853     disptop = (rel < 0 ? scrtop :
1854                rel > 0 ? sbtop : disptop) + n;
1855     if (disptop < sbtop)
1856         disptop = sbtop;
1857     if (disptop > scrtop)
1858         disptop = scrtop;
1859     update_sbar();
1860     term_update();
1861 }
1862
1863 /*
1864  * Spread the selection outwards according to the selection mode.
1865  */
1866 static unsigned long *sel_spread_half (unsigned long *p, int dir) {
1867     unsigned long *linestart, *lineend;
1868     int x;
1869     short wvalue;
1870
1871     x = (p - text) % (cols+1);
1872     linestart = p - x;
1873     lineend = linestart + cols;
1874
1875     switch (selmode) {
1876       case SM_CHAR:
1877         /*
1878          * In this mode, every character is a separate unit, except
1879          * for runs of spaces at the end of a non-wrapping line.
1880          */
1881         if (!(linestart[cols] & ATTR_WRAPPED)) {
1882             unsigned long *q = lineend;
1883             while (q > linestart && (q[-1] & CHAR_MASK) == 0x20)
1884                 q--;
1885             if (q == lineend)
1886                 q--;
1887             if (p >= q)
1888                 p = (dir == -1 ? q : lineend - 1);
1889         }
1890         break;
1891       case SM_WORD:
1892         /*
1893          * In this mode, the units are maximal runs of characters
1894          * whose `wordness' has the same value.
1895          */
1896         wvalue = wordness[*p & CHAR_MASK];
1897         if (dir == +1) {
1898             while (p < lineend && wordness[p[1] & CHAR_MASK] == wvalue)
1899                 p++;
1900         } else {
1901             while (p > linestart && wordness[p[-1] & CHAR_MASK] == wvalue)
1902                 p--;
1903         }
1904         break;
1905       case SM_LINE:
1906         /*
1907          * In this mode, every line is a unit.
1908          */
1909         p = (dir == -1 ? linestart : lineend - 1);
1910         break;
1911     }
1912     return p;
1913 }
1914
1915 static void sel_spread (void) {
1916     selstart = sel_spread_half (selstart, -1);
1917     selend = sel_spread_half (selend - 1, +1) + 1;
1918 }
1919
1920 void term_mouse (Mouse_Button b, Mouse_Action a, int x, int y) {
1921     unsigned long *selpoint;
1922     
1923     if (y<0) y = 0;
1924     if (y>=rows) y = rows-1;
1925     if (x<0) {
1926         if (y > 0) {
1927             x = cols-1;
1928             y--;
1929         } else
1930             x = 0;
1931     }
1932     if (x>=cols) x = cols-1;
1933
1934     selpoint = disptop + y * (cols+1);
1935     if ((selpoint[cols]&LATTR_MODE) != LATTR_NORM)
1936         selpoint += x/2;
1937     else
1938         selpoint += x;
1939
1940     if (b == MB_SELECT && a == MA_CLICK) {
1941         deselect();
1942         selstate = ABOUT_TO;
1943         selanchor = selpoint;
1944         selmode = SM_CHAR;
1945     } else if (b == MB_SELECT && (a == MA_2CLK || a == MA_3CLK)) {
1946         deselect();
1947         selmode = (a == MA_2CLK ? SM_WORD : SM_LINE);
1948         selstate = DRAGGING;
1949         selstart = selanchor = selpoint;
1950         selend = selstart + 1;
1951         sel_spread();
1952     } else if ((b == MB_SELECT && a == MA_DRAG) ||
1953                (b == MB_EXTEND && a != MA_RELEASE)) {
1954         if (selstate == ABOUT_TO && selanchor == selpoint)
1955             return;
1956         if (b == MB_EXTEND && a != MA_DRAG && selstate == SELECTED) {
1957             if (selpoint-selstart < (selend-selstart)/2)
1958                 selanchor = selend - 1;
1959             else
1960                 selanchor = selstart;
1961             selstate = DRAGGING;
1962         }
1963         if (selstate != ABOUT_TO && selstate != DRAGGING)
1964             selanchor = selpoint;
1965         selstate = DRAGGING;
1966         if (selpoint < selanchor) {
1967             selstart = selpoint;
1968             selend = selanchor + 1;
1969         } else {
1970             selstart = selanchor;
1971             selend = selpoint + 1;
1972         }
1973         sel_spread();
1974     } else if ((b == MB_SELECT || b == MB_EXTEND) && a == MA_RELEASE) {
1975         if (selstate == DRAGGING) {
1976             /*
1977              * We've completed a selection. We now transfer the
1978              * data to the clipboard.
1979              */
1980             unsigned char *p = selspace;
1981             unsigned long *q = selstart;
1982
1983             while (q < selend) {
1984                 int nl = FALSE;
1985                 unsigned long *lineend = q - (q-text) % (cols+1) + cols;
1986                 unsigned long *nlpos = lineend;
1987
1988                 if (!(*nlpos & ATTR_WRAPPED)) {
1989                     while ((nlpos[-1] & CHAR_MASK) == 0x20 && nlpos > q)
1990                         nlpos--;
1991                     if (nlpos < selend)
1992                         nl = TRUE;
1993                 }
1994                 while (q < nlpos && q < selend)
1995                     *p++ = (unsigned char) (*q++ & CHAR_MASK);
1996                 if (nl) {
1997                     int i;
1998                     for (i=0; i<sizeof(sel_nl); i++)
1999                         *p++ = sel_nl[i];
2000                 }
2001                 q = lineend + 1;       /* start of next line */
2002             }
2003             write_clip (selspace, p - selspace);
2004             selstate = SELECTED;
2005         } else
2006             selstate = NO_SELECTION;
2007     } else if (b == MB_PASTE && (a==MA_CLICK || a==MA_2CLK || a==MA_3CLK)) {
2008         char *data;
2009         int len;
2010
2011         get_clip((void **) &data, &len);
2012         if (data) {
2013             char *p, *q;
2014
2015             if (paste_buffer) sfree(paste_buffer);
2016             paste_pos = paste_hold = paste_len = 0;
2017             paste_buffer = smalloc(len);
2018
2019             p = q = data;
2020             while (p < data+len) {
2021                 while (p < data+len &&
2022                        !(p <= data+len-sizeof(sel_nl) &&
2023                          !memcmp(p, sel_nl, sizeof(sel_nl))))
2024                     p++;
2025
2026                 {
2027                     int i;
2028                     unsigned char c;
2029                     for(i=0;i<p-q;i++)
2030                     {
2031                         c=xlat_kbd2tty(q[i]);
2032                         paste_buffer[paste_len++] = c;
2033                     }
2034                 }
2035
2036                 if (p <= data+len-sizeof(sel_nl) &&
2037                     !memcmp(p, sel_nl, sizeof(sel_nl))) {
2038                     paste_buffer[paste_len++] = '\r';
2039                     p += sizeof(sel_nl);
2040                 }
2041                 q = p;
2042             }
2043
2044             /* Assume a small paste will be OK in one go. */
2045             if (paste_len<256) {
2046                 ldisc->send (paste_buffer, paste_len);
2047                 if (paste_buffer) sfree(paste_buffer);
2048                 paste_buffer = 0;
2049                 paste_pos = paste_hold = paste_len = 0;
2050             }
2051         }
2052         get_clip(NULL, NULL);
2053     }
2054
2055     term_update();
2056 }
2057
2058 void term_nopaste() {
2059     if(paste_len == 0) return;
2060     sfree(paste_buffer);
2061     paste_buffer = 0;
2062     paste_len = 0;
2063 }
2064
2065 void term_paste() {
2066 static long last_paste = 0;
2067     long now, paste_diff;
2068
2069     if(paste_len == 0) return;
2070
2071     /* Don't wait forever to paste */
2072     if(paste_hold) {
2073         now = GetTickCount();
2074         paste_diff = now-last_paste;
2075         if (paste_diff>=0 && paste_diff<450)
2076             return;
2077     }
2078     paste_hold = 0;
2079
2080     while(paste_pos<paste_len)
2081     {
2082         char c = paste_buffer[paste_pos++];
2083         ldisc->send (&c, 1);
2084
2085         if (c =='\r') {
2086             paste_hold = 1;
2087             return;
2088         }
2089     }
2090     sfree(paste_buffer);
2091     paste_buffer = 0;
2092     paste_len = 0;
2093 }
2094
2095 static void deselect (void) {
2096     selstate = NO_SELECTION;
2097     selstart = selend = scrtop;
2098 }
2099
2100 void term_deselect (void) {
2101     deselect();
2102     term_update();
2103 }