]> asedeno.scripts.mit.edu Git - PuTTY.git/blob - terminal.c
Don't forget to flush the bidi cache when the user enables or
[PuTTY.git] / terminal.c
1 #include <stdio.h>
2 #include <stdlib.h>
3 #include <ctype.h>
4
5 #include <time.h>
6 #include <assert.h>
7 #include "putty.h"
8 #include "terminal.h"
9
10 #define poslt(p1,p2) ( (p1).y < (p2).y || ( (p1).y == (p2).y && (p1).x < (p2).x ) )
11 #define posle(p1,p2) ( (p1).y < (p2).y || ( (p1).y == (p2).y && (p1).x <= (p2).x ) )
12 #define poseq(p1,p2) ( (p1).y == (p2).y && (p1).x == (p2).x )
13 #define posdiff(p1,p2) ( ((p1).y - (p2).y) * (term->cols+1) + (p1).x - (p2).x )
14
15 /* Product-order comparisons for rectangular block selection. */
16 #define posPlt(p1,p2) ( (p1).y <= (p2).y && (p1).x < (p2).x )
17 #define posPle(p1,p2) ( (p1).y <= (p2).y && (p1).x <= (p2).x )
18
19 #define incpos(p) ( (p).x == term->cols ? ((p).x = 0, (p).y++, 1) : ((p).x++, 0) )
20 #define decpos(p) ( (p).x == 0 ? ((p).x = term->cols, (p).y--, 1) : ((p).x--, 0) )
21
22 #define VT52_PLUS
23
24 #define CL_ANSIMIN      0x0001         /* Codes in all ANSI like terminals. */
25 #define CL_VT100        0x0002         /* VT100 */
26 #define CL_VT100AVO     0x0004         /* VT100 +AVO; 132x24 (not 132x14) & attrs */
27 #define CL_VT102        0x0008         /* VT102 */
28 #define CL_VT220        0x0010         /* VT220 */
29 #define CL_VT320        0x0020         /* VT320 */
30 #define CL_VT420        0x0040         /* VT420 */
31 #define CL_VT510        0x0080         /* VT510, NB VT510 includes ANSI */
32 #define CL_VT340TEXT    0x0100         /* VT340 extensions that appear in the VT420 */
33 #define CL_SCOANSI      0x1000         /* SCOANSI not in ANSIMIN. */
34 #define CL_ANSI         0x2000         /* ANSI ECMA-48 not in the VT100..VT420 */
35 #define CL_OTHER        0x4000         /* Others, Xterm, linux, putty, dunno, etc */
36
37 #define TM_VT100        (CL_ANSIMIN|CL_VT100)
38 #define TM_VT100AVO     (TM_VT100|CL_VT100AVO)
39 #define TM_VT102        (TM_VT100AVO|CL_VT102)
40 #define TM_VT220        (TM_VT102|CL_VT220)
41 #define TM_VTXXX        (TM_VT220|CL_VT340TEXT|CL_VT510|CL_VT420|CL_VT320)
42 #define TM_SCOANSI      (CL_ANSIMIN|CL_SCOANSI)
43
44 #define TM_PUTTY        (0xFFFF)
45
46 #define compatibility(x) \
47     if ( ((CL_##x)&term->compatibility_level) == 0 ) {  \
48        term->termstate=TOPLEVEL;                        \
49        break;                                           \
50     }
51 #define compatibility2(x,y) \
52     if ( ((CL_##x|CL_##y)&term->compatibility_level) == 0 ) { \
53        term->termstate=TOPLEVEL;                        \
54        break;                                           \
55     }
56
57 #define has_compat(x) ( ((CL_##x)&term->compatibility_level) != 0 )
58
59 const char sco2ansicolour[] = { 0, 4, 2, 6, 1, 5, 3, 7 };
60
61 #define sel_nl_sz  (sizeof(sel_nl)/sizeof(wchar_t))
62 const wchar_t sel_nl[] = SEL_NL;
63
64 /*
65  * Fetch the character at a particular position in a line array,
66  * for purposes of `wordtype'. The reason this isn't just a simple
67  * array reference is that if the character we find is UCSWIDE,
68  * then we must look one space further to the left.
69  */
70 #define UCSGET(a, x) \
71     ( (x)>0 && (a)[(x)].chr == UCSWIDE ? (a)[(x)-1].chr : (a)[(x)].chr )
72
73 /*
74  * Detect the various aliases of U+0020 SPACE.
75  */
76 #define IS_SPACE_CHR(chr) \
77         ((chr) == 0x20 || (DIRECT_CHAR(chr) && ((chr) & 0xFF) == 0x20))
78
79 /*
80  * Spot magic CSETs.
81  */
82 #define CSET_OF(chr) (DIRECT_CHAR(chr)||DIRECT_FONT(chr) ? (chr)&CSET_MASK : 0)
83
84 /*
85  * Internal prototypes.
86  */
87 static void resizeline(Terminal *, termline *, int);
88 static termline *lineptr(Terminal *, int, int, int);
89 static void unlineptr(termline *);
90 static void do_paint(Terminal *, Context, int);
91 static void erase_lots(Terminal *, int, int, int);
92 static void swap_screen(Terminal *, int, int, int);
93 static void update_sbar(Terminal *);
94 static void deselect(Terminal *);
95 static void term_print_finish(Terminal *);
96 #ifdef OPTIMISE_SCROLL
97 static void scroll_display(Terminal *, int, int, int);
98 #endif /* OPTIMISE_SCROLL */
99
100 static termline *newline(Terminal *term, int cols, int bce)
101 {
102     termline *line;
103     int j;
104
105     line = snew(termline);
106     line->chars = snewn(cols, termchar);
107     for (j = 0; j < cols; j++)
108         line->chars[j] = (bce ? term->erase_char : term->basic_erase_char);
109     line->cols = line->size = cols;
110     line->lattr = LATTR_NORM;
111     line->temporary = FALSE;
112     line->cc_free = 0;
113
114     return line;
115 }
116
117 static void freeline(termline *line)
118 {
119     if (line) {
120         sfree(line->chars);
121         sfree(line);
122     }
123 }
124
125 static void unlineptr(termline *line)
126 {
127     if (line->temporary)
128         freeline(line);
129 }
130
131 /*
132  * Diagnostic function: verify that a termline has a correct
133  * combining character structure.
134  * 
135  * XXX-REMOVE-BEFORE-RELEASE: This is a performance-intensive
136  * check. Although it's currently really useful for getting all the
137  * bugs out of the new cc stuff, it will want to be absent when we
138  * make a proper release.
139  */
140 static void cc_check(termline *line)
141 {
142     unsigned char *flags;
143     int i, j;
144
145     assert(line->size >= line->cols);
146
147     flags = snewn(line->size, unsigned char);
148
149     for (i = 0; i < line->size; i++)
150         flags[i] = (i < line->cols);
151
152     for (i = 0; i < line->cols; i++) {
153         j = i;
154         while (line->chars[j].cc_next) {
155             j += line->chars[j].cc_next;
156             assert(j >= line->cols && j < line->size);
157             assert(!flags[j]);
158             flags[j] = TRUE;
159         }
160     }
161
162     j = line->cc_free;
163     if (j) {
164         while (1) {
165             assert(j >= line->cols && j < line->size);
166             assert(!flags[j]);
167             flags[j] = TRUE;
168             if (line->chars[j].cc_next)
169                 j += line->chars[j].cc_next;
170             else
171                 break;
172         }
173     }
174
175     j = 0;
176     for (i = 0; i < line->size; i++)
177         j += (flags[i] != 0);
178
179     assert(j == line->size);
180 }
181
182 /*
183  * Add a combining character to a character cell.
184  */
185 static void add_cc(termline *line, int col, unsigned long chr)
186 {
187     int newcc;
188
189     assert(col >= 0 && col < line->cols);
190
191     /*
192      * Start by extending the cols array if the free list is empty.
193      */
194     if (!line->cc_free) {
195         int n = line->size;
196         line->size += 16 + (line->size - line->cols) / 2;
197         line->chars = sresize(line->chars, line->size, termchar);
198         line->cc_free = n;
199         while (n < line->size) {
200             if (n+1 < line->size)
201                 line->chars[n].cc_next = 1;
202             else
203                 line->chars[n].cc_next = 0;
204             n++;
205         }
206     }
207
208     /*
209      * Now walk the cc list of the cell in question.
210      */
211     while (line->chars[col].cc_next)
212         col += line->chars[col].cc_next;
213
214     /*
215      * `col' now points at the last cc currently in this cell; so
216      * we simply add another one.
217      */
218     newcc = line->cc_free;
219     if (line->chars[newcc].cc_next)
220         line->cc_free = newcc + line->chars[newcc].cc_next;
221     else
222         line->cc_free = 0;
223     line->chars[newcc].cc_next = 0;
224     line->chars[newcc].chr = chr;
225     line->chars[col].cc_next = newcc - col;
226
227     cc_check(line);                    /* XXX-REMOVE-BEFORE-RELEASE */
228 }
229
230 /*
231  * Clear the combining character list in a character cell.
232  */
233 static void clear_cc(termline *line, int col)
234 {
235     int oldfree, origcol = col;
236
237     assert(col >= 0 && col < line->cols);
238
239     if (!line->chars[col].cc_next)
240         return;                        /* nothing needs doing */
241
242     oldfree = line->cc_free;
243     line->cc_free = col + line->chars[col].cc_next;
244     while (line->chars[col].cc_next)
245         col += line->chars[col].cc_next;
246     if (oldfree)
247         line->chars[col].cc_next = oldfree - col;
248     else
249         line->chars[col].cc_next = 0;
250
251     line->chars[origcol].cc_next = 0;
252
253     cc_check(line);                    /* XXX-REMOVE-BEFORE-RELEASE */
254 }
255
256 /*
257  * Compare two character cells for equality. Special case required
258  * in do_paint() where we override what we expect the chr and attr
259  * fields to be.
260  */
261 static int termchars_equal_override(termchar *a, termchar *b,
262                                     unsigned long bchr, unsigned long battr)
263 {
264     /* FULL-TERMCHAR */
265     if (a->chr != bchr)
266         return FALSE;
267     if (a->attr != battr)
268         return FALSE;
269     while (a->cc_next || b->cc_next) {
270         if (!a->cc_next || !b->cc_next)
271             return FALSE;              /* one cc-list ends, other does not */
272         a += a->cc_next;
273         b += b->cc_next;
274         if (a->chr != b->chr)
275             return FALSE;
276     }
277     return TRUE;
278 }
279
280 static int termchars_equal(termchar *a, termchar *b)
281 {
282     return termchars_equal_override(a, b, b->chr, b->attr);
283 }
284
285 /*
286  * Copy a character cell. (Requires a pointer to the destination
287  * termline, so as to access its free list.)
288  */
289 static void copy_termchar(termline *destline, int x, termchar *src)
290 {
291     clear_cc(destline, x);
292
293     destline->chars[x] = *src;         /* copy everything except cc-list */
294     destline->chars[x].cc_next = 0;    /* and make sure this is zero */
295
296     while (src->cc_next) {
297         src += src->cc_next;
298         add_cc(destline, x, src->chr);
299     }
300
301     cc_check(destline);                /* XXX-REMOVE-BEFORE-RELEASE */
302 }
303
304 /*
305  * Move a character cell within its termline.
306  */
307 static void move_termchar(termline *line, termchar *dest, termchar *src)
308 {
309     /* First clear the cc list from the original char, just in case. */
310     clear_cc(line, dest - line->chars);
311
312     /* Move the character cell and adjust its cc_next. */
313     *dest = *src;                      /* copy everything except cc-list */
314     if (src->cc_next)
315         dest->cc_next = src->cc_next - (dest-src);
316
317     /* Ensure the original cell doesn't have a cc list. */
318     src->cc_next = 0;
319
320     cc_check(line);                    /* XXX-REMOVE-BEFORE-RELEASE */
321 }
322
323 /*
324  * Compress and decompress a termline into an RLE-based format for
325  * storing in scrollback. (Since scrollback almost never needs to
326  * be modified and exists in huge quantities, this is a sensible
327  * tradeoff, particularly since it allows us to continue adding
328  * features to the main termchar structure without proportionally
329  * bloating the terminal emulator's memory footprint unless those
330  * features are in constant use.)
331  */
332 struct buf {
333     unsigned char *data;
334     int len, size;
335 };
336 static void add(struct buf *b, unsigned char c)
337 {
338     if (b->len >= b->size) {
339         b->size = (b->len * 3 / 2) + 512;
340         b->data = sresize(b->data, b->size, unsigned char);
341     }
342     b->data[b->len++] = c;
343 }
344 static int get(struct buf *b)
345 {
346     return b->data[b->len++];
347 }
348 static void makerle(struct buf *b, termline *ldata,
349                     void (*makeliteral)(struct buf *b, termchar *c,
350                                         unsigned long *state))
351 {
352     int hdrpos, hdrsize, n, prevlen, prevpos, thislen, thispos, prev2;
353     termchar *c = ldata->chars;
354     unsigned long state = 0, oldstate;
355
356     n = ldata->cols;
357
358     hdrpos = b->len;
359     hdrsize = 0;
360     add(b, 0);
361     prevlen = prevpos = 0;
362     prev2 = FALSE;
363
364     while (n-- > 0) {
365         thispos = b->len;
366         makeliteral(b, c++, &state);
367         thislen = b->len - thispos;
368         if (thislen == prevlen &&
369             !memcmp(b->data + prevpos, b->data + thispos, thislen)) {
370             /*
371              * This literal precisely matches the previous one.
372              * Turn it into a run if it's worthwhile.
373              * 
374              * With one-byte literals, it costs us two bytes to
375              * encode a run, plus another byte to write the header
376              * to resume normal output; so a three-element run is
377              * neutral, and anything beyond that is unconditionally
378              * worthwhile. With two-byte literals or more, even a
379              * 2-run is a win.
380              */
381             if (thislen > 1 || prev2) {
382                 int runpos, runlen;
383
384                 /*
385                  * It's worth encoding a run. Start at prevpos,
386                  * unless hdrsize==0 in which case we can back up
387                  * another one and start by overwriting hdrpos.
388                  */
389
390                 hdrsize--;             /* remove the literal at prevpos */
391                 if (prev2) {
392                     assert(hdrsize > 0);
393                     hdrsize--;
394                     prevpos -= prevlen;/* and possibly another one */
395                 }
396
397                 if (hdrsize == 0) {
398                     assert(prevpos == hdrpos + 1);
399                     runpos = hdrpos;
400                     b->len = prevpos+prevlen;
401                 } else {
402                     memmove(b->data + prevpos+1, b->data + prevpos, prevlen);
403                     runpos = prevpos;
404                     b->len = prevpos+prevlen+1;
405                     /*
406                      * Terminate the previous run of ordinary
407                      * literals.
408                      */
409                     assert(hdrsize >= 1 && hdrsize <= 128);
410                     b->data[hdrpos] = hdrsize - 1;
411                 }
412
413                 runlen = prev2 ? 3 : 2;
414
415                 while (n > 0 && runlen < 129) {
416                     int tmppos, tmplen;
417                     tmppos = b->len;
418                     oldstate = state;
419                     makeliteral(b, c, &state);
420                     tmplen = b->len - tmppos;
421                     b->len = tmppos;
422                     if (tmplen != thislen ||
423                         memcmp(b->data + runpos+1, b->data + tmppos, tmplen)) {
424                         state = oldstate;
425                         break;         /* run over */
426                     }
427                     n--, c++, runlen++;
428                 }
429
430                 assert(runlen >= 2 && runlen <= 129);
431                 b->data[runpos] = runlen + 0x80 - 2;
432
433                 hdrpos = b->len;
434                 hdrsize = 0;
435                 add(b, 0);
436
437                 continue;
438             } else {
439                 /*
440                  * Just flag that the previous two literals were
441                  * identical, in case we find a third identical one
442                  * we want to turn into a run.
443                  */
444                 prev2 = TRUE;
445                 prevlen = thislen;
446                 prevpos = thispos;
447             }
448         } else {
449             prev2 = FALSE;
450             prevlen = thislen;
451             prevpos = thispos;
452         }
453
454         /*
455          * This character isn't (yet) part of a run. Add it to
456          * hdrsize.
457          */
458         hdrsize++;
459         if (hdrsize == 128) {
460             b->data[hdrpos] = hdrsize - 1;
461             hdrpos = b->len;
462             hdrsize = 0;
463             add(b, 0);
464             prevlen = prevpos = 0;
465             prev2 = FALSE;
466         }
467     }
468
469     /*
470      * Clean up.
471      */
472     if (hdrsize > 0) {
473         assert(hdrsize <= 128);
474         b->data[hdrpos] = hdrsize - 1;
475     } else {
476         b->len = hdrpos;
477     }
478 }
479 static void makeliteral_chr(struct buf *b, termchar *c, unsigned long *state)
480 {
481     /*
482      * My encoding for characters is UTF-8-like, in that it stores
483      * 7-bit ASCII in one byte and uses high-bit-set bytes as
484      * introducers to indicate a longer sequence. However, it's
485      * unlike UTF-8 in that it doesn't need to be able to
486      * resynchronise, and therefore I don't want to waste two bits
487      * per byte on having recognisable continuation characters.
488      * Also I don't want to rule out the possibility that I may one
489      * day use values 0x80000000-0xFFFFFFFF for interesting
490      * purposes, so unlike UTF-8 I need a full 32-bit range.
491      * Accordingly, here is my encoding:
492      * 
493      * 00000000-0000007F: 0xxxxxxx (but see below)
494      * 00000080-00003FFF: 10xxxxxx xxxxxxxx
495      * 00004000-001FFFFF: 110xxxxx xxxxxxxx xxxxxxxx
496      * 00200000-0FFFFFFF: 1110xxxx xxxxxxxx xxxxxxxx xxxxxxxx
497      * 10000000-FFFFFFFF: 11110ZZZ xxxxxxxx xxxxxxxx xxxxxxxx xxxxxxxx
498      * 
499      * (`Z' is like `x' but is always going to be zero since the
500      * values I'm encoding don't go above 2^32. In principle the
501      * five-byte form of the encoding could extend to 2^35, and
502      * there could be six-, seven-, eight- and nine-byte forms as
503      * well to allow up to 64-bit values to be encoded. But that's
504      * completely unnecessary for these purposes!)
505      * 
506      * The encoding as written above would be very simple, except
507      * that 7-bit ASCII can occur in several different ways in the
508      * terminal data; sometimes it crops up in the D800 page
509      * (CSET_ASCII) but at other times it's in the 0000 page (real
510      * Unicode). Therefore, this encoding is actually _stateful_:
511      * the one-byte encoding of 00-7F actually indicates `reuse the
512      * upper three bytes of the last character', and to encode an
513      * absolute value of 00-7F you need to use the two-byte form
514      * instead.
515      */
516     if ((c->chr & ~0x7F) == *state) {
517         add(b, (unsigned char)(c->chr & 0x7F));
518     } else if (c->chr < 0x4000) {
519         add(b, (unsigned char)(((c->chr >> 8) & 0x3F) | 0x80));
520         add(b, (unsigned char)(c->chr & 0xFF));
521     } else if (c->chr < 0x200000) {
522         add(b, (unsigned char)(((c->chr >> 16) & 0x1F) | 0xC0));
523         add(b, (unsigned char)((c->chr >> 8) & 0xFF));
524         add(b, (unsigned char)(c->chr & 0xFF));
525     } else if (c->chr < 0x10000000) {
526         add(b, (unsigned char)(((c->chr >> 24) & 0x0F) | 0xE0));
527         add(b, (unsigned char)((c->chr >> 16) & 0xFF));
528         add(b, (unsigned char)((c->chr >> 8) & 0xFF));
529         add(b, (unsigned char)(c->chr & 0xFF));
530     } else {
531         add(b, 0xF0);
532         add(b, (unsigned char)((c->chr >> 24) & 0xFF));
533         add(b, (unsigned char)((c->chr >> 16) & 0xFF));
534         add(b, (unsigned char)((c->chr >> 8) & 0xFF));
535         add(b, (unsigned char)(c->chr & 0xFF));
536     }
537     *state = c->chr & ~0xFF;
538 }
539 static void makeliteral_attr(struct buf *b, termchar *c, unsigned long *state)
540 {
541     /*
542      * My encoding for attributes is 16-bit-granular and assumes
543      * that the top bit of the word is never required. I either
544      * store a two-byte value with the top bit clear (indicating
545      * just that value), or a four-byte value with the top bit set
546      * (indicating the same value with its top bit clear).
547      */
548     if (c->attr < 0x8000) {
549         add(b, (unsigned char)((c->attr >> 8) & 0xFF));
550         add(b, (unsigned char)(c->attr & 0xFF));
551     } else {
552         add(b, (unsigned char)(((c->attr >> 24) & 0x7F) | 0x80));
553         add(b, (unsigned char)((c->attr >> 16) & 0xFF));
554         add(b, (unsigned char)((c->attr >> 8) & 0xFF));
555         add(b, (unsigned char)(c->attr & 0xFF));
556     }
557 }
558 static void makeliteral_cc(struct buf *b, termchar *c, unsigned long *state)
559 {
560     /*
561      * For combining characters, I just encode a bunch of ordinary
562      * chars using makeliteral_chr, and terminate with a \0
563      * character (which I know won't come up as a combining char
564      * itself).
565      * 
566      * I don't use the stateful encoding in makeliteral_chr.
567      */
568     unsigned long zstate;
569     termchar z;
570
571     while (c->cc_next) {
572         c += c->cc_next;
573
574         assert(c->chr != 0);
575
576         zstate = 0;
577         makeliteral_chr(b, c, &zstate);
578     }
579
580     z.chr = 0;
581     zstate = 0;
582     makeliteral_chr(b, &z, &zstate);
583 }
584
585 static termline *decompressline(unsigned char *data, int *bytes_used);
586
587 static unsigned char *compressline(termline *ldata)
588 {
589     struct buf buffer = { NULL, 0, 0 }, *b = &buffer;
590
591     /*
592      * First, store the column count, 7 bits at a time, least
593      * significant `digit' first, with the high bit set on all but
594      * the last.
595      */
596     {
597         int n = ldata->cols;
598         while (n >= 128) {
599             add(b, (unsigned char)((n & 0x7F) | 0x80));
600             n >>= 7;
601         }
602         add(b, (unsigned char)(n));
603     }
604
605     /*
606      * Next store the lattrs; same principle.
607      */
608     {
609         int n = ldata->lattr;
610         while (n >= 128) {
611             add(b, (unsigned char)((n & 0x7F) | 0x80));
612             n >>= 7;
613         }
614         add(b, (unsigned char)(n));
615     }
616
617     /*
618      * Now we store a sequence of separate run-length encoded
619      * fragments, each containing exactly as many symbols as there
620      * are columns in the ldata.
621      * 
622      * All of these have a common basic format:
623      * 
624      *  - a byte 00-7F indicates that X+1 literals follow it
625      *  - a byte 80-FF indicates that a single literal follows it
626      *    and expects to be repeated (X-0x80)+2 times.
627      * 
628      * The format of the `literals' varies between the fragments.
629      */
630     makerle(b, ldata, makeliteral_chr);
631     makerle(b, ldata, makeliteral_attr);
632     makerle(b, ldata, makeliteral_cc);
633
634     /*
635      * Diagnostics: ensure that the compressed data really does
636      * decompress to the right thing.
637      */
638 #ifndef CHECK_SB_COMPRESSION
639     {
640         int dused;
641         termline *dcl;
642         int i;
643
644 #ifdef DIAGNOSTIC_SB_COMPRESSION
645         for (i = 0; i < b->len; i++) {
646             printf(" %02x ", b->data[i]);
647         }
648         printf("\n");
649 #endif
650
651         dcl = decompressline(b->data, &dused);
652         assert(b->len == dused);
653         assert(ldata->cols == dcl->cols);
654         assert(ldata->lattr == dcl->lattr);
655         for (i = 0; i < ldata->cols; i++)
656             assert(termchars_equal(&ldata->chars[i], &dcl->chars[i]));
657
658 #ifdef DIAGNOSTIC_SB_COMPRESSION
659         printf("%d cols (%d bytes) -> %d bytes (factor of %g)\n",
660                ldata->cols, 4 * ldata->cols, dused,
661                (double)dused / (4 * ldata->cols));
662 #endif
663
664         freeline(dcl);
665     }
666 #endif
667
668     /*
669      * Trim the allocated memory so we don't waste any, and return.
670      */
671     return sresize(b->data, b->len, unsigned char);
672 }
673
674 static void readrle(struct buf *b, termline *ldata,
675                     void (*readliteral)(struct buf *b, termchar *c,
676                                         termline *ldata, unsigned long *state))
677 {
678     int n = 0;
679     unsigned long state = 0;
680
681     while (n < ldata->cols) {
682         int hdr = get(b);
683
684         if (hdr >= 0x80) {
685             /* A run. */
686
687             int pos = b->len, count = hdr + 2 - 0x80;
688             while (count--) {
689                 assert(n < ldata->cols);
690                 b->len = pos;
691                 readliteral(b, ldata->chars + n, ldata, &state);
692                 n++;
693             }
694         } else {
695             /* Just a sequence of consecutive literals. */
696
697             int count = hdr + 1;
698             while (count--) {
699                 assert(n < ldata->cols);
700                 readliteral(b, ldata->chars + n, ldata, &state);
701                 n++;
702             }
703         }
704     }
705
706     assert(n == ldata->cols);
707 }
708 static void readliteral_chr(struct buf *b, termchar *c, termline *ldata,
709                             unsigned long *state)
710 {
711     int byte;
712
713     /*
714      * 00000000-0000007F: 0xxxxxxx
715      * 00000080-00003FFF: 10xxxxxx xxxxxxxx
716      * 00004000-001FFFFF: 110xxxxx xxxxxxxx xxxxxxxx
717      * 00200000-0FFFFFFF: 1110xxxx xxxxxxxx xxxxxxxx xxxxxxxx
718      * 10000000-FFFFFFFF: 11110ZZZ xxxxxxxx xxxxxxxx xxxxxxxx xxxxxxxx
719      */
720
721     byte = get(b);
722     if (byte < 0x80) {
723         c->chr = byte | *state;
724     } else if (byte < 0xC0) {
725         c->chr = (byte &~ 0xC0) << 8;
726         c->chr |= get(b);
727     } else if (byte < 0xE0) {
728         c->chr = (byte &~ 0xE0) << 16;
729         c->chr |= get(b) << 8;
730         c->chr |= get(b);
731     } else if (byte < 0xF0) {
732         c->chr = (byte &~ 0xF0) << 24;
733         c->chr |= get(b) << 16;
734         c->chr |= get(b) << 8;
735         c->chr |= get(b);
736     } else {
737         assert(byte == 0xF0);
738         c->chr = get(b) << 24;
739         c->chr |= get(b) << 16;
740         c->chr |= get(b) << 8;
741         c->chr |= get(b);
742     }
743     *state = c->chr & ~0xFF;
744 }
745 static void readliteral_attr(struct buf *b, termchar *c, termline *ldata,
746                              unsigned long *state)
747 {
748     int val;
749
750     val = get(b) << 8;
751     val |= get(b);
752
753     if (val >= 0x8000) {
754         val <<= 16;
755         val |= get(b) << 8;
756         val |= get(b);
757     }
758
759     c->attr = val;
760 }
761 static void readliteral_cc(struct buf *b, termchar *c, termline *ldata,
762                            unsigned long *state)
763 {
764     termchar n;
765     unsigned long zstate;
766     int x = c - ldata->chars;
767
768     c->cc_next = 0;
769
770     while (1) {
771         zstate = 0;
772         readliteral_chr(b, &n, ldata, &zstate);
773         if (!n.chr)
774             break;
775         add_cc(ldata, x, n.chr);
776     }
777 }
778
779 static termline *decompressline(unsigned char *data, int *bytes_used)
780 {
781     int ncols, byte, shift;
782     struct buf buffer, *b = &buffer;
783     termline *ldata;
784
785     b->data = data;
786     b->len = 0;
787
788     /*
789      * First read in the column count.
790      */
791     ncols = shift = 0;
792     do {
793         byte = get(b);
794         ncols |= (byte & 0x7F) << shift;
795         shift += 7;
796     } while (byte & 0x80);
797
798     /*
799      * Now create the output termline.
800      */
801     ldata = snew(termline);
802     ldata->chars = snewn(ncols, termchar);
803     ldata->cols = ldata->size = ncols;
804     ldata->temporary = TRUE;
805     ldata->cc_free = 0;
806
807     /*
808      * We must set all the cc pointers in ldata->chars to 0 right
809      * now, so that cc diagnostics that verify the integrity of the
810      * whole line will make sense while we're in the middle of
811      * building it up.
812      */
813     {
814         int i;
815         for (i = 0; i < ldata->cols; i++)
816             ldata->chars[i].cc_next = 0;
817     }
818
819     /*
820      * Now read in the lattr.
821      */
822     ldata->lattr = shift = 0;
823     do {
824         byte = get(b);
825         ldata->lattr |= (byte & 0x7F) << shift;
826         shift += 7;
827     } while (byte & 0x80);
828
829     /*
830      * Now we read in each of the RLE streams in turn.
831      */
832     readrle(b, ldata, readliteral_chr);
833     readrle(b, ldata, readliteral_attr);
834     readrle(b, ldata, readliteral_cc);
835
836     /* Return the number of bytes read, for diagnostic purposes. */
837     if (bytes_used)
838         *bytes_used = b->len;
839
840     return ldata;
841 }
842
843 /*
844  * Resize a line to make it `cols' columns wide.
845  */
846 static void resizeline(Terminal *term, termline *line, int cols)
847 {
848     int i, oldcols;
849
850     if (line->cols != cols) {
851
852         oldcols = line->cols;
853
854         /*
855          * This line is the wrong length, which probably means it
856          * hasn't been accessed since a resize. Resize it now.
857          * 
858          * First, go through all the characters that will be thrown
859          * out in the resize (if we're shrinking the line) and
860          * return their cc lists to the cc free list.
861          */
862         for (i = cols; i < oldcols; i++)
863             clear_cc(line, i);
864
865         /*
866          * If we're shrinking the line, we now bodily move the
867          * entire cc section from where it started to where it now
868          * needs to be. (We have to do this before the resize, so
869          * that the data we're copying is still there. However, if
870          * we're expanding, we have to wait until _after_ the
871          * resize so that the space we're copying into is there.)
872          */
873         if (cols < oldcols)
874             memmove(line->chars + cols, line->chars + oldcols,
875                     (line->size - line->cols) * TSIZE);
876
877         /*
878          * Now do the actual resize, leaving the _same_ amount of
879          * cc space as there was to begin with.
880          */
881         line->size += cols - oldcols;
882         line->chars = sresize(line->chars, line->size, TTYPE);
883         line->cols = cols;
884
885         /*
886          * If we're expanding the line, _now_ we move the cc
887          * section.
888          */
889         if (cols > oldcols)
890             memmove(line->chars + cols, line->chars + oldcols,
891                     (line->size - line->cols) * TSIZE);
892
893         /*
894          * Go through what's left of the original line, and adjust
895          * the first cc_next pointer in each list. (All the
896          * subsequent ones are still valid because they are
897          * relative offsets within the cc block.) Also do the same
898          * to the head of the cc_free list.
899          */
900         for (i = 0; i < oldcols && i < cols; i++)
901             if (line->chars[i].cc_next)
902                 line->chars[i].cc_next += cols - oldcols;
903         if (line->cc_free)
904             line->cc_free += cols - oldcols;
905
906         /*
907          * And finally fill in the new space with erase chars. (We
908          * don't have to worry about cc lists here, because we
909          * _know_ the erase char doesn't have one.)
910          */
911         for (i = oldcols; i < cols; i++)
912             line->chars[i] = term->basic_erase_char;
913
914         cc_check(line);                /* XXX-REMOVE-BEFORE-RELEASE */
915     }
916 }
917
918 /*
919  * Get the number of lines in the scrollback.
920  */
921 static int sblines(Terminal *term)
922 {
923     int sblines = count234(term->scrollback);
924     if (term->cfg.erase_to_scrollback &&
925         term->alt_which && term->alt_screen) {
926             sblines += term->alt_sblines;
927     }
928     return sblines;
929 }
930
931 /*
932  * Retrieve a line of the screen or of the scrollback, according to
933  * whether the y coordinate is non-negative or negative
934  * (respectively).
935  */
936 static termline *lineptr(Terminal *term, int y, int lineno, int screen)
937 {
938     termline *line;
939     tree234 *whichtree;
940     int treeindex;
941
942     if (y >= 0) {
943         whichtree = term->screen;
944         treeindex = y;
945     } else {
946         int altlines = 0;
947
948         assert(!screen);
949
950         if (term->cfg.erase_to_scrollback &&
951             term->alt_which && term->alt_screen) {
952             altlines = term->alt_sblines;
953         }
954         if (y < -altlines) {
955             whichtree = term->scrollback;
956             treeindex = y + altlines + count234(term->scrollback);
957         } else {
958             whichtree = term->alt_screen;
959             treeindex = y + term->alt_sblines;
960             /* treeindex = y + count234(term->alt_screen); */
961         }
962     }
963     if (whichtree == term->scrollback) {
964         unsigned char *cline = index234(whichtree, treeindex);
965         line = decompressline(cline, NULL);
966     } else {
967         line = index234(whichtree, treeindex);
968     }
969
970     /* We assume that we don't screw up and retrieve something out of range. */
971     assert(line != NULL);
972
973     resizeline(term, line, term->cols);
974     /* FIXME: should we sort the compressed scrollback out here? */
975
976     return line;
977 }
978
979 #define lineptr(x) (lineptr)(term,x,__LINE__,FALSE)
980 #define scrlineptr(x) (lineptr)(term,x,__LINE__,TRUE)
981
982 /*
983  * Set up power-on settings for the terminal.
984  */
985 static void power_on(Terminal *term)
986 {
987     term->curs.x = term->curs.y = 0;
988     term->alt_x = term->alt_y = 0;
989     term->savecurs.x = term->savecurs.y = 0;
990     term->alt_t = term->marg_t = 0;
991     if (term->rows != -1)
992         term->alt_b = term->marg_b = term->rows - 1;
993     else
994         term->alt_b = term->marg_b = 0;
995     if (term->cols != -1) {
996         int i;
997         for (i = 0; i < term->cols; i++)
998             term->tabs[i] = (i % 8 == 0 ? TRUE : FALSE);
999     }
1000     term->alt_om = term->dec_om = term->cfg.dec_om;
1001     term->alt_ins = term->insert = FALSE;
1002     term->alt_wnext = term->wrapnext = term->save_wnext = FALSE;
1003     term->alt_wrap = term->wrap = term->cfg.wrap_mode;
1004     term->alt_cset = term->cset = term->save_cset = 0;
1005     term->alt_utf = term->utf = term->save_utf = 0;
1006     term->utf_state = 0;
1007     term->alt_sco_acs = term->sco_acs = term->save_sco_acs = 0;
1008     term->cset_attr[0] = term->cset_attr[1] = term->save_csattr = CSET_ASCII;
1009     term->rvideo = 0;
1010     term->in_vbell = FALSE;
1011     term->cursor_on = 1;
1012     term->big_cursor = 0;
1013     term->default_attr = term->save_attr = term->curr_attr = ATTR_DEFAULT;
1014     term->term_editing = term->term_echoing = FALSE;
1015     term->app_cursor_keys = term->cfg.app_cursor;
1016     term->app_keypad_keys = term->cfg.app_keypad;
1017     term->use_bce = term->cfg.bce;
1018     term->blink_is_real = term->cfg.blinktext;
1019     term->erase_char = term->basic_erase_char;
1020     term->alt_which = 0;
1021     term_print_finish(term);
1022     {
1023         int i;
1024         for (i = 0; i < 256; i++)
1025             term->wordness[i] = term->cfg.wordness[i];
1026     }
1027     if (term->screen) {
1028         swap_screen(term, 1, FALSE, FALSE);
1029         erase_lots(term, FALSE, TRUE, TRUE);
1030         swap_screen(term, 0, FALSE, FALSE);
1031         erase_lots(term, FALSE, TRUE, TRUE);
1032     }
1033 }
1034
1035 /*
1036  * Force a screen update.
1037  */
1038 void term_update(Terminal *term)
1039 {
1040     Context ctx;
1041     ctx = get_ctx(term->frontend);
1042     if (ctx) {
1043         int need_sbar_update = term->seen_disp_event;
1044         if (term->seen_disp_event && term->cfg.scroll_on_disp) {
1045             term->disptop = 0;         /* return to main screen */
1046             term->seen_disp_event = 0;
1047             need_sbar_update = TRUE;
1048         }
1049
1050         if (need_sbar_update)
1051             update_sbar(term);
1052         do_paint(term, ctx, TRUE);
1053         sys_cursor(term->frontend, term->curs.x, term->curs.y - term->disptop);
1054         free_ctx(ctx);
1055     }
1056 }
1057
1058 /*
1059  * Called from front end when a keypress occurs, to trigger
1060  * anything magical that needs to happen in that situation.
1061  */
1062 void term_seen_key_event(Terminal *term)
1063 {
1064     /*
1065      * On any keypress, clear the bell overload mechanism
1066      * completely, on the grounds that large numbers of
1067      * beeps coming from deliberate key action are likely
1068      * to be intended (e.g. beeps from filename completion
1069      * blocking repeatedly).
1070      */
1071     term->beep_overloaded = FALSE;
1072     while (term->beephead) {
1073         struct beeptime *tmp = term->beephead;
1074         term->beephead = tmp->next;
1075         sfree(tmp);
1076     }
1077     term->beeptail = NULL;
1078     term->nbeeps = 0;
1079
1080     /*
1081      * Reset the scrollback on keypress, if we're doing that.
1082      */
1083     if (term->cfg.scroll_on_key) {
1084         term->disptop = 0;             /* return to main screen */
1085         term->seen_disp_event = 1;
1086     }
1087 }
1088
1089 /*
1090  * Same as power_on(), but an external function.
1091  */
1092 void term_pwron(Terminal *term)
1093 {
1094     power_on(term);
1095     if (term->ldisc)                   /* cause ldisc to notice changes */
1096         ldisc_send(term->ldisc, NULL, 0, 0);
1097     term->disptop = 0;
1098     deselect(term);
1099     term_update(term);
1100 }
1101
1102 static void set_erase_char(Terminal *term)
1103 {
1104     term->erase_char = term->basic_erase_char;
1105     if (term->use_bce)
1106         term->erase_char.attr = (term->curr_attr &
1107                                  (ATTR_FGMASK | ATTR_BGMASK));
1108 }
1109
1110 /*
1111  * When the user reconfigures us, we need to check the forbidden-
1112  * alternate-screen config option, disable raw mouse mode if the
1113  * user has disabled mouse reporting, and abandon a print job if
1114  * the user has disabled printing.
1115  */
1116 void term_reconfig(Terminal *term, Config *cfg)
1117 {
1118     /*
1119      * Before adopting the new config, check all those terminal
1120      * settings which control power-on defaults; and if they've
1121      * changed, we will modify the current state as well as the
1122      * default one. The full list is: Auto wrap mode, DEC Origin
1123      * Mode, BCE, blinking text, character classes.
1124      */
1125     int reset_wrap, reset_decom, reset_bce, reset_blink, reset_charclass;
1126     int i;
1127
1128     reset_wrap = (term->cfg.wrap_mode != cfg->wrap_mode);
1129     reset_decom = (term->cfg.dec_om != cfg->dec_om);
1130     reset_bce = (term->cfg.bce != cfg->bce);
1131     reset_blink = (term->cfg.blinktext != cfg->blinktext);
1132     reset_charclass = 0;
1133     for (i = 0; i < lenof(term->cfg.wordness); i++)
1134         if (term->cfg.wordness[i] != cfg->wordness[i])
1135             reset_charclass = 1;
1136
1137     /*
1138      * If the bidi or shaping settings have changed, flush the bidi
1139      * cache completely.
1140      */
1141     if (term->cfg.arabicshaping != cfg->arabicshaping ||
1142         term->cfg.bidi != cfg->bidi) {
1143         for (i = 0; i < term->bidi_cache_size; i++) {
1144             sfree(term->pre_bidi_cache[i].chars);
1145             sfree(term->post_bidi_cache[i].chars);
1146             term->pre_bidi_cache[i].width = -1;
1147             term->pre_bidi_cache[i].chars = NULL;
1148             term->post_bidi_cache[i].width = -1;
1149             term->post_bidi_cache[i].chars = NULL;
1150         }
1151     }
1152
1153     term->cfg = *cfg;                  /* STRUCTURE COPY */
1154
1155     if (reset_wrap)
1156         term->alt_wrap = term->wrap = term->cfg.wrap_mode;
1157     if (reset_decom)
1158         term->alt_om = term->dec_om = term->cfg.dec_om;
1159     if (reset_bce) {
1160         term->use_bce = term->cfg.bce;
1161         set_erase_char(term);
1162     }
1163     if (reset_blink)
1164         term->blink_is_real = term->cfg.blinktext;
1165     if (reset_charclass)
1166         for (i = 0; i < 256; i++)
1167             term->wordness[i] = term->cfg.wordness[i];
1168
1169     if (term->cfg.no_alt_screen)
1170         swap_screen(term, 0, FALSE, FALSE);
1171     if (term->cfg.no_mouse_rep) {
1172         term->xterm_mouse = 0;
1173         set_raw_mouse_mode(term->frontend, 0);
1174     }
1175     if (term->cfg.no_remote_charset) {
1176         term->cset_attr[0] = term->cset_attr[1] = CSET_ASCII;
1177         term->sco_acs = term->alt_sco_acs = 0;
1178         term->utf = 0;
1179     }
1180     if (!*term->cfg.printer) {
1181         term_print_finish(term);
1182     }
1183 }
1184
1185 /*
1186  * Clear the scrollback.
1187  */
1188 void term_clrsb(Terminal *term)
1189 {
1190     termline *line;
1191     term->disptop = 0;
1192     while ((line = delpos234(term->scrollback, 0)) != NULL) {
1193         sfree(line);            /* this is compressed data, not a termline */
1194     }
1195     term->tempsblines = 0;
1196     term->alt_sblines = 0;
1197     update_sbar(term);
1198 }
1199
1200 /*
1201  * Initialise the terminal.
1202  */
1203 Terminal *term_init(Config *mycfg, struct unicode_data *ucsdata,
1204                     void *frontend)
1205 {
1206     Terminal *term;
1207
1208     /*
1209      * Allocate a new Terminal structure and initialise the fields
1210      * that need it.
1211      */
1212     term = snew(Terminal);
1213     term->frontend = frontend;
1214     term->ucsdata = ucsdata;
1215     term->cfg = *mycfg;                /* STRUCTURE COPY */
1216     term->logctx = NULL;
1217     term->compatibility_level = TM_PUTTY;
1218     strcpy(term->id_string, "\033[?6c");
1219     term->last_blink = term->last_tblink = 0;
1220     term->paste_buffer = NULL;
1221     term->paste_len = 0;
1222     term->last_paste = 0;
1223     bufchain_init(&term->inbuf);
1224     bufchain_init(&term->printer_buf);
1225     term->printing = term->only_printing = FALSE;
1226     term->print_job = NULL;
1227     term->vt52_mode = FALSE;
1228     term->cr_lf_return = FALSE;
1229     term->seen_disp_event = FALSE;
1230     term->xterm_mouse = term->mouse_is_down = FALSE;
1231     term->reset_132 = FALSE;
1232     term->blinker = term->tblinker = 0;
1233     term->has_focus = 1;
1234     term->repeat_off = FALSE;
1235     term->termstate = TOPLEVEL;
1236     term->selstate = NO_SELECTION;
1237     term->curstype = 0;
1238
1239     term->screen = term->alt_screen = term->scrollback = NULL;
1240     term->tempsblines = 0;
1241     term->alt_sblines = 0;
1242     term->disptop = 0;
1243     term->disptext = NULL;
1244     term->dispcursx = term->dispcursy = -1;
1245     term->tabs = NULL;
1246     deselect(term);
1247     term->rows = term->cols = -1;
1248     power_on(term);
1249     term->beephead = term->beeptail = NULL;
1250 #ifdef OPTIMISE_SCROLL
1251     term->scrollhead = term->scrolltail = NULL;
1252 #endif /* OPTIMISE_SCROLL */
1253     term->nbeeps = 0;
1254     term->lastbeep = FALSE;
1255     term->beep_overloaded = FALSE;
1256     term->attr_mask = 0xffffffff;
1257     term->resize_fn = NULL;
1258     term->resize_ctx = NULL;
1259     term->in_term_out = FALSE;
1260     term->ltemp = NULL;
1261     term->ltemp_size = 0;
1262     term->wcFrom = NULL;
1263     term->wcTo = NULL;
1264     term->wcFromTo_size = 0;
1265
1266     term->bidi_cache_size = 0;
1267     term->pre_bidi_cache = term->post_bidi_cache = NULL;
1268
1269     /* FULL-TERMCHAR */
1270     term->basic_erase_char.chr = CSET_ASCII | ' ';
1271     term->basic_erase_char.attr = ATTR_DEFAULT;
1272     term->basic_erase_char.cc_next = 0;
1273     term->erase_char = term->basic_erase_char;
1274
1275     return term;
1276 }
1277
1278 void term_free(Terminal *term)
1279 {
1280     termline *line;
1281     struct beeptime *beep;
1282     int i;
1283
1284     while ((line = delpos234(term->scrollback, 0)) != NULL)
1285         sfree(line);                   /* compressed data, not a termline */
1286     freetree234(term->scrollback);
1287     while ((line = delpos234(term->screen, 0)) != NULL)
1288         freeline(line);
1289     freetree234(term->screen);
1290     while ((line = delpos234(term->alt_screen, 0)) != NULL)
1291         freeline(line);
1292     freetree234(term->alt_screen);
1293     if (term->disptext) {
1294         for (i = 0; i < term->rows; i++)
1295             freeline(term->disptext[i]);
1296     }
1297     sfree(term->disptext);
1298     while (term->beephead) {
1299         beep = term->beephead;
1300         term->beephead = beep->next;
1301         sfree(beep);
1302     }
1303     bufchain_clear(&term->inbuf);
1304     if(term->print_job)
1305         printer_finish_job(term->print_job);
1306     bufchain_clear(&term->printer_buf);
1307     sfree(term->paste_buffer);
1308     sfree(term->ltemp);
1309     sfree(term->wcFrom);
1310     sfree(term->wcTo);
1311
1312     for (i = 0; i < term->bidi_cache_size; i++) {
1313         sfree(term->pre_bidi_cache[i].chars);
1314         sfree(term->post_bidi_cache[i].chars);
1315     }
1316     sfree(term->pre_bidi_cache);
1317     sfree(term->post_bidi_cache);
1318
1319     sfree(term);
1320 }
1321
1322 /*
1323  * Set up the terminal for a given size.
1324  */
1325 void term_size(Terminal *term, int newrows, int newcols, int newsavelines)
1326 {
1327     tree234 *newalt;
1328     termline **newdisp, *line;
1329     int i, j, oldrows = term->rows;
1330     int sblen;
1331     int save_alt_which = term->alt_which;
1332
1333     if (newrows == term->rows && newcols == term->cols &&
1334         newsavelines == term->savelines)
1335         return;                        /* nothing to do */
1336
1337     deselect(term);
1338     swap_screen(term, 0, FALSE, FALSE);
1339
1340     term->alt_t = term->marg_t = 0;
1341     term->alt_b = term->marg_b = newrows - 1;
1342
1343     if (term->rows == -1) {
1344         term->scrollback = newtree234(NULL);
1345         term->screen = newtree234(NULL);
1346         term->tempsblines = 0;
1347         term->rows = 0;
1348     }
1349
1350     /*
1351      * Resize the screen and scrollback. We only need to shift
1352      * lines around within our data structures, because lineptr()
1353      * will take care of resizing each individual line if
1354      * necessary. So:
1355      * 
1356      *  - If the new screen is longer, we shunt lines in from temporary
1357      *    scrollback if possible, otherwise we add new blank lines at
1358      *    the bottom.
1359      *
1360      *  - If the new screen is shorter, we remove any blank lines at
1361      *    the bottom if possible, otherwise shunt lines above the cursor
1362      *    to scrollback if possible, otherwise delete lines below the
1363      *    cursor.
1364      * 
1365      *  - Then, if the new scrollback length is less than the
1366      *    amount of scrollback we actually have, we must throw some
1367      *    away.
1368      */
1369     sblen = count234(term->scrollback);
1370     /* Do this loop to expand the screen if newrows > rows */
1371     assert(term->rows == count234(term->screen));
1372     while (term->rows < newrows) {
1373         if (term->tempsblines > 0) {
1374             unsigned char *cline;
1375             /* Insert a line from the scrollback at the top of the screen. */
1376             assert(sblen >= term->tempsblines);
1377             cline = delpos234(term->scrollback, --sblen);
1378             line = decompressline(cline, NULL);
1379             sfree(cline);
1380             line->temporary = FALSE;   /* reconstituted line is now real */
1381             term->tempsblines -= 1;
1382             addpos234(term->screen, line, 0);
1383             term->curs.y += 1;
1384             term->savecurs.y += 1;
1385         } else {
1386             /* Add a new blank line at the bottom of the screen. */
1387             line = newline(term, newcols, FALSE);
1388             addpos234(term->screen, line, count234(term->screen));
1389         }
1390         term->rows += 1;
1391     }
1392     /* Do this loop to shrink the screen if newrows < rows */
1393     while (term->rows > newrows) {
1394         if (term->curs.y < term->rows - 1) {
1395             /* delete bottom row, unless it contains the cursor */
1396             sfree(delpos234(term->screen, term->rows - 1));
1397         } else {
1398             /* push top row to scrollback */
1399             line = delpos234(term->screen, 0);
1400             addpos234(term->scrollback, compressline(line), sblen++);
1401             freeline(line);
1402             term->tempsblines += 1;
1403             term->curs.y -= 1;
1404             term->savecurs.y -= 1;
1405         }
1406         term->rows -= 1;
1407     }
1408     assert(term->rows == newrows);
1409     assert(count234(term->screen) == newrows);
1410
1411     /* Delete any excess lines from the scrollback. */
1412     while (sblen > newsavelines) {
1413         line = delpos234(term->scrollback, 0);
1414         sfree(line);
1415         sblen--;
1416     }
1417     if (sblen < term->tempsblines)
1418         term->tempsblines = sblen;
1419     assert(count234(term->scrollback) <= newsavelines);
1420     assert(count234(term->scrollback) >= term->tempsblines);
1421     term->disptop = 0;
1422
1423     /* Make a new displayed text buffer. */
1424     newdisp = snewn(newrows, termline *);
1425     for (i = 0; i < newrows; i++) {
1426         newdisp[i] = newline(term, newcols, FALSE);
1427         for (j = 0; j < newcols; j++)
1428             newdisp[i]->chars[i].attr = ATTR_INVALID;
1429     }
1430     if (term->disptext) {
1431         for (i = 0; i < oldrows; i++)
1432             freeline(term->disptext[i]);
1433     }
1434     sfree(term->disptext);
1435     term->disptext = newdisp;
1436     term->dispcursx = term->dispcursy = -1;
1437
1438     /* Make a new alternate screen. */
1439     newalt = newtree234(NULL);
1440     for (i = 0; i < newrows; i++) {
1441         line = newline(term, newcols, TRUE);
1442         addpos234(newalt, line, i);
1443     }
1444     if (term->alt_screen) {
1445         while (NULL != (line = delpos234(term->alt_screen, 0)))
1446             freeline(line);
1447         freetree234(term->alt_screen);
1448     }
1449     term->alt_screen = newalt;
1450     term->alt_sblines = 0;
1451
1452     term->tabs = sresize(term->tabs, newcols, unsigned char);
1453     {
1454         int i;
1455         for (i = (term->cols > 0 ? term->cols : 0); i < newcols; i++)
1456             term->tabs[i] = (i % 8 == 0 ? TRUE : FALSE);
1457     }
1458
1459     /* Check that the cursor positions are still valid. */
1460     if (term->savecurs.y < 0)
1461         term->savecurs.y = 0;
1462     if (term->savecurs.y >= newrows)
1463         term->savecurs.y = newrows - 1;
1464     if (term->curs.y < 0)
1465         term->curs.y = 0;
1466     if (term->curs.y >= newrows)
1467         term->curs.y = newrows - 1;
1468     if (term->curs.x >= newcols)
1469         term->curs.x = newcols - 1;
1470     term->alt_x = term->alt_y = 0;
1471     term->wrapnext = term->alt_wnext = FALSE;
1472
1473     term->rows = newrows;
1474     term->cols = newcols;
1475     term->savelines = newsavelines;
1476
1477     swap_screen(term, save_alt_which, FALSE, FALSE);
1478
1479     update_sbar(term);
1480     term_update(term);
1481     if (term->resize_fn)
1482         term->resize_fn(term->resize_ctx, term->cols, term->rows);
1483 }
1484
1485 /*
1486  * Hand a function and context pointer to the terminal which it can
1487  * use to notify a back end of resizes.
1488  */
1489 void term_provide_resize_fn(Terminal *term,
1490                             void (*resize_fn)(void *, int, int),
1491                             void *resize_ctx)
1492 {
1493     term->resize_fn = resize_fn;
1494     term->resize_ctx = resize_ctx;
1495     if (term->cols > 0 && term->rows > 0)
1496         resize_fn(resize_ctx, term->cols, term->rows);
1497 }
1498
1499 /* Find the bottom line on the screen that has any content.
1500  * If only the top line has content, returns 0.
1501  * If no lines have content, return -1.
1502  */ 
1503 static int find_last_nonempty_line(Terminal * term, tree234 * screen)
1504 {
1505     int i;
1506     for (i = count234(screen) - 1; i >= 0; i--) {
1507         termline *line = index234(screen, i);
1508         int j;
1509         for (j = 0; j < line->cols; j++)
1510             if (!termchars_equal(&line->chars[j], &term->erase_char))
1511                 break;
1512         if (j != line->cols) break;
1513     }
1514     return i;
1515 }
1516
1517 /*
1518  * Swap screens. If `reset' is TRUE and we have been asked to
1519  * switch to the alternate screen, we must bring most of its
1520  * configuration from the main screen and erase the contents of the
1521  * alternate screen completely. (This is even true if we're already
1522  * on it! Blame xterm.)
1523  */
1524 static void swap_screen(Terminal *term, int which, int reset, int keep_cur_pos)
1525 {
1526     int t;
1527     tree234 *ttr;
1528
1529     if (!which)
1530         reset = FALSE;                 /* do no weird resetting if which==0 */
1531
1532     if (which != term->alt_which) {
1533         term->alt_which = which;
1534
1535         ttr = term->alt_screen;
1536         term->alt_screen = term->screen;
1537         term->screen = ttr;
1538         term->alt_sblines = find_last_nonempty_line(term, term->alt_screen) + 1;
1539         t = term->curs.x;
1540         if (!reset && !keep_cur_pos)
1541             term->curs.x = term->alt_x;
1542         term->alt_x = t;
1543         t = term->curs.y;
1544         if (!reset && !keep_cur_pos)
1545             term->curs.y = term->alt_y;
1546         term->alt_y = t;
1547         t = term->marg_t;
1548         if (!reset) term->marg_t = term->alt_t;
1549         term->alt_t = t;
1550         t = term->marg_b;
1551         if (!reset) term->marg_b = term->alt_b;
1552         term->alt_b = t;
1553         t = term->dec_om;
1554         if (!reset) term->dec_om = term->alt_om;
1555         term->alt_om = t;
1556         t = term->wrap;
1557         if (!reset) term->wrap = term->alt_wrap;
1558         term->alt_wrap = t;
1559         t = term->wrapnext;
1560         if (!reset) term->wrapnext = term->alt_wnext;
1561         term->alt_wnext = t;
1562         t = term->insert;
1563         if (!reset) term->insert = term->alt_ins;
1564         term->alt_ins = t;
1565         t = term->cset;
1566         if (!reset) term->cset = term->alt_cset;
1567         term->alt_cset = t;
1568         t = term->utf;
1569         if (!reset) term->utf = term->alt_utf;
1570         term->alt_utf = t;
1571         t = term->sco_acs;
1572         if (!reset) term->sco_acs = term->alt_sco_acs;
1573         term->alt_sco_acs = t;
1574     }
1575
1576     if (reset && term->screen) {
1577         /*
1578          * Yes, this _is_ supposed to honour background-colour-erase.
1579          */
1580         erase_lots(term, FALSE, TRUE, TRUE);
1581     }
1582 }
1583
1584 /*
1585  * Update the scroll bar.
1586  */
1587 static void update_sbar(Terminal *term)
1588 {
1589     int nscroll = sblines(term);
1590     set_sbar(term->frontend, nscroll + term->rows,
1591              nscroll + term->disptop, term->rows);
1592 }
1593
1594 /*
1595  * Check whether the region bounded by the two pointers intersects
1596  * the scroll region, and de-select the on-screen selection if so.
1597  */
1598 static void check_selection(Terminal *term, pos from, pos to)
1599 {
1600     if (poslt(from, term->selend) && poslt(term->selstart, to))
1601         deselect(term);
1602 }
1603
1604 /*
1605  * Scroll the screen. (`lines' is +ve for scrolling forward, -ve
1606  * for backward.) `sb' is TRUE if the scrolling is permitted to
1607  * affect the scrollback buffer.
1608  */
1609 static void scroll(Terminal *term, int topline, int botline, int lines, int sb)
1610 {
1611     termline *line;
1612     int i, seltop, olddisptop, shift;
1613
1614     if (topline != 0 || term->alt_which != 0)
1615         sb = FALSE;
1616
1617     olddisptop = term->disptop;
1618     shift = lines;
1619     if (lines < 0) {
1620         while (lines < 0) {
1621             line = delpos234(term->screen, botline);
1622             resizeline(term, line, term->cols);
1623             for (i = 0; i < term->cols; i++)
1624                 copy_termchar(line, i, &term->erase_char);
1625             line->lattr = LATTR_NORM;
1626             addpos234(term->screen, line, topline);
1627
1628             if (term->selstart.y >= topline && term->selstart.y <= botline) {
1629                 term->selstart.y++;
1630                 if (term->selstart.y > botline) {
1631                     term->selstart.y = botline + 1;
1632                     term->selstart.x = 0;
1633                 }
1634             }
1635             if (term->selend.y >= topline && term->selend.y <= botline) {
1636                 term->selend.y++;
1637                 if (term->selend.y > botline) {
1638                     term->selend.y = botline + 1;
1639                     term->selend.x = 0;
1640                 }
1641             }
1642
1643             lines++;
1644         }
1645     } else {
1646         while (lines > 0) {
1647             line = delpos234(term->screen, topline);
1648             cc_check(line);            /* XXX-REMOVE-BEFORE-RELEASE */
1649             if (sb && term->savelines > 0) {
1650                 int sblen = count234(term->scrollback);
1651                 /*
1652                  * We must add this line to the scrollback. We'll
1653                  * remove a line from the top of the scrollback if
1654                  * the scrollback is full.
1655                  */
1656                 if (sblen == term->savelines) {
1657                     unsigned char *cline;
1658
1659                     sblen--;
1660                     cline = delpos234(term->scrollback, 0);
1661                     sfree(cline);
1662                 } else
1663                     term->tempsblines += 1;
1664
1665                 addpos234(term->scrollback, compressline(line), sblen);
1666
1667                 line = newline(term, term->cols, TRUE);
1668
1669                 /*
1670                  * If the user is currently looking at part of the
1671                  * scrollback, and they haven't enabled any options
1672                  * that are going to reset the scrollback as a
1673                  * result of this movement, then the chances are
1674                  * they'd like to keep looking at the same line. So
1675                  * we move their viewpoint at the same rate as the
1676                  * scroll, at least until their viewpoint hits the
1677                  * top end of the scrollback buffer, at which point
1678                  * we don't have the choice any more.
1679                  * 
1680                  * Thanks to Jan Holmen Holsten for the idea and
1681                  * initial implementation.
1682                  */
1683                 if (term->disptop > -term->savelines && term->disptop < 0)
1684                     term->disptop--;
1685             }
1686             resizeline(term, line, term->cols);
1687             for (i = 0; i < term->cols; i++)
1688                 copy_termchar(line, i, &term->erase_char);
1689             line->lattr = LATTR_NORM;
1690             addpos234(term->screen, line, botline);
1691
1692             /*
1693              * If the selection endpoints move into the scrollback,
1694              * we keep them moving until they hit the top. However,
1695              * of course, if the line _hasn't_ moved into the
1696              * scrollback then we don't do this, and cut them off
1697              * at the top of the scroll region.
1698              * 
1699              * This applies to selstart and selend (for an existing
1700              * selection), and also selanchor (for one being
1701              * selected as we speak).
1702              */
1703             seltop = sb ? -term->savelines : topline;
1704
1705             if (term->selstate != NO_SELECTION) {
1706                 if (term->selstart.y >= seltop &&
1707                     term->selstart.y <= botline) {
1708                     term->selstart.y--;
1709                     if (term->selstart.y < seltop) {
1710                         term->selstart.y = seltop;
1711                         term->selstart.x = 0;
1712                     }
1713                 }
1714                 if (term->selend.y >= seltop && term->selend.y <= botline) {
1715                     term->selend.y--;
1716                     if (term->selend.y < seltop) {
1717                         term->selend.y = seltop;
1718                         term->selend.x = 0;
1719                     }
1720                 }
1721                 if (term->selanchor.y >= seltop &&
1722                     term->selanchor.y <= botline) {
1723                     term->selanchor.y--;
1724                     if (term->selanchor.y < seltop) {
1725                         term->selanchor.y = seltop;
1726                         term->selanchor.x = 0;
1727                     }
1728                 }
1729             }
1730
1731             lines--;
1732         }
1733     }
1734 #ifdef OPTIMISE_SCROLL
1735     shift += term->disptop - olddisptop;
1736     if (shift < term->rows && shift > -term->rows && shift != 0)
1737         scroll_display(term, topline, botline, shift);
1738 #endif /* OPTIMISE_SCROLL */
1739 }
1740
1741 #ifdef OPTIMISE_SCROLL
1742 /*
1743  * Add a scroll of a region on the screen into the pending scroll list.
1744  * `lines' is +ve for scrolling forward, -ve for backward.
1745  *
1746  * If the scroll is on the same area as the last scroll in the list,
1747  * merge them.
1748  */
1749 static void save_scroll(Terminal *term, int topline, int botline, int lines)
1750 {
1751     struct scrollregion *newscroll;
1752     if (term->scrolltail &&
1753         term->scrolltail->topline == topline && 
1754         term->scrolltail->botline == botline) {
1755         term->scrolltail->lines += lines;
1756     } else {
1757         newscroll = snew(struct scrollregion);
1758         newscroll->topline = topline;
1759         newscroll->botline = botline;
1760         newscroll->lines = lines;
1761         newscroll->next = NULL;
1762
1763         if (!term->scrollhead)
1764             term->scrollhead = newscroll;
1765         else
1766             term->scrolltail->next = newscroll;
1767         term->scrolltail = newscroll;
1768     }
1769 }
1770
1771 /*
1772  * Scroll the physical display, and our conception of it in disptext.
1773  */
1774 static void scroll_display(Terminal *term, int topline, int botline, int lines)
1775 {
1776     int distance, nlines, i, j;
1777
1778     distance = lines > 0 ? lines : -lines;
1779     nlines = botline - topline + 1 - distance;
1780     if (lines > 0) {
1781         for (i = 0; i < nlines; i++)
1782             for (j = 0; j < term->cols; j++)
1783                 copy_termchar(term->disptext[start+i], j,
1784                               term->disptext[start+i+distance]->chars+j);
1785         if (term->dispcursy >= 0 &&
1786             term->dispcursy >= topline + distance &&
1787             term->dispcursy < topline + distance + nlines)
1788             term->dispcursy -= distance;
1789         for (i = 0; i < distance; i++)
1790             for (j = 0; j < term->cols; j++)
1791                 term->disptext[start+nlines+i]->chars[j].attr |= ATTR_INVALID;
1792     } else {
1793         for (i = nlines; i-- ;)
1794             for (j = 0; j < term->cols; j++)
1795                 copy_termchar(term->disptext[start+i+distance], j,
1796                               term->disptext[start+i]->chars+j);
1797         if (term->dispcursy >= 0 &&
1798             term->dispcursy >= topline &&
1799             term->dispcursy < topline + nlines)
1800             term->dispcursy += distance;
1801         for (i = 0; i < distance; i++)
1802             for (j = 0; j < term->cols; j++)
1803                 term->disptext[start+i]->chars[j].attr |= ATTR_INVALID;
1804     }
1805     save_scroll(term, topline, botline, lines);
1806 }
1807 #endif /* OPTIMISE_SCROLL */
1808
1809 /*
1810  * Move the cursor to a given position, clipping at boundaries. We
1811  * may or may not want to clip at the scroll margin: marg_clip is 0
1812  * not to, 1 to disallow _passing_ the margins, and 2 to disallow
1813  * even _being_ outside the margins.
1814  */
1815 static void move(Terminal *term, int x, int y, int marg_clip)
1816 {
1817     if (x < 0)
1818         x = 0;
1819     if (x >= term->cols)
1820         x = term->cols - 1;
1821     if (marg_clip) {
1822         if ((term->curs.y >= term->marg_t || marg_clip == 2) &&
1823             y < term->marg_t)
1824             y = term->marg_t;
1825         if ((term->curs.y <= term->marg_b || marg_clip == 2) &&
1826             y > term->marg_b)
1827             y = term->marg_b;
1828     }
1829     if (y < 0)
1830         y = 0;
1831     if (y >= term->rows)
1832         y = term->rows - 1;
1833     term->curs.x = x;
1834     term->curs.y = y;
1835     term->wrapnext = FALSE;
1836 }
1837
1838 /*
1839  * Save or restore the cursor and SGR mode.
1840  */
1841 static void save_cursor(Terminal *term, int save)
1842 {
1843     if (save) {
1844         term->savecurs = term->curs;
1845         term->save_attr = term->curr_attr;
1846         term->save_cset = term->cset;
1847         term->save_utf = term->utf;
1848         term->save_wnext = term->wrapnext;
1849         term->save_csattr = term->cset_attr[term->cset];
1850         term->save_sco_acs = term->sco_acs;
1851     } else {
1852         term->curs = term->savecurs;
1853         /* Make sure the window hasn't shrunk since the save */
1854         if (term->curs.x >= term->cols)
1855             term->curs.x = term->cols - 1;
1856         if (term->curs.y >= term->rows)
1857             term->curs.y = term->rows - 1;
1858
1859         term->curr_attr = term->save_attr;
1860         term->cset = term->save_cset;
1861         term->utf = term->save_utf;
1862         term->wrapnext = term->save_wnext;
1863         /*
1864          * wrapnext might reset to False if the x position is no
1865          * longer at the rightmost edge.
1866          */
1867         if (term->wrapnext && term->curs.x < term->cols-1)
1868             term->wrapnext = FALSE;
1869         term->cset_attr[term->cset] = term->save_csattr;
1870         term->sco_acs = term->save_sco_acs;
1871         set_erase_char(term);
1872     }
1873 }
1874
1875 /*
1876  * This function is called before doing _anything_ which affects
1877  * only part of a line of text. It is used to mark the boundary
1878  * between two character positions, and it indicates that some sort
1879  * of effect is going to happen on only one side of that boundary.
1880  * 
1881  * The effect of this function is to check whether a CJK
1882  * double-width character is straddling the boundary, and to remove
1883  * it and replace it with two spaces if so. (Of course, one or
1884  * other of those spaces is then likely to be replaced with
1885  * something else again, as a result of whatever happens next.)
1886  * 
1887  * Also, if the boundary is at the right-hand _edge_ of the screen,
1888  * it implies something deliberate is being done to the rightmost
1889  * column position; hence we must clear LATTR_WRAPPED2.
1890  * 
1891  * The input to the function is the coordinates of the _second_
1892  * character of the pair.
1893  */
1894 static void check_boundary(Terminal *term, int x, int y)
1895 {
1896     termline *ldata;
1897
1898     /* Validate input coordinates, just in case. */
1899     if (x == 0 || x > term->cols)
1900         return;
1901
1902     ldata = scrlineptr(y);
1903     if (x == term->cols) {
1904         ldata->lattr &= ~LATTR_WRAPPED2;
1905     } else {
1906         if (ldata->chars[x].chr == UCSWIDE) {
1907             clear_cc(ldata, x-1);
1908             clear_cc(ldata, x);
1909             ldata->chars[x-1].chr = ' ' | CSET_ASCII;
1910             ldata->chars[x] = ldata->chars[x-1];
1911         }
1912     }
1913 }
1914
1915 /*
1916  * Erase a large portion of the screen: the whole screen, or the
1917  * whole line, or parts thereof.
1918  */
1919 static void erase_lots(Terminal *term,
1920                        int line_only, int from_begin, int to_end)
1921 {
1922     pos start, end;
1923     int erase_lattr;
1924     int erasing_lines_from_top = 0;
1925
1926     if (line_only) {
1927         start.y = term->curs.y;
1928         start.x = 0;
1929         end.y = term->curs.y + 1;
1930         end.x = 0;
1931         erase_lattr = FALSE;
1932     } else {
1933         start.y = 0;
1934         start.x = 0;
1935         end.y = term->rows;
1936         end.x = 0;
1937         erase_lattr = TRUE;
1938     }
1939     if (!from_begin) {
1940         start = term->curs;
1941     }
1942     if (!to_end) {
1943         end = term->curs;
1944         incpos(end);
1945     }
1946     if (!from_begin || !to_end)
1947         check_boundary(term, term->curs.x, term->curs.y);
1948     check_selection(term, start, end);
1949
1950     /* Clear screen also forces a full window redraw, just in case. */
1951     if (start.y == 0 && start.x == 0 && end.y == term->rows)
1952         term_invalidate(term);
1953
1954     /* Lines scrolled away shouldn't be brought back on if the terminal
1955      * resizes. */
1956     if (start.y == 0 && start.x == 0 && end.x == 0 && erase_lattr)
1957         erasing_lines_from_top = 1;
1958
1959     if (term->cfg.erase_to_scrollback && erasing_lines_from_top) {
1960         /* If it's a whole number of lines, starting at the top, and
1961          * we're fully erasing them, erase by scrolling and keep the
1962          * lines in the scrollback. */
1963         int scrolllines = end.y;
1964         if (end.y == term->rows) {
1965             /* Shrink until we find a non-empty row.*/
1966             scrolllines = find_last_nonempty_line(term, term->screen) + 1;
1967         }
1968         if (scrolllines > 0)
1969             scroll(term, 0, scrolllines - 1, scrolllines, TRUE);
1970     } else {
1971         termline *ldata = scrlineptr(start.y);
1972         while (poslt(start, end)) {
1973             if (start.x == term->cols) {
1974                 if (!erase_lattr)
1975                     ldata->lattr &= ~(LATTR_WRAPPED | LATTR_WRAPPED2);
1976                 else
1977                     ldata->lattr = LATTR_NORM;
1978             } else {
1979                 copy_termchar(ldata, start.x, &term->erase_char);
1980             }
1981             if (incpos(start) && start.y < term->rows) {
1982                 ldata = scrlineptr(start.y);
1983             }
1984         }
1985     }
1986
1987     /* After an erase of lines from the top of the screen, we shouldn't
1988      * bring the lines back again if the terminal enlarges (since the user or
1989      * application has explictly thrown them away). */
1990     if (erasing_lines_from_top && !(term->alt_which))
1991         term->tempsblines = 0;
1992 }
1993
1994 /*
1995  * Insert or delete characters within the current line. n is +ve if
1996  * insertion is desired, and -ve for deletion.
1997  */
1998 static void insch(Terminal *term, int n)
1999 {
2000     int dir = (n < 0 ? -1 : +1);
2001     int m, j;
2002     pos cursplus;
2003     termline *ldata;
2004
2005     n = (n < 0 ? -n : n);
2006     if (n > term->cols - term->curs.x)
2007         n = term->cols - term->curs.x;
2008     m = term->cols - term->curs.x - n;
2009     cursplus.y = term->curs.y;
2010     cursplus.x = term->curs.x + n;
2011     check_selection(term, term->curs, cursplus);
2012     check_boundary(term, term->curs.x, term->curs.y);
2013     if (dir < 0)
2014         check_boundary(term, term->curs.x + n, term->curs.y);
2015     ldata = scrlineptr(term->curs.y);
2016     if (dir < 0) {
2017         for (j = 0; j < m; j++)
2018             move_termchar(ldata,
2019                           ldata->chars + term->curs.x + j,
2020                           ldata->chars + term->curs.x + j + n);
2021         while (n--)
2022             copy_termchar(ldata, term->curs.x + m++, &term->erase_char);
2023     } else {
2024         for (j = m; j-- ;)
2025             move_termchar(ldata,
2026                           ldata->chars + term->curs.x + j + n,
2027                           ldata->chars + term->curs.x + j);
2028         while (n--)
2029             copy_termchar(ldata, term->curs.x + n, &term->erase_char);
2030     }
2031 }
2032
2033 /*
2034  * Toggle terminal mode `mode' to state `state'. (`query' indicates
2035  * whether the mode is a DEC private one or a normal one.)
2036  */
2037 static void toggle_mode(Terminal *term, int mode, int query, int state)
2038 {
2039     unsigned long ticks;
2040
2041     if (query)
2042         switch (mode) {
2043           case 1:                      /* DECCKM: application cursor keys */
2044             term->app_cursor_keys = state;
2045             break;
2046           case 2:                      /* DECANM: VT52 mode */
2047             term->vt52_mode = !state;
2048             if (term->vt52_mode) {
2049                 term->blink_is_real = FALSE;
2050                 term->vt52_bold = FALSE;
2051             } else {
2052                 term->blink_is_real = term->cfg.blinktext;
2053             }
2054             break;
2055           case 3:                      /* DECCOLM: 80/132 columns */
2056             deselect(term);
2057             if (!term->cfg.no_remote_resize)
2058                 request_resize(term->frontend, state ? 132 : 80, term->rows);
2059             term->reset_132 = state;
2060             term->alt_t = term->marg_t = 0;
2061             term->alt_b = term->marg_b = term->rows - 1;
2062             move(term, 0, 0, 0);
2063             erase_lots(term, FALSE, TRUE, TRUE);
2064             break;
2065           case 5:                      /* DECSCNM: reverse video */
2066             /*
2067              * Toggle reverse video. If we receive an OFF within the
2068              * visual bell timeout period after an ON, we trigger an
2069              * effective visual bell, so that ESC[?5hESC[?5l will
2070              * always be an actually _visible_ visual bell.
2071              */
2072             ticks = GETTICKCOUNT();
2073             /* turn off a previous vbell to avoid inconsistencies */
2074             if (ticks - term->vbell_startpoint >= VBELL_TIMEOUT)
2075                 term->in_vbell = FALSE;
2076             if (term->rvideo && !state &&    /* we're turning it off... */
2077                 (ticks - term->rvbell_startpoint) < VBELL_TIMEOUT) {/*...soon*/
2078                 /* If there's no vbell timeout already, or this one lasts
2079                  * longer, replace vbell_timeout with ours. */
2080                 if (!term->in_vbell ||
2081                     (term->rvbell_startpoint - term->vbell_startpoint <
2082                      VBELL_TIMEOUT))
2083                     term->vbell_startpoint = term->rvbell_startpoint;
2084                 term->in_vbell = TRUE; /* may clear rvideo but set in_vbell */
2085             } else if (!term->rvideo && state) {
2086                 /* This is an ON, so we notice the time and save it. */
2087                 term->rvbell_startpoint = ticks;
2088             }
2089             term->rvideo = state;
2090             term->seen_disp_event = TRUE;
2091             if (state)
2092                 term_update(term);
2093             break;
2094           case 6:                      /* DECOM: DEC origin mode */
2095             term->dec_om = state;
2096             break;
2097           case 7:                      /* DECAWM: auto wrap */
2098             term->wrap = state;
2099             break;
2100           case 8:                      /* DECARM: auto key repeat */
2101             term->repeat_off = !state;
2102             break;
2103           case 10:                     /* DECEDM: set local edit mode */
2104             term->term_editing = state;
2105             if (term->ldisc)           /* cause ldisc to notice changes */
2106                 ldisc_send(term->ldisc, NULL, 0, 0);
2107             break;
2108           case 25:                     /* DECTCEM: enable/disable cursor */
2109             compatibility2(OTHER, VT220);
2110             term->cursor_on = state;
2111             term->seen_disp_event = TRUE;
2112             break;
2113           case 47:                     /* alternate screen */
2114             compatibility(OTHER);
2115             deselect(term);
2116             swap_screen(term, term->cfg.no_alt_screen ? 0 : state, FALSE, FALSE);
2117             term->disptop = 0;
2118             break;
2119           case 1000:                   /* xterm mouse 1 */
2120             term->xterm_mouse = state ? 1 : 0;
2121             set_raw_mouse_mode(term->frontend, state);
2122             break;
2123           case 1002:                   /* xterm mouse 2 */
2124             term->xterm_mouse = state ? 2 : 0;
2125             set_raw_mouse_mode(term->frontend, state);
2126             break;
2127           case 1047:                   /* alternate screen */
2128             compatibility(OTHER);
2129             deselect(term);
2130             swap_screen(term, term->cfg.no_alt_screen ? 0 : state, TRUE, TRUE);
2131             term->disptop = 0;
2132             break;
2133           case 1048:                   /* save/restore cursor */
2134             if (!term->cfg.no_alt_screen)
2135                 save_cursor(term, state);
2136             if (!state) term->seen_disp_event = TRUE;
2137             break;
2138           case 1049:                   /* cursor & alternate screen */
2139             if (state && !term->cfg.no_alt_screen)
2140                 save_cursor(term, state);
2141             if (!state) term->seen_disp_event = TRUE;
2142             compatibility(OTHER);
2143             deselect(term);
2144             swap_screen(term, term->cfg.no_alt_screen ? 0 : state, TRUE, FALSE);
2145             if (!state && !term->cfg.no_alt_screen)
2146                 save_cursor(term, state);
2147             term->disptop = 0;
2148             break;
2149     } else
2150         switch (mode) {
2151           case 4:                      /* IRM: set insert mode */
2152             compatibility(VT102);
2153             term->insert = state;
2154             break;
2155           case 12:                     /* SRM: set echo mode */
2156             term->term_echoing = !state;
2157             if (term->ldisc)           /* cause ldisc to notice changes */
2158                 ldisc_send(term->ldisc, NULL, 0, 0);
2159             break;
2160           case 20:                     /* LNM: Return sends ... */
2161             term->cr_lf_return = state;
2162             break;
2163           case 34:                     /* WYULCURM: Make cursor BIG */
2164             compatibility2(OTHER, VT220);
2165             term->big_cursor = !state;
2166         }
2167 }
2168
2169 /*
2170  * Process an OSC sequence: set window title or icon name.
2171  */
2172 static void do_osc(Terminal *term)
2173 {
2174     if (term->osc_w) {
2175         while (term->osc_strlen--)
2176             term->wordness[(unsigned char)
2177                 term->osc_string[term->osc_strlen]] = term->esc_args[0];
2178     } else {
2179         term->osc_string[term->osc_strlen] = '\0';
2180         switch (term->esc_args[0]) {
2181           case 0:
2182           case 1:
2183             if (!term->cfg.no_remote_wintitle)
2184                 set_icon(term->frontend, term->osc_string);
2185             if (term->esc_args[0] == 1)
2186                 break;
2187             /* fall through: parameter 0 means set both */
2188           case 2:
2189           case 21:
2190             if (!term->cfg.no_remote_wintitle)
2191                 set_title(term->frontend, term->osc_string);
2192             break;
2193         }
2194     }
2195 }
2196
2197 /*
2198  * ANSI printing routines.
2199  */
2200 static void term_print_setup(Terminal *term)
2201 {
2202     bufchain_clear(&term->printer_buf);
2203     term->print_job = printer_start_job(term->cfg.printer);
2204 }
2205 static void term_print_flush(Terminal *term)
2206 {
2207     void *data;
2208     int len;
2209     int size;
2210     while ((size = bufchain_size(&term->printer_buf)) > 5) {
2211         bufchain_prefix(&term->printer_buf, &data, &len);
2212         if (len > size-5)
2213             len = size-5;
2214         printer_job_data(term->print_job, data, len);
2215         bufchain_consume(&term->printer_buf, len);
2216     }
2217 }
2218 static void term_print_finish(Terminal *term)
2219 {
2220     void *data;
2221     int len, size;
2222     char c;
2223
2224     if (!term->printing && !term->only_printing)
2225         return;                        /* we need do nothing */
2226
2227     term_print_flush(term);
2228     while ((size = bufchain_size(&term->printer_buf)) > 0) {
2229         bufchain_prefix(&term->printer_buf, &data, &len);
2230         c = *(char *)data;
2231         if (c == '\033' || c == '\233') {
2232             bufchain_consume(&term->printer_buf, size);
2233             break;
2234         } else {
2235             printer_job_data(term->print_job, &c, 1);
2236             bufchain_consume(&term->printer_buf, 1);
2237         }
2238     }
2239     printer_finish_job(term->print_job);
2240     term->print_job = NULL;
2241     term->printing = term->only_printing = FALSE;
2242 }
2243
2244 /*
2245  * Remove everything currently in `inbuf' and stick it up on the
2246  * in-memory display. There's a big state machine in here to
2247  * process escape sequences...
2248  */
2249 void term_out(Terminal *term)
2250 {
2251     unsigned long c;
2252     int unget;
2253     unsigned char localbuf[256], *chars;
2254     int nchars = 0;
2255
2256     unget = -1;
2257
2258     chars = NULL;                      /* placate compiler warnings */
2259     while (nchars > 0 || bufchain_size(&term->inbuf) > 0) {
2260         if (unget == -1) {
2261             if (nchars == 0) {
2262                 void *ret;
2263                 bufchain_prefix(&term->inbuf, &ret, &nchars);
2264                 if (nchars > sizeof(localbuf))
2265                     nchars = sizeof(localbuf);
2266                 memcpy(localbuf, ret, nchars);
2267                 bufchain_consume(&term->inbuf, nchars);
2268                 chars = localbuf;
2269                 assert(chars != NULL);
2270             }
2271             c = *chars++;
2272             nchars--;
2273
2274             /*
2275              * Optionally log the session traffic to a file. Useful for
2276              * debugging and possibly also useful for actual logging.
2277              */
2278             if (term->cfg.logtype == LGTYP_DEBUG && term->logctx)
2279                 logtraffic(term->logctx, (unsigned char) c, LGTYP_DEBUG);
2280         } else {
2281             c = unget;
2282             unget = -1;
2283         }
2284
2285         /* Note only VT220+ are 8-bit VT102 is seven bit, it shouldn't even
2286          * be able to display 8-bit characters, but I'll let that go 'cause
2287          * of i18n.
2288          */
2289
2290         /*
2291          * If we're printing, add the character to the printer
2292          * buffer.
2293          */
2294         if (term->printing) {
2295             bufchain_add(&term->printer_buf, &c, 1);
2296
2297             /*
2298              * If we're in print-only mode, we use a much simpler
2299              * state machine designed only to recognise the ESC[4i
2300              * termination sequence.
2301              */
2302             if (term->only_printing) {
2303                 if (c == '\033')
2304                     term->print_state = 1;
2305                 else if (c == (unsigned char)'\233')
2306                     term->print_state = 2;
2307                 else if (c == '[' && term->print_state == 1)
2308                     term->print_state = 2;
2309                 else if (c == '4' && term->print_state == 2)
2310                     term->print_state = 3;
2311                 else if (c == 'i' && term->print_state == 3)
2312                     term->print_state = 4;
2313                 else
2314                     term->print_state = 0;
2315                 if (term->print_state == 4) {
2316                     term_print_finish(term);
2317                 }
2318                 continue;
2319             }
2320         }
2321
2322         /* First see about all those translations. */
2323         if (term->termstate == TOPLEVEL) {
2324             if (in_utf(term))
2325                 switch (term->utf_state) {
2326                   case 0:
2327                     if (c < 0x80) {
2328                         /* UTF-8 must be stateless so we ignore iso2022. */
2329                         if (term->ucsdata->unitab_ctrl[c] != 0xFF) 
2330                              c = term->ucsdata->unitab_ctrl[c];
2331                         else c = ((unsigned char)c) | CSET_ASCII;
2332                         break;
2333                     } else if ((c & 0xe0) == 0xc0) {
2334                         term->utf_size = term->utf_state = 1;
2335                         term->utf_char = (c & 0x1f);
2336                     } else if ((c & 0xf0) == 0xe0) {
2337                         term->utf_size = term->utf_state = 2;
2338                         term->utf_char = (c & 0x0f);
2339                     } else if ((c & 0xf8) == 0xf0) {
2340                         term->utf_size = term->utf_state = 3;
2341                         term->utf_char = (c & 0x07);
2342                     } else if ((c & 0xfc) == 0xf8) {
2343                         term->utf_size = term->utf_state = 4;
2344                         term->utf_char = (c & 0x03);
2345                     } else if ((c & 0xfe) == 0xfc) {
2346                         term->utf_size = term->utf_state = 5;
2347                         term->utf_char = (c & 0x01);
2348                     } else {
2349                         c = UCSERR;
2350                         break;
2351                     }
2352                     continue;
2353                   case 1:
2354                   case 2:
2355                   case 3:
2356                   case 4:
2357                   case 5:
2358                     if ((c & 0xC0) != 0x80) {
2359                         unget = c;
2360                         c = UCSERR;
2361                         term->utf_state = 0;
2362                         break;
2363                     }
2364                     term->utf_char = (term->utf_char << 6) | (c & 0x3f);
2365                     if (--term->utf_state)
2366                         continue;
2367
2368                     c = term->utf_char;
2369
2370                     /* Is somebody trying to be evil! */
2371                     if (c < 0x80 ||
2372                         (c < 0x800 && term->utf_size >= 2) ||
2373                         (c < 0x10000 && term->utf_size >= 3) ||
2374                         (c < 0x200000 && term->utf_size >= 4) ||
2375                         (c < 0x4000000 && term->utf_size >= 5))
2376                         c = UCSERR;
2377
2378                     /* Unicode line separator and paragraph separator are CR-LF */
2379                     if (c == 0x2028 || c == 0x2029)
2380                         c = 0x85;
2381
2382                     /* High controls are probably a Baaad idea too. */
2383                     if (c < 0xA0)
2384                         c = 0xFFFD;
2385
2386                     /* The UTF-16 surrogates are not nice either. */
2387                     /*       The standard give the option of decoding these: 
2388                      *       I don't want to! */
2389                     if (c >= 0xD800 && c < 0xE000)
2390                         c = UCSERR;
2391
2392                     /* ISO 10646 characters now limited to UTF-16 range. */
2393                     if (c > 0x10FFFF)
2394                         c = UCSERR;
2395
2396                     /* This is currently a TagPhobic application.. */
2397                     if (c >= 0xE0000 && c <= 0xE007F)
2398                         continue;
2399
2400                     /* U+FEFF is best seen as a null. */
2401                     if (c == 0xFEFF)
2402                         continue;
2403                     /* But U+FFFE is an error. */
2404                     if (c == 0xFFFE || c == 0xFFFF)
2405                         c = UCSERR;
2406
2407                     break;
2408             }
2409             /* Are we in the nasty ACS mode? Note: no sco in utf mode. */
2410             else if(term->sco_acs && 
2411                     (c!='\033' && c!='\012' && c!='\015' && c!='\b'))
2412             {
2413                if (term->sco_acs == 2) c |= 0x80;
2414                c |= CSET_SCOACS;
2415             } else {
2416                 switch (term->cset_attr[term->cset]) {
2417                     /* 
2418                      * Linedraw characters are different from 'ESC ( B'
2419                      * only for a small range. For ones outside that
2420                      * range, make sure we use the same font as well as
2421                      * the same encoding.
2422                      */
2423                   case CSET_LINEDRW:
2424                     if (term->ucsdata->unitab_ctrl[c] != 0xFF)
2425                         c = term->ucsdata->unitab_ctrl[c];
2426                     else
2427                         c = ((unsigned char) c) | CSET_LINEDRW;
2428                     break;
2429
2430                   case CSET_GBCHR:
2431                     /* If UK-ASCII, make the '#' a LineDraw Pound */
2432                     if (c == '#') {
2433                         c = '}' | CSET_LINEDRW;
2434                         break;
2435                     }
2436                   /*FALLTHROUGH*/ case CSET_ASCII:
2437                     if (term->ucsdata->unitab_ctrl[c] != 0xFF)
2438                         c = term->ucsdata->unitab_ctrl[c];
2439                     else
2440                         c = ((unsigned char) c) | CSET_ASCII;
2441                     break;
2442                 case CSET_SCOACS:
2443                     if (c>=' ') c = ((unsigned char)c) | CSET_SCOACS;
2444                     break;
2445                 }
2446             }
2447         }
2448
2449         /* How about C1 controls ? */
2450         if ((c & -32) == 0x80 && term->termstate < DO_CTRLS &&
2451             !term->vt52_mode && has_compat(VT220)) {
2452             term->termstate = SEEN_ESC;
2453             term->esc_query = FALSE;
2454             c = '@' + (c & 0x1F);
2455         }
2456
2457         /* Or the GL control. */
2458         if (c == '\177' && term->termstate < DO_CTRLS && has_compat(OTHER)) {
2459             if (term->curs.x && !term->wrapnext)
2460                 term->curs.x--;
2461             term->wrapnext = FALSE;
2462             /* destructive backspace might be disabled */
2463             if (!term->cfg.no_dbackspace) {
2464                 copy_termchar(scrlineptr(term->curs.y),
2465                               term->curs.x, &term->erase_char);
2466             }
2467         } else
2468             /* Or normal C0 controls. */
2469         if ((c & ~0x1F) == 0 && term->termstate < DO_CTRLS) {
2470             switch (c) {
2471               case '\005':             /* ENQ: terminal type query */
2472                 /* Strictly speaking this is VT100 but a VT100 defaults to
2473                  * no response. Other terminals respond at their option.
2474                  *
2475                  * Don't put a CR in the default string as this tends to
2476                  * upset some weird software.
2477                  *
2478                  * An xterm returns "xterm" (5 characters)
2479                  */
2480                 compatibility(ANSIMIN);
2481                 if (term->ldisc) {
2482                     char abuf[256], *s, *d;
2483                     int state = 0;
2484                     for (s = term->cfg.answerback, d = abuf; *s; s++) {
2485                         if (state) {
2486                             if (*s >= 'a' && *s <= 'z')
2487                                 *d++ = (*s - ('a' - 1));
2488                             else if ((*s >= '@' && *s <= '_') ||
2489                                      *s == '?' || (*s & 0x80))
2490                                 *d++ = ('@' ^ *s);
2491                             else if (*s == '~')
2492                                 *d++ = '^';
2493                             state = 0;
2494                         } else if (*s == '^') {
2495                             state = 1;
2496                         } else
2497                             *d++ = *s;
2498                     }
2499                     lpage_send(term->ldisc, DEFAULT_CODEPAGE,
2500                                abuf, d - abuf, 0);
2501                 }
2502                 break;
2503               case '\007':            /* BEL: Bell */
2504                 {
2505                     struct beeptime *newbeep;
2506                     unsigned long ticks;
2507
2508                     ticks = GETTICKCOUNT();
2509
2510                     if (!term->beep_overloaded) {
2511                         newbeep = snew(struct beeptime);
2512                         newbeep->ticks = ticks;
2513                         newbeep->next = NULL;
2514                         if (!term->beephead)
2515                             term->beephead = newbeep;
2516                         else
2517                             term->beeptail->next = newbeep;
2518                         term->beeptail = newbeep;
2519                         term->nbeeps++;
2520                     }
2521
2522                     /*
2523                      * Throw out any beeps that happened more than
2524                      * t seconds ago.
2525                      */
2526                     while (term->beephead &&
2527                            term->beephead->ticks < ticks - term->cfg.bellovl_t) {
2528                         struct beeptime *tmp = term->beephead;
2529                         term->beephead = tmp->next;
2530                         sfree(tmp);
2531                         if (!term->beephead)
2532                             term->beeptail = NULL;
2533                         term->nbeeps--;
2534                     }
2535
2536                     if (term->cfg.bellovl && term->beep_overloaded &&
2537                         ticks - term->lastbeep >= (unsigned)term->cfg.bellovl_s) {
2538                         /*
2539                          * If we're currently overloaded and the
2540                          * last beep was more than s seconds ago,
2541                          * leave overload mode.
2542                          */
2543                         term->beep_overloaded = FALSE;
2544                     } else if (term->cfg.bellovl && !term->beep_overloaded &&
2545                                term->nbeeps >= term->cfg.bellovl_n) {
2546                         /*
2547                          * Now, if we have n or more beeps
2548                          * remaining in the queue, go into overload
2549                          * mode.
2550                          */
2551                         term->beep_overloaded = TRUE;
2552                     }
2553                     term->lastbeep = ticks;
2554
2555                     /*
2556                      * Perform an actual beep if we're not overloaded.
2557                      */
2558                     if (!term->cfg.bellovl || !term->beep_overloaded) {
2559                         beep(term->frontend, term->cfg.beep);
2560                         if (term->cfg.beep == BELL_VISUAL) {
2561                             term->in_vbell = TRUE;
2562                             term->vbell_startpoint = ticks;
2563                             term_update(term);
2564                         }
2565                     }
2566                     term->seen_disp_event = TRUE;
2567                 }
2568                 break;
2569               case '\b':              /* BS: Back space */
2570                 if (term->curs.x == 0 &&
2571                     (term->curs.y == 0 || term->wrap == 0))
2572                     /* do nothing */ ;
2573                 else if (term->curs.x == 0 && term->curs.y > 0)
2574                     term->curs.x = term->cols - 1, term->curs.y--;
2575                 else if (term->wrapnext)
2576                     term->wrapnext = FALSE;
2577                 else
2578                     term->curs.x--;
2579                 term->seen_disp_event = TRUE;
2580                 break;
2581               case '\016':            /* LS1: Locking-shift one */
2582                 compatibility(VT100);
2583                 term->cset = 1;
2584                 break;
2585               case '\017':            /* LS0: Locking-shift zero */
2586                 compatibility(VT100);
2587                 term->cset = 0;
2588                 break;
2589               case '\033':            /* ESC: Escape */
2590                 if (term->vt52_mode)
2591                     term->termstate = VT52_ESC;
2592                 else {
2593                     compatibility(ANSIMIN);
2594                     term->termstate = SEEN_ESC;
2595                     term->esc_query = FALSE;
2596                 }
2597                 break;
2598               case '\015':            /* CR: Carriage return */
2599                 term->curs.x = 0;
2600                 term->wrapnext = FALSE;
2601                 term->seen_disp_event = TRUE;
2602                 term->paste_hold = 0;
2603                 if (term->logctx)
2604                     logtraffic(term->logctx, (unsigned char) c, LGTYP_ASCII);
2605                 break;
2606               case '\014':            /* FF: Form feed */
2607                 if (has_compat(SCOANSI)) {
2608                     move(term, 0, 0, 0);
2609                     erase_lots(term, FALSE, FALSE, TRUE);
2610                     term->disptop = 0;
2611                     term->wrapnext = FALSE;
2612                     term->seen_disp_event = 1;
2613                     break;
2614                 }
2615               case '\013':            /* VT: Line tabulation */
2616                 compatibility(VT100);
2617               case '\012':            /* LF: Line feed */
2618                 if (term->curs.y == term->marg_b)
2619                     scroll(term, term->marg_t, term->marg_b, 1, TRUE);
2620                 else if (term->curs.y < term->rows - 1)
2621                     term->curs.y++;
2622                 if (term->cfg.lfhascr)
2623                     term->curs.x = 0;
2624                 term->wrapnext = FALSE;
2625                 term->seen_disp_event = 1;
2626                 term->paste_hold = 0;
2627                 if (term->logctx)
2628                     logtraffic(term->logctx, (unsigned char) c, LGTYP_ASCII);
2629                 break;
2630               case '\t':              /* HT: Character tabulation */
2631                 {
2632                     pos old_curs = term->curs;
2633                     termline *ldata = scrlineptr(term->curs.y);
2634
2635                     do {
2636                         term->curs.x++;
2637                     } while (term->curs.x < term->cols - 1 &&
2638                              !term->tabs[term->curs.x]);
2639
2640                     if ((ldata->lattr & LATTR_MODE) != LATTR_NORM) {
2641                         if (term->curs.x >= term->cols / 2)
2642                             term->curs.x = term->cols / 2 - 1;
2643                     } else {
2644                         if (term->curs.x >= term->cols)
2645                             term->curs.x = term->cols - 1;
2646                     }
2647
2648                     check_selection(term, old_curs, term->curs);
2649                 }
2650                 term->seen_disp_event = TRUE;
2651                 break;
2652             }
2653         } else
2654             switch (term->termstate) {
2655               case TOPLEVEL:
2656                 /* Only graphic characters get this far;
2657                  * ctrls are stripped above */
2658                 {
2659                     termline *cline = scrlineptr(term->curs.y);
2660                     int width = 0;
2661                     if (DIRECT_CHAR(c))
2662                         width = 1;
2663                     if (!width)
2664                         width = wcwidth((wchar_t) c);
2665
2666                     if (term->wrapnext && term->wrap && width > 0) {
2667                         cline->lattr |= LATTR_WRAPPED;
2668                         if (term->curs.y == term->marg_b)
2669                             scroll(term, term->marg_t, term->marg_b, 1, TRUE);
2670                         else if (term->curs.y < term->rows - 1)
2671                             term->curs.y++;
2672                         term->curs.x = 0;
2673                         term->wrapnext = FALSE;
2674                         cline = scrlineptr(term->curs.y);
2675                     }
2676                     if (term->insert && width > 0)
2677                         insch(term, width);
2678                     if (term->selstate != NO_SELECTION) {
2679                         pos cursplus = term->curs;
2680                         incpos(cursplus);
2681                         check_selection(term, term->curs, cursplus);
2682                     }
2683                     if (((c & CSET_MASK) == CSET_ASCII ||
2684                          (c & CSET_MASK) == 0) &&
2685                         term->logctx)
2686                         logtraffic(term->logctx, (unsigned char) c,
2687                                    LGTYP_ASCII);
2688
2689                     switch (width) {
2690                       case 2:
2691                         /*
2692                          * If we're about to display a double-width
2693                          * character starting in the rightmost
2694                          * column, then we do something special
2695                          * instead. We must print a space in the
2696                          * last column of the screen, then wrap;
2697                          * and we also set LATTR_WRAPPED2 which
2698                          * instructs subsequent cut-and-pasting not
2699                          * only to splice this line to the one
2700                          * after it, but to ignore the space in the
2701                          * last character position as well.
2702                          * (Because what was actually output to the
2703                          * terminal was presumably just a sequence
2704                          * of CJK characters, and we don't want a
2705                          * space to be pasted in the middle of
2706                          * those just because they had the
2707                          * misfortune to start in the wrong parity
2708                          * column. xterm concurs.)
2709                          */
2710                         check_boundary(term, term->curs.x, term->curs.y);
2711                         check_boundary(term, term->curs.x+2, term->curs.y);
2712                         if (term->curs.x == term->cols-1) {
2713                             copy_termchar(cline, term->curs.x,
2714                                           &term->erase_char);
2715                             cline->lattr |= LATTR_WRAPPED | LATTR_WRAPPED2;
2716                             if (term->curs.y == term->marg_b)
2717                                 scroll(term, term->marg_t, term->marg_b,
2718                                        1, TRUE);
2719                             else if (term->curs.y < term->rows - 1)
2720                                 term->curs.y++;
2721                             term->curs.x = 0;
2722                             /* Now we must check_boundary again, of course. */
2723                             check_boundary(term, term->curs.x, term->curs.y);
2724                             check_boundary(term, term->curs.x+2, term->curs.y);
2725                         }
2726
2727                         /* FULL-TERMCHAR */
2728                         clear_cc(cline, term->curs.x);
2729                         cline->chars[term->curs.x].chr = c;
2730                         cline->chars[term->curs.x].attr = term->curr_attr;
2731
2732                         term->curs.x++;
2733
2734                         /* FULL-TERMCHAR */
2735                         clear_cc(cline, term->curs.x);
2736                         cline->chars[term->curs.x].chr = UCSWIDE;
2737                         cline->chars[term->curs.x].attr = term->curr_attr;
2738
2739                         break;
2740                       case 1:
2741                         check_boundary(term, term->curs.x, term->curs.y);
2742                         check_boundary(term, term->curs.x+1, term->curs.y);
2743
2744                         /* FULL-TERMCHAR */
2745                         clear_cc(cline, term->curs.x);
2746                         cline->chars[term->curs.x].chr = c;
2747                         cline->chars[term->curs.x].attr = term->curr_attr;
2748
2749                         break;
2750                       case 0:
2751                         if (term->curs.x > 0) {
2752                             int x = term->curs.x - 1;
2753
2754                             /* If we're in wrapnext state, the character
2755                              * to combine with is _here_, not to our left. */
2756                             if (term->wrapnext)
2757                                 x++;
2758
2759                             /*
2760                              * If the previous character is
2761                              * UCSWIDE, back up another one.
2762                              */
2763                             if (cline->chars[x].chr == UCSWIDE) {
2764                                 assert(x > 0);
2765                                 x--;
2766                             }
2767
2768                             add_cc(cline, x, c);
2769                             term->seen_disp_event = 1;
2770                         }
2771                         continue;
2772                       default:
2773                         continue;
2774                     }
2775                     term->curs.x++;
2776                     if (term->curs.x == term->cols) {
2777                         term->curs.x--;
2778                         term->wrapnext = TRUE;
2779                         if (term->wrap && term->vt52_mode) {
2780                             cline->lattr |= LATTR_WRAPPED;
2781                             if (term->curs.y == term->marg_b)
2782                                 scroll(term, term->marg_t, term->marg_b, 1, TRUE);
2783                             else if (term->curs.y < term->rows - 1)
2784                                 term->curs.y++;
2785                             term->curs.x = 0;
2786                             term->wrapnext = FALSE;
2787                         }
2788                     }
2789                     term->seen_disp_event = 1;
2790                 }
2791                 break;
2792
2793               case OSC_MAYBE_ST:
2794                 /*
2795                  * This state is virtually identical to SEEN_ESC, with the
2796                  * exception that we have an OSC sequence in the pipeline,
2797                  * and _if_ we see a backslash, we process it.
2798                  */
2799                 if (c == '\\') {
2800                     do_osc(term);
2801                     term->termstate = TOPLEVEL;
2802                     break;
2803                 }
2804                 /* else fall through */
2805               case SEEN_ESC:
2806                 if (c >= ' ' && c <= '/') {
2807                     if (term->esc_query)
2808                         term->esc_query = -1;
2809                     else
2810                         term->esc_query = c;
2811                     break;
2812                 }
2813                 term->termstate = TOPLEVEL;
2814                 switch (ANSI(c, term->esc_query)) {
2815                   case '[':             /* enter CSI mode */
2816                     term->termstate = SEEN_CSI;
2817                     term->esc_nargs = 1;
2818                     term->esc_args[0] = ARG_DEFAULT;
2819                     term->esc_query = FALSE;
2820                     break;
2821                   case ']':             /* OSC: xterm escape sequences */
2822                     /* Compatibility is nasty here, xterm, linux, decterm yuk! */
2823                     compatibility(OTHER);
2824                     term->termstate = SEEN_OSC;
2825                     term->esc_args[0] = 0;
2826                     break;
2827                   case '7':             /* DECSC: save cursor */
2828                     compatibility(VT100);
2829                     save_cursor(term, TRUE);
2830                     break;
2831                   case '8':             /* DECRC: restore cursor */
2832                     compatibility(VT100);
2833                     save_cursor(term, FALSE);
2834                     term->seen_disp_event = TRUE;
2835                     break;
2836                   case '=':             /* DECKPAM: Keypad application mode */
2837                     compatibility(VT100);
2838                     term->app_keypad_keys = TRUE;
2839                     break;
2840                   case '>':             /* DECKPNM: Keypad numeric mode */
2841                     compatibility(VT100);
2842                     term->app_keypad_keys = FALSE;
2843                     break;
2844                   case 'D':            /* IND: exactly equivalent to LF */
2845                     compatibility(VT100);
2846                     if (term->curs.y == term->marg_b)
2847                         scroll(term, term->marg_t, term->marg_b, 1, TRUE);
2848                     else if (term->curs.y < term->rows - 1)
2849                         term->curs.y++;
2850                     term->wrapnext = FALSE;
2851                     term->seen_disp_event = TRUE;
2852                     break;
2853                   case 'E':            /* NEL: exactly equivalent to CR-LF */
2854                     compatibility(VT100);
2855                     term->curs.x = 0;
2856                     if (term->curs.y == term->marg_b)
2857                         scroll(term, term->marg_t, term->marg_b, 1, TRUE);
2858                     else if (term->curs.y < term->rows - 1)
2859                         term->curs.y++;
2860                     term->wrapnext = FALSE;
2861                     term->seen_disp_event = TRUE;
2862                     break;
2863                   case 'M':            /* RI: reverse index - backwards LF */
2864                     compatibility(VT100);
2865                     if (term->curs.y == term->marg_t)
2866                         scroll(term, term->marg_t, term->marg_b, -1, TRUE);
2867                     else if (term->curs.y > 0)
2868                         term->curs.y--;
2869                     term->wrapnext = FALSE;
2870                     term->seen_disp_event = TRUE;
2871                     break;
2872                   case 'Z':            /* DECID: terminal type query */
2873                     compatibility(VT100);
2874                     if (term->ldisc)
2875                         ldisc_send(term->ldisc, term->id_string,
2876                                    strlen(term->id_string), 0);
2877                     break;
2878                   case 'c':            /* RIS: restore power-on settings */
2879                     compatibility(VT100);
2880                     power_on(term);
2881                     if (term->ldisc)   /* cause ldisc to notice changes */
2882                         ldisc_send(term->ldisc, NULL, 0, 0);
2883                     if (term->reset_132) {
2884                         if (!term->cfg.no_remote_resize)
2885                             request_resize(term->frontend, 80, term->rows);
2886                         term->reset_132 = 0;
2887                     }
2888                     term->disptop = 0;
2889                     term->seen_disp_event = TRUE;
2890                     break;
2891                   case 'H':            /* HTS: set a tab */
2892                     compatibility(VT100);
2893                     term->tabs[term->curs.x] = TRUE;
2894                     break;
2895
2896                   case ANSI('8', '#'):  /* DECALN: fills screen with Es :-) */
2897                     compatibility(VT100);
2898                     {
2899                         termline *ldata;
2900                         int i, j;
2901                         pos scrtop, scrbot;
2902
2903                         for (i = 0; i < term->rows; i++) {
2904                             ldata = scrlineptr(i);
2905                             for (j = 0; j < term->cols; j++) {
2906                                 copy_termchar(ldata, j,
2907                                               &term->basic_erase_char);
2908                                 ldata->chars[j].chr = 'E';
2909                             }
2910                             ldata->lattr = LATTR_NORM;
2911                         }
2912                         term->disptop = 0;
2913                         term->seen_disp_event = TRUE;
2914                         scrtop.x = scrtop.y = 0;
2915                         scrbot.x = 0;
2916                         scrbot.y = term->rows;
2917                         check_selection(term, scrtop, scrbot);
2918                     }
2919                     break;
2920
2921                   case ANSI('3', '#'):
2922                   case ANSI('4', '#'):
2923                   case ANSI('5', '#'):
2924                   case ANSI('6', '#'):
2925                     compatibility(VT100);
2926                     {
2927                         int nlattr;
2928
2929                         switch (ANSI(c, term->esc_query)) {
2930                           case ANSI('3', '#'): /* DECDHL: 2*height, top */
2931                             nlattr = LATTR_TOP;
2932                             break;
2933                           case ANSI('4', '#'): /* DECDHL: 2*height, bottom */
2934                             nlattr = LATTR_BOT;
2935                             break;
2936                           case ANSI('5', '#'): /* DECSWL: normal */
2937                             nlattr = LATTR_NORM;
2938                             break;
2939                           default: /* case ANSI('6', '#'): DECDWL: 2*width */
2940                             nlattr = LATTR_WIDE;
2941                             break;
2942                         }
2943                         scrlineptr(term->curs.y)->lattr = nlattr;
2944                     }
2945                     break;
2946                   /* GZD4: G0 designate 94-set */
2947                   case ANSI('A', '('):
2948                     compatibility(VT100);
2949                     if (!term->cfg.no_remote_charset)
2950                         term->cset_attr[0] = CSET_GBCHR;
2951                     break;
2952                   case ANSI('B', '('):
2953                     compatibility(VT100);
2954                     if (!term->cfg.no_remote_charset)
2955                         term->cset_attr[0] = CSET_ASCII;
2956                     break;
2957                   case ANSI('0', '('):
2958                     compatibility(VT100);
2959                     if (!term->cfg.no_remote_charset)
2960                         term->cset_attr[0] = CSET_LINEDRW;
2961                     break;
2962                   case ANSI('U', '('): 
2963                     compatibility(OTHER);
2964                     if (!term->cfg.no_remote_charset)
2965                         term->cset_attr[0] = CSET_SCOACS; 
2966                     break;
2967                   /* G1D4: G1-designate 94-set */
2968                   case ANSI('A', ')'):
2969                     compatibility(VT100);
2970                     if (!term->cfg.no_remote_charset)
2971                         term->cset_attr[1] = CSET_GBCHR;
2972                     break;
2973                   case ANSI('B', ')'):
2974                     compatibility(VT100);
2975                     if (!term->cfg.no_remote_charset)
2976                         term->cset_attr[1] = CSET_ASCII;
2977                     break;
2978                   case ANSI('0', ')'):
2979                     compatibility(VT100);
2980                     if (!term->cfg.no_remote_charset)
2981                         term->cset_attr[1] = CSET_LINEDRW;
2982                     break;
2983                   case ANSI('U', ')'): 
2984                     compatibility(OTHER);
2985                     if (!term->cfg.no_remote_charset)
2986                         term->cset_attr[1] = CSET_SCOACS; 
2987                     break;
2988                   /* DOCS: Designate other coding system */
2989                   case ANSI('8', '%'):  /* Old Linux code */
2990                   case ANSI('G', '%'):
2991                     compatibility(OTHER);
2992                     if (!term->cfg.no_remote_charset)
2993                         term->utf = 1;
2994                     break;
2995                   case ANSI('@', '%'):
2996                     compatibility(OTHER);
2997                     if (!term->cfg.no_remote_charset)
2998                         term->utf = 0;
2999                     break;
3000                 }
3001                 break;
3002               case SEEN_CSI:
3003                 term->termstate = TOPLEVEL;  /* default */
3004                 if (isdigit(c)) {
3005                     if (term->esc_nargs <= ARGS_MAX) {
3006                         if (term->esc_args[term->esc_nargs - 1] == ARG_DEFAULT)
3007                             term->esc_args[term->esc_nargs - 1] = 0;
3008                         term->esc_args[term->esc_nargs - 1] =
3009                             10 * term->esc_args[term->esc_nargs - 1] + c - '0';
3010                     }
3011                     term->termstate = SEEN_CSI;
3012                 } else if (c == ';') {
3013                     if (++term->esc_nargs <= ARGS_MAX)
3014                         term->esc_args[term->esc_nargs - 1] = ARG_DEFAULT;
3015                     term->termstate = SEEN_CSI;
3016                 } else if (c < '@') {
3017                     if (term->esc_query)
3018                         term->esc_query = -1;
3019                     else if (c == '?')
3020                         term->esc_query = TRUE;
3021                     else
3022                         term->esc_query = c;
3023                     term->termstate = SEEN_CSI;
3024                 } else
3025                     switch (ANSI(c, term->esc_query)) {
3026                       case 'A':       /* CUU: move up N lines */
3027                         move(term, term->curs.x,
3028                              term->curs.y - def(term->esc_args[0], 1), 1);
3029                         term->seen_disp_event = TRUE;
3030                         break;
3031                       case 'e':         /* VPR: move down N lines */
3032                         compatibility(ANSI);
3033                         /* FALLTHROUGH */
3034                       case 'B':         /* CUD: Cursor down */
3035                         move(term, term->curs.x,
3036                              term->curs.y + def(term->esc_args[0], 1), 1);
3037                         term->seen_disp_event = TRUE;
3038                         break;
3039                       case ANSI('c', '>'):      /* DA: report xterm version */
3040                         compatibility(OTHER);
3041                         /* this reports xterm version 136 so that VIM can
3042                            use the drag messages from the mouse reporting */
3043                         if (term->ldisc)
3044                             ldisc_send(term->ldisc, "\033[>0;136;0c", 11, 0);
3045                         break;
3046                       case 'a':         /* HPR: move right N cols */
3047                         compatibility(ANSI);
3048                         /* FALLTHROUGH */
3049                       case 'C':         /* CUF: Cursor right */ 
3050                         move(term, term->curs.x + def(term->esc_args[0], 1),
3051                              term->curs.y, 1);
3052                         term->seen_disp_event = TRUE;
3053                         break;
3054                       case 'D':       /* CUB: move left N cols */
3055                         move(term, term->curs.x - def(term->esc_args[0], 1),
3056                              term->curs.y, 1);
3057                         term->seen_disp_event = TRUE;
3058                         break;
3059                       case 'E':       /* CNL: move down N lines and CR */
3060                         compatibility(ANSI);
3061                         move(term, 0,
3062                              term->curs.y + def(term->esc_args[0], 1), 1);
3063                         term->seen_disp_event = TRUE;
3064                         break;
3065                       case 'F':       /* CPL: move up N lines and CR */
3066                         compatibility(ANSI);
3067                         move(term, 0,
3068                              term->curs.y - def(term->esc_args[0], 1), 1);
3069                         term->seen_disp_event = TRUE;
3070                         break;
3071                       case 'G':       /* CHA */
3072                       case '`':       /* HPA: set horizontal posn */
3073                         compatibility(ANSI);
3074                         move(term, def(term->esc_args[0], 1) - 1,
3075                              term->curs.y, 0);
3076                         term->seen_disp_event = TRUE;
3077                         break;
3078                       case 'd':       /* VPA: set vertical posn */
3079                         compatibility(ANSI);
3080                         move(term, term->curs.x,
3081                              ((term->dec_om ? term->marg_t : 0) +
3082                               def(term->esc_args[0], 1) - 1),
3083                              (term->dec_om ? 2 : 0));
3084                         term->seen_disp_event = TRUE;
3085                         break;
3086                       case 'H':      /* CUP */
3087                       case 'f':      /* HVP: set horz and vert posns at once */
3088                         if (term->esc_nargs < 2)
3089                             term->esc_args[1] = ARG_DEFAULT;
3090                         move(term, def(term->esc_args[1], 1) - 1,
3091                              ((term->dec_om ? term->marg_t : 0) +
3092                               def(term->esc_args[0], 1) - 1),
3093                              (term->dec_om ? 2 : 0));
3094                         term->seen_disp_event = TRUE;
3095                         break;
3096                       case 'J':       /* ED: erase screen or parts of it */
3097                         {
3098                             unsigned int i = def(term->esc_args[0], 0) + 1;
3099                             if (i > 3)
3100                                 i = 0;
3101                             erase_lots(term, FALSE, !!(i & 2), !!(i & 1));
3102                         }
3103                         term->disptop = 0;
3104                         term->seen_disp_event = TRUE;
3105                         break;
3106                       case 'K':       /* EL: erase line or parts of it */
3107                         {
3108                             unsigned int i = def(term->esc_args[0], 0) + 1;
3109                             if (i > 3)
3110                                 i = 0;
3111                             erase_lots(term, TRUE, !!(i & 2), !!(i & 1));
3112                         }
3113                         term->seen_disp_event = TRUE;
3114                         break;
3115                       case 'L':       /* IL: insert lines */
3116                         compatibility(VT102);
3117                         if (term->curs.y <= term->marg_b)
3118                             scroll(term, term->curs.y, term->marg_b,
3119                                    -def(term->esc_args[0], 1), FALSE);
3120                         term->seen_disp_event = TRUE;
3121                         break;
3122                       case 'M':       /* DL: delete lines */
3123                         compatibility(VT102);
3124                         if (term->curs.y <= term->marg_b)
3125                             scroll(term, term->curs.y, term->marg_b,
3126                                    def(term->esc_args[0], 1),
3127                                    TRUE);
3128                         term->seen_disp_event = TRUE;
3129                         break;
3130                       case '@':       /* ICH: insert chars */
3131                         /* XXX VTTEST says this is vt220, vt510 manual says vt102 */
3132                         compatibility(VT102);
3133                         insch(term, def(term->esc_args[0], 1));
3134                         term->seen_disp_event = TRUE;
3135                         break;
3136                       case 'P':       /* DCH: delete chars */
3137                         compatibility(VT102);
3138                         insch(term, -def(term->esc_args[0], 1));
3139                         term->seen_disp_event = TRUE;
3140                         break;
3141                       case 'c':       /* DA: terminal type query */
3142                         compatibility(VT100);
3143                         /* This is the response for a VT102 */
3144                         if (term->ldisc)
3145                             ldisc_send(term->ldisc, term->id_string,
3146                                        strlen(term->id_string), 0);
3147                         break;
3148                       case 'n':       /* DSR: cursor position query */
3149                         if (term->ldisc) {
3150                             if (term->esc_args[0] == 6) {
3151                                 char buf[32];
3152                                 sprintf(buf, "\033[%d;%dR", term->curs.y + 1,
3153                                         term->curs.x + 1);
3154                                 ldisc_send(term->ldisc, buf, strlen(buf), 0);
3155                             } else if (term->esc_args[0] == 5) {
3156                                 ldisc_send(term->ldisc, "\033[0n", 4, 0);
3157                             }
3158                         }
3159                         break;
3160                       case 'h':       /* SM: toggle modes to high */
3161                       case ANSI_QUE('h'):
3162                         compatibility(VT100);
3163                         {
3164                             int i;
3165                             for (i = 0; i < term->esc_nargs; i++)
3166                                 toggle_mode(term, term->esc_args[i],
3167                                             term->esc_query, TRUE);
3168                         }
3169                         break;
3170                       case 'i':         /* MC: Media copy */
3171                       case ANSI_QUE('i'):
3172                         compatibility(VT100);
3173                         {
3174                             if (term->esc_nargs != 1) break;
3175                             if (term->esc_args[0] == 5 && *term->cfg.printer) {
3176                                 term->printing = TRUE;
3177                                 term->only_printing = !term->esc_query;
3178                                 term->print_state = 0;
3179                                 term_print_setup(term);
3180                             } else if (term->esc_args[0] == 4 &&
3181                                        term->printing) {
3182                                 term_print_finish(term);
3183                             }
3184                         }
3185                         break;                  
3186                       case 'l':       /* RM: toggle modes to low */
3187                       case ANSI_QUE('l'):
3188                         compatibility(VT100);
3189                         {
3190                             int i;
3191                             for (i = 0; i < term->esc_nargs; i++)
3192                                 toggle_mode(term, term->esc_args[i],
3193                                             term->esc_query, FALSE);
3194                         }
3195                         break;
3196                       case 'g':       /* TBC: clear tabs */
3197                         compatibility(VT100);
3198                         if (term->esc_nargs == 1) {
3199                             if (term->esc_args[0] == 0) {
3200                                 term->tabs[term->curs.x] = FALSE;
3201                             } else if (term->esc_args[0] == 3) {
3202                                 int i;
3203                                 for (i = 0; i < term->cols; i++)
3204                                     term->tabs[i] = FALSE;
3205                             }
3206                         }
3207                         break;
3208                       case 'r':       /* DECSTBM: set scroll margins */
3209                         compatibility(VT100);
3210                         if (term->esc_nargs <= 2) {
3211                             int top, bot;
3212                             top = def(term->esc_args[0], 1) - 1;
3213                             bot = (term->esc_nargs <= 1
3214                                    || term->esc_args[1] == 0 ?
3215                                    term->rows :
3216                                    def(term->esc_args[1], term->rows)) - 1;
3217                             if (bot >= term->rows)
3218                                 bot = term->rows - 1;
3219                             /* VTTEST Bug 9 - if region is less than 2 lines
3220                              * don't change region.
3221                              */
3222                             if (bot - top > 0) {
3223                                 term->marg_t = top;
3224                                 term->marg_b = bot;
3225                                 term->curs.x = 0;
3226                                 /*
3227                                  * I used to think the cursor should be
3228                                  * placed at the top of the newly marginned
3229                                  * area. Apparently not: VMS TPU falls over
3230                                  * if so.
3231                                  *
3232                                  * Well actually it should for
3233                                  * Origin mode - RDB
3234                                  */
3235                                 term->curs.y = (term->dec_om ?
3236                                                 term->marg_t : 0);
3237                                 term->seen_disp_event = TRUE;
3238                             }
3239                         }
3240                         break;
3241                       case 'm':       /* SGR: set graphics rendition */
3242                         {
3243                             /* 
3244                              * A VT100 without the AVO only had one
3245                              * attribute, either underline or
3246                              * reverse video depending on the
3247                              * cursor type, this was selected by
3248                              * CSI 7m.
3249                              *
3250                              * case 2:
3251                              *  This is sometimes DIM, eg on the
3252                              *  GIGI and Linux
3253                              * case 8:
3254                              *  This is sometimes INVIS various ANSI.
3255                              * case 21:
3256                              *  This like 22 disables BOLD, DIM and INVIS
3257                              *
3258                              * The ANSI colours appear on any
3259                              * terminal that has colour (obviously)
3260                              * but the interaction between sgr0 and
3261                              * the colours varies but is usually
3262                              * related to the background colour
3263                              * erase item. The interaction between
3264                              * colour attributes and the mono ones
3265                              * is also very implementation
3266                              * dependent.
3267                              *
3268                              * The 39 and 49 attributes are likely
3269                              * to be unimplemented.
3270                              */
3271                             int i;
3272                             for (i = 0; i < term->esc_nargs; i++) {
3273                                 switch (def(term->esc_args[i], 0)) {
3274                                   case 0:       /* restore defaults */
3275                                     term->curr_attr = term->default_attr;
3276                                     break;
3277                                   case 1:       /* enable bold */
3278                                     compatibility(VT100AVO);
3279                                     term->curr_attr |= ATTR_BOLD;
3280                                     break;
3281                                   case 21:      /* (enable double underline) */
3282                                     compatibility(OTHER);
3283                                   case 4:       /* enable underline */
3284                                     compatibility(VT100AVO);
3285                                     term->curr_attr |= ATTR_UNDER;
3286                                     break;
3287                                   case 5:       /* enable blink */
3288                                     compatibility(VT100AVO);
3289                                     term->curr_attr |= ATTR_BLINK;
3290                                     break;
3291                                   case 6:       /* SCO light bkgrd */
3292                                     compatibility(SCOANSI);
3293                                     term->blink_is_real = FALSE;
3294                                     term->curr_attr |= ATTR_BLINK;
3295                                     break;
3296                                   case 7:       /* enable reverse video */
3297                                     term->curr_attr |= ATTR_REVERSE;
3298                                     break;
3299                                   case 10:      /* SCO acs off */
3300                                     compatibility(SCOANSI);
3301                                     if (term->cfg.no_remote_charset) break;
3302                                     term->sco_acs = 0; break;
3303                                   case 11:      /* SCO acs on */
3304                                     compatibility(SCOANSI);
3305                                     if (term->cfg.no_remote_charset) break;
3306                                     term->sco_acs = 1; break;
3307                                   case 12:      /* SCO acs on, |0x80 */
3308                                     compatibility(SCOANSI);
3309                                     if (term->cfg.no_remote_charset) break;
3310                                     term->sco_acs = 2; break;
3311                                   case 22:      /* disable bold */
3312                                     compatibility2(OTHER, VT220);
3313                                     term->curr_attr &= ~ATTR_BOLD;
3314                                     break;
3315                                   case 24:      /* disable underline */
3316                                     compatibility2(OTHER, VT220);
3317                                     term->curr_attr &= ~ATTR_UNDER;
3318                                     break;
3319                                   case 25:      /* disable blink */
3320                                     compatibility2(OTHER, VT220);
3321                                     term->curr_attr &= ~ATTR_BLINK;
3322                                     break;
3323                                   case 27:      /* disable reverse video */
3324                                     compatibility2(OTHER, VT220);
3325                                     term->curr_attr &= ~ATTR_REVERSE;
3326                                     break;
3327                                   case 30:
3328                                   case 31:
3329                                   case 32:
3330                                   case 33:
3331                                   case 34:
3332                                   case 35:
3333                                   case 36:
3334                                   case 37:
3335                                     /* foreground */
3336                                     term->curr_attr &= ~ATTR_FGMASK;
3337                                     term->curr_attr |=
3338                                         (term->esc_args[i] - 30)<<ATTR_FGSHIFT;
3339                                     break;
3340                                   case 90:
3341                                   case 91:
3342                                   case 92:
3343                                   case 93:
3344                                   case 94:
3345                                   case 95:
3346                                   case 96:
3347                                   case 97:
3348                                     /* xterm-style bright foreground */
3349                                     term->curr_attr &= ~ATTR_FGMASK;
3350                                     term->curr_attr |=
3351                                         ((term->esc_args[i] - 90 + 16)
3352                                          << ATTR_FGSHIFT);
3353                                     break;
3354                                   case 39:      /* default-foreground */
3355                                     term->curr_attr &= ~ATTR_FGMASK;
3356                                     term->curr_attr |= ATTR_DEFFG;
3357                                     break;
3358                                   case 40:
3359                                   case 41:
3360                                   case 42:
3361                                   case 43:
3362                                   case 44:
3363                                   case 45:
3364                                   case 46:
3365                                   case 47:
3366                                     /* background */
3367                                     term->curr_attr &= ~ATTR_BGMASK;
3368                                     term->curr_attr |=
3369                                         (term->esc_args[i] - 40)<<ATTR_BGSHIFT;
3370                                     break;
3371                                   case 100:
3372                                   case 101:
3373                                   case 102:
3374                                   case 103:
3375                                   case 104:
3376                                   case 105:
3377                                   case 106:
3378                                   case 107:
3379                                     /* xterm-style bright background */
3380                                     term->curr_attr &= ~ATTR_BGMASK;
3381                                     term->curr_attr |=
3382                                         ((term->esc_args[i] - 100 + 16)
3383                                          << ATTR_BGSHIFT);
3384                                     break;
3385                                   case 49:      /* default-background */
3386                                     term->curr_attr &= ~ATTR_BGMASK;
3387                                     term->curr_attr |= ATTR_DEFBG;
3388                                     break;
3389                                 }
3390                             }
3391                             set_erase_char(term);
3392                         }
3393                         break;
3394                       case 's':       /* save cursor */
3395                         save_cursor(term, TRUE);
3396                         break;
3397                       case 'u':       /* restore cursor */
3398                         save_cursor(term, FALSE);
3399                         term->seen_disp_event = TRUE;
3400                         break;
3401                       case 't': /* DECSLPP: set page size - ie window height */
3402                         /*
3403                          * VT340/VT420 sequence DECSLPP, DEC only allows values
3404                          *  24/25/36/48/72/144 other emulators (eg dtterm) use
3405                          * illegal values (eg first arg 1..9) for window changing 
3406                          * and reports.
3407                          */
3408                         if (term->esc_nargs <= 1
3409                             && (term->esc_args[0] < 1 ||
3410                                 term->esc_args[0] >= 24)) {
3411                             compatibility(VT340TEXT);
3412                             if (!term->cfg.no_remote_resize)
3413                                 request_resize(term->frontend, term->cols,
3414                                                def(term->esc_args[0], 24));
3415                             deselect(term);
3416                         } else if (term->esc_nargs >= 1 &&
3417                                    term->esc_args[0] >= 1 &&
3418                                    term->esc_args[0] < 24) {
3419                             compatibility(OTHER);
3420
3421                             switch (term->esc_args[0]) {
3422                                 int x, y, len;
3423                                 char buf[80], *p;
3424                               case 1:
3425                                 set_iconic(term->frontend, FALSE);
3426                                 break;
3427                               case 2:
3428                                 set_iconic(term->frontend, TRUE);
3429                                 break;
3430                               case 3:
3431                                 if (term->esc_nargs >= 3) {
3432                                     if (!term->cfg.no_remote_resize)
3433                                         move_window(term->frontend,
3434                                                     def(term->esc_args[1], 0),
3435                                                     def(term->esc_args[2], 0));
3436                                 }
3437                                 break;
3438                               case 4:
3439                                 /* We should resize the window to a given
3440                                  * size in pixels here, but currently our
3441                                  * resizing code isn't healthy enough to
3442                                  * manage it. */
3443                                 break;
3444                               case 5:
3445                                 /* move to top */
3446                                 set_zorder(term->frontend, TRUE);
3447                                 break;
3448                               case 6:
3449                                 /* move to bottom */
3450                                 set_zorder(term->frontend, FALSE);
3451                                 break;
3452                               case 7:
3453                                 refresh_window(term->frontend);
3454                                 break;
3455                               case 8:
3456                                 if (term->esc_nargs >= 3) {
3457                                     if (!term->cfg.no_remote_resize)
3458                                         request_resize(term->frontend,
3459                                                        def(term->esc_args[2], term->cfg.width),
3460                                                        def(term->esc_args[1], term->cfg.height));
3461                                 }
3462                                 break;
3463                               case 9:
3464                                 if (term->esc_nargs >= 2)
3465                                     set_zoomed(term->frontend,
3466                                                term->esc_args[1] ?
3467                                                TRUE : FALSE);
3468                                 break;
3469                               case 11:
3470                                 if (term->ldisc)
3471                                     ldisc_send(term->ldisc,
3472                                                is_iconic(term->frontend) ?
3473                                                "\033[1t" : "\033[2t", 4, 0);
3474                                 break;
3475                               case 13:
3476                                 if (term->ldisc) {
3477                                     get_window_pos(term->frontend, &x, &y);
3478                                     len = sprintf(buf, "\033[3;%d;%dt", x, y);
3479                                     ldisc_send(term->ldisc, buf, len, 0);
3480                                 }
3481                                 break;
3482                               case 14:
3483                                 if (term->ldisc) {
3484                                     get_window_pixels(term->frontend, &x, &y);
3485                                     len = sprintf(buf, "\033[4;%d;%dt", x, y);
3486                                     ldisc_send(term->ldisc, buf, len, 0);
3487                                 }
3488                                 break;
3489                               case 18:
3490                                 if (term->ldisc) {
3491                                     len = sprintf(buf, "\033[8;%d;%dt",
3492                                                   term->rows, term->cols);
3493                                     ldisc_send(term->ldisc, buf, len, 0);
3494                                 }
3495                                 break;
3496                               case 19:
3497                                 /*
3498                                  * Hmmm. Strictly speaking we
3499                                  * should return `the size of the
3500                                  * screen in characters', but
3501                                  * that's not easy: (a) window
3502                                  * furniture being what it is it's
3503                                  * hard to compute, and (b) in
3504                                  * resize-font mode maximising the
3505                                  * window wouldn't change the
3506                                  * number of characters. *shrug*. I
3507                                  * think we'll ignore it for the
3508                                  * moment and see if anyone
3509                                  * complains, and then ask them
3510                                  * what they would like it to do.
3511                                  */
3512                                 break;
3513                               case 20:
3514                                 if (term->ldisc &&
3515                                     !term->cfg.no_remote_qtitle) {
3516                                     p = get_window_title(term->frontend, TRUE);
3517                                     len = strlen(p);
3518                                     ldisc_send(term->ldisc, "\033]L", 3, 0);
3519                                     ldisc_send(term->ldisc, p, len, 0);
3520                                     ldisc_send(term->ldisc, "\033\\", 2, 0);
3521                                 }
3522                                 break;
3523                               case 21:
3524                                 if (term->ldisc &&
3525                                     !term->cfg.no_remote_qtitle) {
3526                                     p = get_window_title(term->frontend,FALSE);
3527                                     len = strlen(p);
3528                                     ldisc_send(term->ldisc, "\033]l", 3, 0);
3529                                     ldisc_send(term->ldisc, p, len, 0);
3530                                     ldisc_send(term->ldisc, "\033\\", 2, 0);
3531                                 }
3532                                 break;
3533                             }
3534                         }
3535                         break;
3536                       case 'S':         /* SU: Scroll up */
3537                         compatibility(SCOANSI);
3538                         scroll(term, term->marg_t, term->marg_b,
3539                                def(term->esc_args[0], 1), TRUE);
3540                         term->wrapnext = FALSE;
3541                         term->seen_disp_event = TRUE;
3542                         break;
3543                       case 'T':         /* SD: Scroll down */
3544                         compatibility(SCOANSI);
3545                         scroll(term, term->marg_t, term->marg_b,
3546                                -def(term->esc_args[0], 1), TRUE);
3547                         term->wrapnext = FALSE;
3548                         term->seen_disp_event = TRUE;
3549                         break;
3550                       case ANSI('|', '*'): /* DECSNLS */
3551                         /* 
3552                          * Set number of lines on screen
3553                          * VT420 uses VGA like hardware and can
3554                          * support any size in reasonable range
3555                          * (24..49 AIUI) with no default specified.
3556                          */
3557                         compatibility(VT420);
3558                         if (term->esc_nargs == 1 && term->esc_args[0] > 0) {
3559                             if (!term->cfg.no_remote_resize)
3560                                 request_resize(term->frontend, term->cols,
3561                                                def(term->esc_args[0],
3562                                                    term->cfg.height));
3563                             deselect(term);
3564                         }
3565                         break;
3566                       case ANSI('|', '$'): /* DECSCPP */
3567                         /*
3568                          * Set number of columns per page
3569                          * Docs imply range is only 80 or 132, but
3570                          * I'll allow any.
3571                          */
3572                         compatibility(VT340TEXT);
3573                         if (term->esc_nargs <= 1) {
3574                             if (!term->cfg.no_remote_resize)
3575                                 request_resize(term->frontend,
3576                                                def(term->esc_args[0],
3577                                                    term->cfg.width), term->rows);
3578                             deselect(term);
3579                         }
3580                         break;
3581                       case 'X':     /* ECH: write N spaces w/o moving cursor */
3582                         /* XXX VTTEST says this is vt220, vt510 manual
3583                          * says vt100 */
3584                         compatibility(ANSIMIN);
3585                         {
3586                             int n = def(term->esc_args[0], 1);
3587                             pos cursplus;
3588                             int p = term->curs.x;
3589                             termline *cline = scrlineptr(term->curs.y);
3590
3591                             if (n > term->cols - term->curs.x)
3592                                 n = term->cols - term->curs.x;
3593                             cursplus = term->curs;
3594                             cursplus.x += n;
3595                             check_boundary(term, term->curs.x, term->curs.y);
3596                             check_boundary(term, term->curs.x+n, term->curs.y);
3597                             check_selection(term, term->curs, cursplus);
3598                             while (n--)
3599                                 copy_termchar(cline, p++,
3600                                               &term->erase_char);
3601                             term->seen_disp_event = TRUE;
3602                         }
3603                         break;
3604                       case 'x':       /* DECREQTPARM: report terminal characteristics */
3605                         compatibility(VT100);
3606                         if (term->ldisc) {
3607                             char buf[32];
3608                             int i = def(term->esc_args[0], 0);
3609                             if (i == 0 || i == 1) {
3610                                 strcpy(buf, "\033[2;1;1;112;112;1;0x");
3611                                 buf[2] += i;
3612                                 ldisc_send(term->ldisc, buf, 20, 0);
3613                             }
3614                         }
3615                         break;
3616                       case 'Z':         /* CBT: BackTab for xterm */
3617                         compatibility(OTHER);
3618                         {
3619                             int i = def(term->esc_args[0], 1);
3620                             pos old_curs = term->curs;
3621
3622                             for(;i>0 && term->curs.x>0; i--) {
3623                                 do {
3624                                     term->curs.x--;
3625                                 } while (term->curs.x >0 &&
3626                                          !term->tabs[term->curs.x]);
3627                             }
3628                             check_selection(term, old_curs, term->curs);
3629                         }
3630                         break;
3631                       case ANSI('c', '='):      /* Hide or Show Cursor */
3632                         compatibility(SCOANSI);
3633                         switch(term->esc_args[0]) {
3634                           case 0:  /* hide cursor */
3635                             term->cursor_on = FALSE;
3636                             break;
3637                           case 1:  /* restore cursor */
3638                             term->big_cursor = FALSE;
3639                             term->cursor_on = TRUE;
3640                             break;
3641                           case 2:  /* block cursor */
3642                             term->big_cursor = TRUE;
3643                             term->cursor_on = TRUE;
3644                             break;
3645                         }
3646                         break;
3647                       case ANSI('C', '='):
3648                         /*
3649                          * set cursor start on scanline esc_args[0] and
3650                          * end on scanline esc_args[1].If you set
3651                          * the bottom scan line to a value less than
3652                          * the top scan line, the cursor will disappear.
3653                          */
3654                         compatibility(SCOANSI);
3655                         if (term->esc_nargs >= 2) {
3656                             if (term->esc_args[0] > term->esc_args[1])
3657                                 term->cursor_on = FALSE;
3658                             else
3659                                 term->cursor_on = TRUE;
3660                         }
3661                         break;
3662                       case ANSI('D', '='):
3663                         compatibility(SCOANSI);
3664                         term->blink_is_real = FALSE;
3665                         if (term->esc_args[0]>=1)
3666                             term->curr_attr |= ATTR_BLINK;
3667                         else
3668                             term->curr_attr &= ~ATTR_BLINK;
3669                         break;
3670                       case ANSI('E', '='):
3671                         compatibility(SCOANSI);
3672                         term->blink_is_real = (term->esc_args[0] >= 1);
3673                         break;
3674                       case ANSI('F', '='):      /* set normal foreground */
3675                         compatibility(SCOANSI);
3676                         if (term->esc_args[0] >= 0 && term->esc_args[0] < 16) {
3677                             long colour =
3678                                 (sco2ansicolour[term->esc_args[0] & 0x7] |
3679                                  ((term->esc_args[0] & 0x8) << 1)) <<
3680                                 ATTR_FGSHIFT;
3681                             term->curr_attr &= ~ATTR_FGMASK;
3682                             term->curr_attr |= colour;
3683                             term->default_attr &= ~ATTR_FGMASK;
3684                             term->default_attr |= colour;
3685                         }
3686                         break;
3687                       case ANSI('G', '='):      /* set normal background */
3688                         compatibility(SCOANSI);
3689                         if (term->esc_args[0] >= 0 && term->esc_args[0] < 16) {
3690                             long colour =
3691                                 (sco2ansicolour[term->esc_args[0] & 0x7] |
3692                                  ((term->esc_args[0] & 0x8) << 1)) <<
3693                                 ATTR_BGSHIFT;
3694                             term->curr_attr &= ~ATTR_BGMASK;
3695                             term->curr_attr |= colour;
3696                             term->default_attr &= ~ATTR_BGMASK;
3697                             term->default_attr |= colour;
3698                         }
3699                         break;
3700                       case ANSI('L', '='):
3701                         compatibility(SCOANSI);
3702                         term->use_bce = (term->esc_args[0] <= 0);
3703                         set_erase_char(term);
3704                         break;
3705                       case ANSI('p', '"'): /* DECSCL: set compat level */
3706                         /*
3707                          * Allow the host to make this emulator a
3708                          * 'perfect' VT102. This first appeared in
3709                          * the VT220, but we do need to get back to
3710                          * PuTTY mode so I won't check it.
3711                          *
3712                          * The arg in 40..42,50 are a PuTTY extension.
3713                          * The 2nd arg, 8bit vs 7bit is not checked.
3714                          *
3715                          * Setting VT102 mode should also change
3716                          * the Fkeys to generate PF* codes as a
3717                          * real VT102 has no Fkeys. The VT220 does
3718                          * this, F11..F13 become ESC,BS,LF other
3719                          * Fkeys send nothing.
3720                          *
3721                          * Note ESC c will NOT change this!
3722                          */
3723
3724                         switch (term->esc_args[0]) {
3725                           case 61:
3726                             term->compatibility_level &= ~TM_VTXXX;
3727                             term->compatibility_level |= TM_VT102;
3728                             break;
3729                           case 62:
3730                             term->compatibility_level &= ~TM_VTXXX;
3731                             term->compatibility_level |= TM_VT220;
3732                             break;
3733
3734                           default:
3735                             if (term->esc_args[0] > 60 &&
3736                                 term->esc_args[0] < 70)
3737                                 term->compatibility_level |= TM_VTXXX;
3738                             break;
3739
3740                           case 40:
3741                             term->compatibility_level &= TM_VTXXX;
3742                             break;
3743                           case 41:
3744                             term->compatibility_level = TM_PUTTY;
3745                             break;
3746                           case 42:
3747                             term->compatibility_level = TM_SCOANSI;
3748                             break;
3749
3750                           case ARG_DEFAULT:
3751                             term->compatibility_level = TM_PUTTY;
3752                             break;
3753                           case 50:
3754                             break;
3755                         }
3756
3757                         /* Change the response to CSI c */
3758                         if (term->esc_args[0] == 50) {
3759                             int i;
3760                             char lbuf[64];
3761                             strcpy(term->id_string, "\033[?");
3762                             for (i = 1; i < term->esc_nargs; i++) {
3763                                 if (i != 1)
3764                                     strcat(term->id_string, ";");
3765                                 sprintf(lbuf, "%d", term->esc_args[i]);
3766                                 strcat(term->id_string, lbuf);
3767                             }
3768                             strcat(term->id_string, "c");
3769                         }
3770 #if 0
3771                         /* Is this a good idea ? 
3772                          * Well we should do a soft reset at this point ...
3773                          */
3774                         if (!has_compat(VT420) && has_compat(VT100)) {
3775                             if (!term->cfg.no_remote_resize) {
3776                                 if (term->reset_132)
3777                                     request_resize(132, 24);
3778                                 else
3779                                     request_resize(80, 24);
3780                             }
3781                         }
3782 #endif
3783                         break;
3784                     }
3785                 break;
3786               case SEEN_OSC:
3787                 term->osc_w = FALSE;
3788                 switch (c) {
3789                   case 'P':            /* Linux palette sequence */
3790                     term->termstate = SEEN_OSC_P;
3791                     term->osc_strlen = 0;
3792                     break;
3793                   case 'R':            /* Linux palette reset */
3794                     palette_reset(term->frontend);
3795                     term_invalidate(term);
3796                     term->termstate = TOPLEVEL;
3797                     break;
3798                   case 'W':            /* word-set */
3799                     term->termstate = SEEN_OSC_W;
3800                     term->osc_w = TRUE;
3801                     break;
3802                   case '0':
3803                   case '1':
3804                   case '2':
3805                   case '3':
3806                   case '4':
3807                   case '5':
3808                   case '6':
3809                   case '7':
3810                   case '8':
3811                   case '9':
3812                     term->esc_args[0] = 10 * term->esc_args[0] + c - '0';
3813                     break;
3814                   case 'L':
3815                     /*
3816                      * Grotty hack to support xterm and DECterm title
3817                      * sequences concurrently.
3818                      */
3819                     if (term->esc_args[0] == 2) {
3820                         term->esc_args[0] = 1;
3821                         break;
3822                     }
3823                     /* else fall through */
3824                   default:
3825                     term->termstate = OSC_STRING;
3826                     term->osc_strlen = 0;
3827                 }
3828                 break;
3829               case OSC_STRING:
3830                 /*
3831                  * This OSC stuff is EVIL. It takes just one character to get into
3832                  * sysline mode and it's not initially obvious how to get out.
3833                  * So I've added CR and LF as string aborts.
3834                  * This shouldn't effect compatibility as I believe embedded 
3835                  * control characters are supposed to be interpreted (maybe?) 
3836                  * and they don't display anything useful anyway.
3837                  *
3838                  * -- RDB
3839                  */
3840                 if (c == '\012' || c == '\015') {
3841                     term->termstate = TOPLEVEL;
3842                 } else if (c == 0234 || c == '\007') {
3843                     /*
3844                      * These characters terminate the string; ST and BEL
3845                      * terminate the sequence and trigger instant
3846                      * processing of it, whereas ESC goes back to SEEN_ESC
3847                      * mode unless it is followed by \, in which case it is
3848                      * synonymous with ST in the first place.
3849                      */
3850                     do_osc(term);
3851                     term->termstate = TOPLEVEL;
3852                 } else if (c == '\033')
3853                     term->termstate = OSC_MAYBE_ST;
3854                 else if (term->osc_strlen < OSC_STR_MAX)
3855                     term->osc_string[term->osc_strlen++] = (char)c;
3856                 break;
3857               case SEEN_OSC_P:
3858                 {
3859                     int max = (term->osc_strlen == 0 ? 21 : 16);
3860                     int val;
3861                     if ((int)c >= '0' && (int)c <= '9')
3862                         val = c - '0';
3863                     else if ((int)c >= 'A' && (int)c <= 'A' + max - 10)
3864                         val = c - 'A' + 10;
3865                     else if ((int)c >= 'a' && (int)c <= 'a' + max - 10)
3866                         val = c - 'a' + 10;
3867                     else {
3868                         term->termstate = TOPLEVEL;
3869                         break;
3870                     }
3871                     term->osc_string[term->osc_strlen++] = val;
3872                     if (term->osc_strlen >= 7) {
3873                         palette_set(term->frontend, term->osc_string[0],
3874                                     term->osc_string[1] * 16 + term->osc_string[2],
3875                                     term->osc_string[3] * 16 + term->osc_string[4],
3876                                     term->osc_string[5] * 16 + term->osc_string[6]);
3877                         term_invalidate(term);
3878                         term->termstate = TOPLEVEL;
3879                     }
3880                 }
3881                 break;
3882               case SEEN_OSC_W:
3883                 switch (c) {
3884                   case '0':
3885                   case '1':
3886                   case '2':
3887                   case '3':
3888                   case '4':
3889                   case '5':
3890                   case '6':
3891                   case '7':
3892                   case '8':
3893                   case '9':
3894                     term->esc_args[0] = 10 * term->esc_args[0] + c - '0';
3895                     break;
3896                   default:
3897                     term->termstate = OSC_STRING;
3898                     term->osc_strlen = 0;
3899                 }
3900                 break;
3901               case VT52_ESC:
3902                 term->termstate = TOPLEVEL;
3903                 term->seen_disp_event = TRUE;
3904                 switch (c) {
3905                   case 'A':
3906                     move(term, term->curs.x, term->curs.y - 1, 1);
3907                     break;
3908                   case 'B':
3909                     move(term, term->curs.x, term->curs.y + 1, 1);
3910                     break;
3911                   case 'C':
3912                     move(term, term->curs.x + 1, term->curs.y, 1);
3913                     break;
3914                   case 'D':
3915                     move(term, term->curs.x - 1, term->curs.y, 1);
3916                     break;
3917                     /*
3918                      * From the VT100 Manual
3919                      * NOTE: The special graphics characters in the VT100
3920                      *       are different from those in the VT52
3921                      *
3922                      * From VT102 manual:
3923                      *       137 _  Blank             - Same
3924                      *       140 `  Reserved          - Humm.
3925                      *       141 a  Solid rectangle   - Similar
3926                      *       142 b  1/                - Top half of fraction for the
3927                      *       143 c  3/                - subscript numbers below.
3928                      *       144 d  5/
3929                      *       145 e  7/
3930                      *       146 f  Degrees           - Same
3931                      *       147 g  Plus or minus     - Same
3932                      *       150 h  Right arrow
3933                      *       151 i  Ellipsis (dots)
3934                      *       152 j  Divide by
3935                      *       153 k  Down arrow
3936                      *       154 l  Bar at scan 0
3937                      *       155 m  Bar at scan 1
3938                      *       156 n  Bar at scan 2
3939                      *       157 o  Bar at scan 3     - Similar
3940                      *       160 p  Bar at scan 4     - Similar
3941                      *       161 q  Bar at scan 5     - Similar
3942                      *       162 r  Bar at scan 6     - Same
3943                      *       163 s  Bar at scan 7     - Similar
3944                      *       164 t  Subscript 0
3945                      *       165 u  Subscript 1
3946                      *       166 v  Subscript 2
3947                      *       167 w  Subscript 3
3948                      *       170 x  Subscript 4
3949                      *       171 y  Subscript 5
3950                      *       172 z  Subscript 6
3951                      *       173 {  Subscript 7
3952                      *       174 |  Subscript 8
3953                      *       175 }  Subscript 9
3954                      *       176 ~  Paragraph
3955                      *
3956                      */
3957                   case 'F':
3958                     term->cset_attr[term->cset = 0] = CSET_LINEDRW;
3959                     break;
3960                   case 'G':
3961                     term->cset_attr[term->cset = 0] = CSET_ASCII;
3962                     break;
3963                   case 'H':
3964                     move(term, 0, 0, 0);
3965                     break;
3966                   case 'I':
3967                     if (term->curs.y == 0)
3968                         scroll(term, 0, term->rows - 1, -1, TRUE);
3969                     else if (term->curs.y > 0)
3970                         term->curs.y--;
3971                     term->wrapnext = FALSE;
3972                     break;
3973                   case 'J':
3974                     erase_lots(term, FALSE, FALSE, TRUE);
3975                     term->disptop = 0;
3976                     break;
3977                   case 'K':
3978                     erase_lots(term, TRUE, FALSE, TRUE);
3979                     break;
3980 #if 0
3981                   case 'V':
3982                     /* XXX Print cursor line */
3983                     break;
3984                   case 'W':
3985                     /* XXX Start controller mode */
3986                     break;
3987                   case 'X':
3988                     /* XXX Stop controller mode */
3989                     break;
3990 #endif
3991                   case 'Y':
3992                     term->termstate = VT52_Y1;
3993                     break;
3994                   case 'Z':
3995                     if (term->ldisc)
3996                         ldisc_send(term->ldisc, "\033/Z", 3, 0);
3997                     break;
3998                   case '=':
3999                     term->app_keypad_keys = TRUE;
4000                     break;
4001                   case '>':
4002                     term->app_keypad_keys = FALSE;
4003                     break;
4004                   case '<':
4005                     /* XXX This should switch to VT100 mode not current or default
4006                      *     VT mode. But this will only have effect in a VT220+
4007                      *     emulation.
4008                      */
4009                     term->vt52_mode = FALSE;
4010                     term->blink_is_real = term->cfg.blinktext;
4011                     break;
4012 #if 0
4013                   case '^':
4014                     /* XXX Enter auto print mode */
4015                     break;
4016                   case '_':
4017                     /* XXX Exit auto print mode */
4018                     break;
4019                   case ']':
4020                     /* XXX Print screen */
4021                     break;
4022 #endif
4023
4024 #ifdef VT52_PLUS
4025                   case 'E':
4026                     /* compatibility(ATARI) */
4027                     move(term, 0, 0, 0);
4028                     erase_lots(term, FALSE, FALSE, TRUE);
4029                     term->disptop = 0;
4030                     break;
4031                   case 'L':
4032                     /* compatibility(ATARI) */
4033                     if (term->curs.y <= term->marg_b)
4034                         scroll(term, term->curs.y, term->marg_b, -1, FALSE);
4035                     break;
4036                   case 'M':
4037                     /* compatibility(ATARI) */
4038                     if (term->curs.y <= term->marg_b)
4039                         scroll(term, term->curs.y, term->marg_b, 1, TRUE);
4040                     break;
4041                   case 'b':
4042                     /* compatibility(ATARI) */
4043                     term->termstate = VT52_FG;
4044                     break;
4045                   case 'c':
4046                     /* compatibility(ATARI) */
4047                     term->termstate = VT52_BG;
4048                     break;
4049                   case 'd':
4050                     /* compatibility(ATARI) */
4051                     erase_lots(term, FALSE, TRUE, FALSE);
4052                     term->disptop = 0;
4053                     break;
4054                   case 'e':
4055                     /* compatibility(ATARI) */
4056                     term->cursor_on = TRUE;
4057                     break;
4058                   case 'f':
4059                     /* compatibility(ATARI) */
4060                     term->cursor_on = FALSE;
4061                     break;
4062                     /* case 'j': Save cursor position - broken on ST */
4063                     /* case 'k': Restore cursor position */
4064                   case 'l':
4065                     /* compatibility(ATARI) */
4066                     erase_lots(term, TRUE, TRUE, TRUE);
4067                     term->curs.x = 0;
4068                     term->wrapnext = FALSE;
4069                     break;
4070                   case 'o':
4071                     /* compatibility(ATARI) */
4072                     erase_lots(term, TRUE, TRUE, FALSE);
4073                     break;
4074                   case 'p':
4075                     /* compatibility(ATARI) */
4076                     term->curr_attr |= ATTR_REVERSE;
4077                     break;
4078                   case 'q':
4079                     /* compatibility(ATARI) */
4080                     term->curr_attr &= ~ATTR_REVERSE;
4081                     break;
4082                   case 'v':            /* wrap Autowrap on - Wyse style */
4083                     /* compatibility(ATARI) */
4084                     term->wrap = 1;
4085                     break;
4086                   case 'w':            /* Autowrap off */
4087                     /* compatibility(ATARI) */
4088                     term->wrap = 0;
4089                     break;
4090
4091                   case 'R':
4092                     /* compatibility(OTHER) */
4093                     term->vt52_bold = FALSE;
4094                     term->curr_attr = ATTR_DEFAULT;
4095                     set_erase_char(term);
4096                     break;
4097                   case 'S':
4098                     /* compatibility(VI50) */
4099                     term->curr_attr |= ATTR_UNDER;
4100                     break;
4101                   case 'W':
4102                     /* compatibility(VI50) */
4103                     term->curr_attr &= ~ATTR_UNDER;
4104                     break;
4105                   case 'U':
4106                     /* compatibility(VI50) */
4107                     term->vt52_bold = TRUE;
4108                     term->curr_attr |= ATTR_BOLD;
4109                     break;
4110                   case 'T':
4111                     /* compatibility(VI50) */
4112                     term->vt52_bold = FALSE;
4113                     term->curr_attr &= ~ATTR_BOLD;
4114                     break;
4115 #endif
4116                 }
4117                 break;
4118               case VT52_Y1:
4119                 term->termstate = VT52_Y2;
4120                 move(term, term->curs.x, c - ' ', 0);
4121                 break;
4122               case VT52_Y2:
4123                 term->termstate = TOPLEVEL;
4124                 move(term, c - ' ', term->curs.y, 0);
4125                 break;
4126
4127 #ifdef VT52_PLUS
4128               case VT52_FG:
4129                 term->termstate = TOPLEVEL;
4130                 term->curr_attr &= ~ATTR_FGMASK;
4131                 term->curr_attr &= ~ATTR_BOLD;
4132                 term->curr_attr |= (c & 0x7) << ATTR_FGSHIFT;
4133                 if ((c & 0x8) || term->vt52_bold)
4134                     term->curr_attr |= ATTR_BOLD;
4135
4136                 set_erase_char(term);
4137                 break;
4138               case VT52_BG:
4139                 term->termstate = TOPLEVEL;
4140                 term->curr_attr &= ~ATTR_BGMASK;
4141                 term->curr_attr &= ~ATTR_BLINK;
4142                 term->curr_attr |= (c & 0x7) << ATTR_BGSHIFT;
4143
4144                 /* Note: bold background */
4145                 if (c & 0x8)
4146                     term->curr_attr |= ATTR_BLINK;
4147
4148                 set_erase_char(term);
4149                 break;
4150 #endif
4151               default: break;          /* placate gcc warning about enum use */
4152             }
4153         if (term->selstate != NO_SELECTION) {
4154             pos cursplus = term->curs;
4155             incpos(cursplus);
4156             check_selection(term, term->curs, cursplus);
4157         }
4158     }
4159
4160     term_print_flush(term);
4161     logflush(term->logctx);
4162 }
4163
4164 /*
4165  * To prevent having to run the reasonably tricky bidi algorithm
4166  * too many times, we maintain a cache of the last lineful of data
4167  * fed to the algorithm on each line of the display.
4168  */
4169 static int term_bidi_cache_hit(Terminal *term, int line,
4170                                termchar *lbefore, int width)
4171 {
4172     int i;
4173
4174     if (!term->pre_bidi_cache)
4175         return FALSE;                  /* cache doesn't even exist yet! */
4176
4177     if (line >= term->bidi_cache_size)
4178         return FALSE;                  /* cache doesn't have this many lines */
4179
4180     if (!term->pre_bidi_cache[line].chars)
4181         return FALSE;                  /* cache doesn't contain _this_ line */
4182
4183     if (term->pre_bidi_cache[line].width != width)
4184         return FALSE;                  /* line is wrong width */
4185
4186     for (i = 0; i < width; i++)
4187         if (!termchars_equal(term->pre_bidi_cache[line].chars+i, lbefore+i))
4188             return FALSE;              /* line doesn't match cache */
4189
4190     return TRUE;                       /* it didn't match. */
4191 }
4192
4193 static void term_bidi_cache_store(Terminal *term, int line, termchar *lbefore,
4194                                   termchar *lafter, int width)
4195 {
4196     if (!term->pre_bidi_cache || term->bidi_cache_size <= line) {
4197         int j = term->bidi_cache_size;
4198         term->bidi_cache_size = line+1;
4199         term->pre_bidi_cache = sresize(term->pre_bidi_cache,
4200                                        term->bidi_cache_size,
4201                                        struct bidi_cache_entry);
4202         term->post_bidi_cache = sresize(term->post_bidi_cache,
4203                                         term->bidi_cache_size,
4204                                         struct bidi_cache_entry);
4205         while (j < term->bidi_cache_size) {
4206             term->pre_bidi_cache[j].chars =
4207                 term->post_bidi_cache[j].chars = NULL;
4208             term->pre_bidi_cache[j].width =
4209                 term->post_bidi_cache[j].width = -1;
4210             j++;
4211         }
4212     }
4213
4214     sfree(term->pre_bidi_cache[line].chars);
4215     sfree(term->post_bidi_cache[line].chars);
4216
4217     term->pre_bidi_cache[line].width = width;
4218     term->pre_bidi_cache[line].chars = snewn(width, termchar);
4219     term->post_bidi_cache[line].width = width;
4220     term->post_bidi_cache[line].chars = snewn(width, termchar);
4221
4222     memcpy(term->pre_bidi_cache[line].chars, lbefore, width * TSIZE);
4223     memcpy(term->post_bidi_cache[line].chars, lafter, width * TSIZE);
4224 }
4225
4226 /*
4227  * Given a context, update the window. Out of paranoia, we don't
4228  * allow WM_PAINT responses to do scrolling optimisations.
4229  */
4230 static void do_paint(Terminal *term, Context ctx, int may_optimise)
4231 {
4232     int i, it, j, our_curs_y, our_curs_x;
4233     int rv, cursor;
4234     pos scrpos;
4235     wchar_t *ch;
4236     int chlen;
4237     termchar cursor_background;
4238     unsigned long ticks;
4239 #ifdef OPTIMISE_SCROLL
4240     struct scrollregion *sr;
4241 #endif /* OPTIMISE_SCROLL */
4242
4243     cursor_background = term->basic_erase_char;
4244
4245     chlen = 1024;
4246     ch = snewn(chlen, wchar_t);
4247
4248     /*
4249      * Check the visual bell state.
4250      */
4251     if (term->in_vbell) {
4252         ticks = GETTICKCOUNT();
4253         if (ticks - term->vbell_startpoint >= VBELL_TIMEOUT)
4254             term->in_vbell = FALSE;
4255     }
4256
4257     rv = (!term->rvideo ^ !term->in_vbell ? ATTR_REVERSE : 0);
4258
4259     /* Depends on:
4260      * screen array, disptop, scrtop,
4261      * selection, rv, 
4262      * cfg.blinkpc, blink_is_real, tblinker, 
4263      * curs.y, curs.x, blinker, cfg.blink_cur, cursor_on, has_focus, wrapnext
4264      */
4265
4266     /* Has the cursor position or type changed ? */
4267     if (term->cursor_on) {
4268         if (term->has_focus) {
4269             if (term->blinker || !term->cfg.blink_cur)
4270                 cursor = TATTR_ACTCURS;
4271             else
4272                 cursor = 0;
4273         } else
4274             cursor = TATTR_PASCURS;
4275         if (term->wrapnext)
4276             cursor |= TATTR_RIGHTCURS;
4277     } else
4278         cursor = 0;
4279     our_curs_y = term->curs.y - term->disptop;
4280     {
4281         /*
4282          * Adjust the cursor position in the case where it's
4283          * resting on the right-hand half of a CJK wide character.
4284          * xterm's behaviour here, which seems adequate to me, is
4285          * to display the cursor covering the _whole_ character,
4286          * exactly as if it were one space to the left.
4287          */
4288         termline *ldata = lineptr(term->curs.y);
4289         our_curs_x = term->curs.x;
4290         if (our_curs_x > 0 &&
4291             ldata->chars[our_curs_x].chr == UCSWIDE)
4292             our_curs_x--;
4293         unlineptr(ldata);
4294     }
4295
4296     /*
4297      * If the cursor is not where it was last time we painted, and
4298      * its previous position is visible on screen, invalidate its
4299      * previous position.
4300      */
4301     if (term->dispcursy >= 0 &&
4302         (term->curstype != cursor ||
4303          term->dispcursy != our_curs_y ||
4304          term->dispcursx != our_curs_x)) {
4305         termchar *dispcurs = term->disptext[term->dispcursy]->chars +
4306             term->dispcursx;
4307
4308         if (term->dispcursx > 0 && dispcurs->chr == UCSWIDE)
4309             dispcurs[-1].attr |= ATTR_INVALID;
4310         if (term->dispcursx < term->cols-1 && dispcurs[1].chr == UCSWIDE)
4311             dispcurs[1].attr |= ATTR_INVALID;
4312         dispcurs->attr |= ATTR_INVALID;
4313
4314         term->curstype = 0;
4315     }
4316     term->dispcursx = term->dispcursy = -1;
4317
4318 #ifdef OPTIMISE_SCROLL
4319     /* Do scrolls */
4320     sr = term->scrollhead;
4321     while (sr) {
4322         struct scrollregion *next = sr->next;
4323         do_scroll(ctx, sr->topline, sr->botline, sr->lines);
4324         sfree(sr);
4325         sr = next;
4326     }
4327     term->scrollhead = term->scrolltail = NULL;
4328 #endif /* OPTIMISE_SCROLL */
4329
4330     /* The normal screen data */
4331     for (i = 0; i < term->rows; i++) {
4332         termline *ldata;
4333         termchar *lchars;
4334         int dirty_line, dirty_run, selected;
4335         unsigned long attr = 0, cset = 0;
4336         int updated_line = 0;
4337         int start = 0;
4338         int ccount = 0;
4339         int last_run_dirty = 0;
4340
4341         scrpos.y = i + term->disptop;
4342         ldata = lineptr(scrpos.y);
4343
4344         dirty_run = dirty_line = (ldata->lattr !=
4345                                   term->disptext[i]->lattr);
4346         term->disptext[i]->lattr = ldata->lattr;
4347
4348         /* Do Arabic shaping and bidi. */
4349         if(!term->cfg.bidi || !term->cfg.arabicshaping) {
4350
4351             if (!term_bidi_cache_hit(term, i, ldata->chars, term->cols)) {
4352
4353                 if (term->wcFromTo_size < term->cols) {
4354                     term->wcFromTo_size = term->cols;
4355                     term->wcFrom = sresize(term->wcFrom, term->wcFromTo_size,
4356                                            bidi_char);
4357                     term->wcTo = sresize(term->wcTo, term->wcFromTo_size,
4358                                          bidi_char);
4359                 }
4360
4361                 for(it=0; it<term->cols ; it++)
4362                 {
4363                     unsigned long uc = (ldata->chars[it].chr);
4364
4365                     switch (uc & CSET_MASK) {
4366                       case CSET_LINEDRW:
4367                         if (!term->cfg.rawcnp) {
4368                             uc = term->ucsdata->unitab_xterm[uc & 0xFF];
4369                             break;
4370                         }
4371                       case CSET_ASCII:
4372                         uc = term->ucsdata->unitab_line[uc & 0xFF];
4373                         break;
4374                       case CSET_SCOACS:
4375                         uc = term->ucsdata->unitab_scoacs[uc&0xFF];
4376                         break;
4377                     }
4378                     switch (uc & CSET_MASK) {
4379                       case CSET_ACP:
4380                         uc = term->ucsdata->unitab_font[uc & 0xFF];
4381                         break;
4382                       case CSET_OEMCP:
4383                         uc = term->ucsdata->unitab_oemcp[uc & 0xFF];
4384                         break;
4385                     }
4386
4387                     term->wcFrom[it].origwc = term->wcFrom[it].wc =
4388                         (wchar_t)uc;
4389                     term->wcFrom[it].index = it;
4390                 }
4391
4392                 if(!term->cfg.bidi)
4393                     do_bidi(term->wcFrom, term->cols);
4394
4395                 /* this is saved iff done from inside the shaping */
4396                 if(!term->cfg.bidi && term->cfg.arabicshaping)
4397                     for(it=0; it<term->cols; it++)
4398                         term->wcTo[it] = term->wcFrom[it];
4399
4400                 if(!term->cfg.arabicshaping)
4401                     do_shape(term->wcFrom, term->wcTo, term->cols);
4402
4403                 if (term->ltemp_size < ldata->size) {
4404                     term->ltemp_size = ldata->size;
4405                     term->ltemp = sresize(term->ltemp, term->ltemp_size,
4406                                           termchar);
4407                 }
4408
4409                 memcpy(term->ltemp, ldata->chars, ldata->size * TSIZE);
4410
4411                 for(it=0; it<term->cols ; it++)
4412                 {
4413                     term->ltemp[it] = ldata->chars[term->wcTo[it].index];
4414                     if (term->ltemp[it].cc_next)
4415                         term->ltemp[it].cc_next -=
4416                         it - term->wcTo[it].index;
4417
4418                     if (term->wcTo[it].origwc != term->wcTo[it].wc)
4419                         term->ltemp[it].chr = term->wcTo[it].wc;
4420                 }
4421                 term_bidi_cache_store(term, i, ldata->chars,
4422                                       term->ltemp, ldata->size);
4423
4424                 lchars = term->ltemp;
4425             } else {
4426                 lchars = term->post_bidi_cache[i].chars;
4427             }
4428         } else
4429             lchars = ldata->chars;
4430
4431         for (j = 0; j < term->cols; j++) {
4432             unsigned long tattr, tchar;
4433             termchar *d = lchars + j;
4434             int break_run, do_copy;
4435             scrpos.x = j;
4436
4437             tchar = d->chr;
4438             tattr = d->attr;
4439
4440             switch (tchar & CSET_MASK) {
4441               case CSET_ASCII:
4442                 tchar = term->ucsdata->unitab_line[tchar & 0xFF];
4443                 break;
4444               case CSET_LINEDRW:
4445                 tchar = term->ucsdata->unitab_xterm[tchar & 0xFF];
4446                 break;
4447               case CSET_SCOACS:  
4448                 tchar = term->ucsdata->unitab_scoacs[tchar&0xFF]; 
4449                 break;
4450             }
4451             if (j < term->cols-1 && d[1].chr == UCSWIDE)
4452                 tattr |= ATTR_WIDE;
4453
4454             /* Video reversing things */
4455             if (term->selstate == DRAGGING || term->selstate == SELECTED) {
4456                 if (term->seltype == LEXICOGRAPHIC)
4457                     selected = (posle(term->selstart, scrpos) &&
4458                                 poslt(scrpos, term->selend));
4459                 else
4460                     selected = (posPle(term->selstart, scrpos) &&
4461                                 posPlt(scrpos, term->selend));
4462             } else
4463                 selected = FALSE;
4464             tattr = (tattr ^ rv
4465                      ^ (selected ? ATTR_REVERSE : 0));
4466
4467             /* 'Real' blinking ? */
4468             if (term->blink_is_real && (tattr & ATTR_BLINK)) {
4469                 if (term->has_focus && term->tblinker) {
4470                     tchar = term->ucsdata->unitab_line[(unsigned char)' '];
4471                 }
4472                 tattr &= ~ATTR_BLINK;
4473             }
4474
4475             /*
4476              * Check the font we'll _probably_ be using to see if 
4477              * the character is wide when we don't want it to be.
4478              */
4479             if (tchar != term->disptext[i]->chars[j].chr ||
4480                 tattr != (term->disptext[i]->chars[j].attr &~
4481                           ATTR_NARROW)) {
4482                 if ((tattr & ATTR_WIDE) == 0 && char_width(ctx, tchar) == 2)
4483                     tattr |= ATTR_NARROW;
4484             } else if (term->disptext[i]->chars[j].attr & ATTR_NARROW)
4485                 tattr |= ATTR_NARROW;
4486
4487             /* Cursor here ? Save the 'background' */
4488             if (i == our_curs_y && j == our_curs_x) {
4489                 /* FULL-TERMCHAR */
4490                 cursor_background.chr = tchar;
4491                 cursor_background.attr = tattr;
4492                 /* For once, this cc_next field is an absolute index in lchars */
4493                 if (d->cc_next)
4494                     cursor_background.cc_next = d->cc_next + j;
4495                 else
4496                     cursor_background.cc_next = 0;
4497                 term->dispcursx = j;
4498                 term->dispcursy = i;
4499             }
4500
4501             if ((term->disptext[i]->chars[j].attr ^ tattr) & ATTR_WIDE)
4502                 dirty_line = TRUE;
4503
4504             break_run = ((tattr ^ attr) & term->attr_mask) != 0;
4505
4506             /* Special hack for VT100 Linedraw glyphs */
4507             if (tchar >= 0x23BA && tchar <= 0x23BD)
4508                 break_run = TRUE;
4509
4510             /*
4511              * Separate out sequences of characters that have the
4512              * same CSET, if that CSET is a magic one.
4513              */
4514             if (CSET_OF(tchar) != cset)
4515                 break_run = TRUE;
4516
4517             /*
4518              * Break on both sides of any combined-character cell.
4519              */
4520             if (d->cc_next != 0 ||
4521                 (j > 0 && d[-1].cc_next != 0))
4522                 break_run = TRUE;
4523
4524             if (!term->ucsdata->dbcs_screenfont && !dirty_line) {
4525                 if (term->disptext[i]->chars[j].chr == tchar &&
4526                     term->disptext[i]->chars[j].attr == tattr)
4527                     break_run = TRUE;
4528                 else if (!dirty_run && ccount == 1)
4529                     break_run = TRUE;
4530             }
4531
4532             if (break_run) {
4533                 if ((dirty_run || last_run_dirty) && ccount > 0) {
4534                     do_text(ctx, start, i, ch, ccount, attr, ldata->lattr);
4535                     updated_line = 1;
4536                 }
4537                 start = j;
4538                 ccount = 0;
4539                 attr = tattr;
4540                 cset = CSET_OF(tchar);
4541                 if (term->ucsdata->dbcs_screenfont)
4542                     last_run_dirty = dirty_run;
4543                 dirty_run = dirty_line;
4544             }
4545
4546             do_copy = FALSE;
4547             if (!termchars_equal_override(&term->disptext[i]->chars[j],
4548                                           d, tchar, tattr)) {
4549                 do_copy = TRUE;
4550                 dirty_run = TRUE;
4551             }
4552
4553             if (ccount >= chlen) {
4554                 chlen = ccount + 256;
4555                 ch = sresize(ch, chlen, wchar_t);
4556             }
4557             ch[ccount++] = (wchar_t) tchar;
4558
4559             if (d->cc_next) {
4560                 termchar *dd = d;
4561
4562                 while (dd->cc_next) {
4563                     unsigned long schar;
4564
4565                     dd += dd->cc_next;
4566
4567                     schar = dd->chr;
4568                     switch (schar & CSET_MASK) {
4569                       case CSET_ASCII:
4570                         schar = term->ucsdata->unitab_line[schar & 0xFF];
4571                         break;
4572                       case CSET_LINEDRW:
4573                         schar = term->ucsdata->unitab_xterm[schar & 0xFF];
4574                         break;
4575                       case CSET_SCOACS:
4576                         schar = term->ucsdata->unitab_scoacs[schar&0xFF];
4577                         break;
4578                     }
4579
4580                     if (ccount >= chlen) {
4581                         chlen = ccount + 256;
4582                         ch = sresize(ch, chlen, wchar_t);
4583                     }
4584                     ch[ccount++] = (wchar_t) schar;
4585                 }
4586
4587                 attr |= TATTR_COMBINING;
4588             }
4589
4590             if (do_copy) {
4591                 copy_termchar(term->disptext[i], j, d);
4592                 term->disptext[i]->chars[j].chr = tchar;
4593                 term->disptext[i]->chars[j].attr = tattr;
4594             }
4595
4596             /* If it's a wide char step along to the next one. */
4597             if (tattr & ATTR_WIDE) {
4598                 if (++j < term->cols) {
4599                     d++;
4600                     /*
4601                      * By construction above, the cursor should not
4602                      * be on the right-hand half of this character.
4603                      * Ever.
4604                      */
4605                     assert(!(i == our_curs_y && j == our_curs_x));
4606                     if (!termchars_equal(&term->disptext[i]->chars[j], d))
4607                         dirty_run = TRUE;
4608                     copy_termchar(term->disptext[i], j, d);
4609                 }
4610             }
4611         }
4612         if (dirty_run && ccount > 0) {
4613             do_text(ctx, start, i, ch, ccount, attr, ldata->lattr);
4614             updated_line = 1;
4615         }
4616
4617         /* Cursor on this line ? (and changed) */
4618         if (i == our_curs_y && (term->curstype != cursor || updated_line)) {
4619             ch[0] = (wchar_t) cursor_background.chr;
4620             attr = cursor_background.attr | cursor;
4621             ccount = 1;
4622
4623             if (cursor_background.cc_next) {
4624                 termchar *dd = ldata->chars + cursor_background.cc_next;
4625
4626                 while (1) {
4627                     unsigned long schar;
4628
4629                     schar = dd->chr;
4630                     switch (schar & CSET_MASK) {
4631                       case CSET_ASCII:
4632                         schar = term->ucsdata->unitab_line[schar & 0xFF];
4633                         break;
4634                       case CSET_LINEDRW:
4635                         schar = term->ucsdata->unitab_xterm[schar & 0xFF];
4636                         break;
4637                       case CSET_SCOACS:
4638                         schar = term->ucsdata->unitab_scoacs[schar&0xFF];
4639                         break;
4640                     }
4641
4642                     if (ccount >= chlen) {
4643                         chlen = ccount + 256;
4644                         ch = sresize(ch, chlen, wchar_t);
4645                     }
4646                     ch[ccount++] = (wchar_t) schar;
4647
4648                     if (dd->cc_next)
4649                         dd += dd->cc_next;
4650                     else
4651                         break;
4652                 }
4653
4654                 attr |= TATTR_COMBINING;
4655             }
4656
4657             do_cursor(ctx, our_curs_x, i, ch, ccount, attr, ldata->lattr);
4658             term->curstype = cursor;
4659         }
4660
4661         unlineptr(ldata);
4662     }
4663
4664     sfree(ch);
4665 }
4666
4667 /*
4668  * Flick the switch that says if blinking things should be shown or hidden.
4669  */
4670
4671 void term_blink(Terminal *term, int flg)
4672 {
4673     long now, blink_diff;
4674
4675     now = GETTICKCOUNT();
4676     blink_diff = now - term->last_tblink;
4677
4678     /* Make sure the text blinks no more than 2Hz; we'll use 0.45 s period. */
4679     if (blink_diff < 0 || blink_diff > (TICKSPERSEC * 9 / 20)) {
4680         term->last_tblink = now;
4681         term->tblinker = !term->tblinker;
4682     }
4683
4684     if (flg) {
4685         term->blinker = 1;
4686         term->last_blink = now;
4687         return;
4688     }
4689
4690     blink_diff = now - term->last_blink;
4691
4692     /* Make sure the cursor blinks no faster than system blink rate */
4693     if (blink_diff >= 0 && blink_diff < (long) CURSORBLINK)
4694         return;
4695
4696     term->last_blink = now;
4697     term->blinker = !term->blinker;
4698 }
4699
4700 /*
4701  * Invalidate the whole screen so it will be repainted in full.
4702  */
4703 void term_invalidate(Terminal *term)
4704 {
4705     int i, j;
4706
4707     for (i = 0; i < term->rows; i++)
4708         for (j = 0; j < term->cols; j++)
4709             term->disptext[i]->chars[j].attr = ATTR_INVALID;
4710 }
4711
4712 /*
4713  * Paint the window in response to a WM_PAINT message.
4714  */
4715 void term_paint(Terminal *term, Context ctx,
4716                 int left, int top, int right, int bottom, int immediately)
4717 {
4718     int i, j;
4719     if (left < 0) left = 0;
4720     if (top < 0) top = 0;
4721     if (right >= term->cols) right = term->cols-1;
4722     if (bottom >= term->rows) bottom = term->rows-1;
4723
4724     for (i = top; i <= bottom && i < term->rows; i++) {
4725         if ((term->disptext[i]->lattr & LATTR_MODE) == LATTR_NORM)
4726             for (j = left; j <= right && j < term->cols; j++)
4727                 term->disptext[i]->chars[j].attr = ATTR_INVALID;
4728         else
4729             for (j = left / 2; j <= right / 2 + 1 && j < term->cols; j++)
4730                 term->disptext[i]->chars[j].attr = ATTR_INVALID;
4731     }
4732
4733     /* This should happen soon enough, also for some reason it sometimes 
4734      * fails to actually do anything when re-sizing ... painting the wrong
4735      * window perhaps ?
4736      */
4737     if (immediately)
4738         do_paint (term, ctx, FALSE);
4739 }
4740
4741 /*
4742  * Attempt to scroll the scrollback. The second parameter gives the
4743  * position we want to scroll to; the first is +1 to denote that
4744  * this position is relative to the beginning of the scrollback, -1
4745  * to denote it is relative to the end, and 0 to denote that it is
4746  * relative to the current position.
4747  */
4748 void term_scroll(Terminal *term, int rel, int where)
4749 {
4750     int sbtop = -sblines(term);
4751 #ifdef OPTIMISE_SCROLL
4752     int olddisptop = term->disptop;
4753     int shift;
4754 #endif /* OPTIMISE_SCROLL */
4755
4756     term->disptop = (rel < 0 ? 0 : rel > 0 ? sbtop : term->disptop) + where;
4757     if (term->disptop < sbtop)
4758         term->disptop = sbtop;
4759     if (term->disptop > 0)
4760         term->disptop = 0;
4761     update_sbar(term);
4762 #ifdef OPTIMISE_SCROLL
4763     shift = (term->disptop - olddisptop);
4764     if (shift < term->rows && shift > -term->rows)
4765         scroll_display(term, 0, term->rows - 1, shift);
4766 #endif /* OPTIMISE_SCROLL */
4767     term_update(term);
4768 }
4769
4770 static void clipme(Terminal *term, pos top, pos bottom, int rect, int desel)
4771 {
4772     wchar_t *workbuf;
4773     wchar_t *wbptr;                    /* where next char goes within workbuf */
4774     int old_top_x;
4775     int wblen = 0;                     /* workbuf len */
4776     int buflen;                        /* amount of memory allocated to workbuf */
4777
4778     buflen = 5120;                     /* Default size */
4779     workbuf = snewn(buflen, wchar_t);
4780     wbptr = workbuf;                   /* start filling here */
4781     old_top_x = top.x;                 /* needed for rect==1 */
4782
4783     while (poslt(top, bottom)) {
4784         int nl = FALSE;
4785         termline *ldata = lineptr(top.y);
4786         pos nlpos;
4787
4788         /*
4789          * nlpos will point at the maximum position on this line we
4790          * should copy up to. So we start it at the end of the
4791          * line...
4792          */
4793         nlpos.y = top.y;
4794         nlpos.x = term->cols;
4795
4796         /*
4797          * ... move it backwards if there's unused space at the end
4798          * of the line (and also set `nl' if this is the case,
4799          * because in normal selection mode this means we need a
4800          * newline at the end)...
4801          */
4802         if (!(ldata->lattr & LATTR_WRAPPED)) {
4803             while (IS_SPACE_CHR(ldata->chars[nlpos.x - 1].chr) &&
4804                    poslt(top, nlpos))
4805                 decpos(nlpos);
4806             if (poslt(nlpos, bottom))
4807                 nl = TRUE;
4808         } else if (ldata->lattr & LATTR_WRAPPED2) {
4809             /* Ignore the last char on the line in a WRAPPED2 line. */
4810             decpos(nlpos);
4811         }
4812
4813         /*
4814          * ... and then clip it to the terminal x coordinate if
4815          * we're doing rectangular selection. (In this case we
4816          * still did the above, so that copying e.g. the right-hand
4817          * column from a table doesn't fill with spaces on the
4818          * right.)
4819          */
4820         if (rect) {
4821             if (nlpos.x > bottom.x)
4822                 nlpos.x = bottom.x;
4823             nl = (top.y < bottom.y);
4824         }
4825
4826         while (poslt(top, bottom) && poslt(top, nlpos)) {
4827 #if 0
4828             char cbuf[16], *p;
4829             sprintf(cbuf, "<U+%04x>", (ldata[top.x] & 0xFFFF));
4830 #else
4831             wchar_t cbuf[16], *p;
4832             int set, c;
4833             int x = top.x;
4834
4835             if (ldata->chars[x].chr == UCSWIDE) {
4836                 top.x++;
4837                 continue;
4838             }
4839
4840             while (1) {
4841                 int uc = ldata->chars[x].chr;
4842
4843                 switch (uc & CSET_MASK) {
4844                   case CSET_LINEDRW:
4845                     if (!term->cfg.rawcnp) {
4846                         uc = term->ucsdata->unitab_xterm[uc & 0xFF];
4847                         break;
4848                     }
4849                   case CSET_ASCII:
4850                     uc = term->ucsdata->unitab_line[uc & 0xFF];
4851                     break;
4852                   case CSET_SCOACS:
4853                     uc = term->ucsdata->unitab_scoacs[uc&0xFF];
4854                     break;
4855                 }
4856                 switch (uc & CSET_MASK) {
4857                   case CSET_ACP:
4858                     uc = term->ucsdata->unitab_font[uc & 0xFF];
4859                     break;
4860                   case CSET_OEMCP:
4861                     uc = term->ucsdata->unitab_oemcp[uc & 0xFF];
4862                     break;
4863                 }
4864
4865                 set = (uc & CSET_MASK);
4866                 c = (uc & ~CSET_MASK);
4867                 cbuf[0] = uc;
4868                 cbuf[1] = 0;
4869
4870                 if (DIRECT_FONT(uc)) {
4871                     if (c >= ' ' && c != 0x7F) {
4872                         char buf[4];
4873                         WCHAR wbuf[4];
4874                         int rv;
4875                         if (is_dbcs_leadbyte(term->ucsdata->font_codepage, (BYTE) c)) {
4876                             buf[0] = c;
4877                             buf[1] = (char) (0xFF & ldata->chars[top.x + 1].chr);
4878                             rv = mb_to_wc(term->ucsdata->font_codepage, 0, buf, 2, wbuf, 4);
4879                             top.x++;
4880                         } else {
4881                             buf[0] = c;
4882                             rv = mb_to_wc(term->ucsdata->font_codepage, 0, buf, 1, wbuf, 4);
4883                         }
4884
4885                         if (rv > 0) {
4886                             memcpy(cbuf, wbuf, rv * sizeof(wchar_t));
4887                             cbuf[rv] = 0;
4888                         }
4889                     }
4890                 }
4891 #endif
4892
4893                 for (p = cbuf; *p; p++) {
4894                     /* Enough overhead for trailing NL and nul */
4895                     if (wblen >= buflen - 16) {
4896                         buflen += 100;
4897                         workbuf = sresize(workbuf, buflen, wchar_t);
4898                         wbptr = workbuf + wblen;
4899                     }
4900                     wblen++;
4901                     *wbptr++ = *p;
4902                 }
4903
4904                 if (ldata->chars[x].cc_next)
4905                     x += ldata->chars[x].cc_next;
4906                 else
4907                     break;
4908             }
4909             top.x++;
4910         }
4911         if (nl) {
4912             int i;
4913             for (i = 0; i < sel_nl_sz; i++) {
4914                 wblen++;
4915                 *wbptr++ = sel_nl[i];
4916             }
4917         }
4918         top.y++;
4919         top.x = rect ? old_top_x : 0;
4920
4921         unlineptr(ldata);
4922     }
4923 #if SELECTION_NUL_TERMINATED
4924     wblen++;
4925     *wbptr++ = 0;
4926 #endif
4927     write_clip(term->frontend, workbuf, wblen, desel); /* transfer to clipbd */
4928     if (buflen > 0)                    /* indicates we allocated this buffer */
4929         sfree(workbuf);
4930 }
4931
4932 void term_copyall(Terminal *term)
4933 {
4934     pos top;
4935     pos bottom;
4936     tree234 *screen = term->screen;
4937     top.y = -sblines(term);
4938     top.x = 0;
4939     bottom.y = find_last_nonempty_line(term, screen);
4940     bottom.x = term->cols;
4941     clipme(term, top, bottom, 0, TRUE);
4942 }
4943
4944 /*
4945  * The wordness array is mainly for deciding the disposition of the
4946  * US-ASCII characters.
4947  */
4948 static int wordtype(Terminal *term, int uc)
4949 {
4950     struct ucsword {
4951         int start, end, ctype;
4952     };
4953     static const struct ucsword ucs_words[] = {
4954         {
4955         128, 160, 0}, {
4956         161, 191, 1}, {
4957         215, 215, 1}, {
4958         247, 247, 1}, {
4959         0x037e, 0x037e, 1},            /* Greek question mark */
4960         {
4961         0x0387, 0x0387, 1},            /* Greek ano teleia */
4962         {
4963         0x055a, 0x055f, 1},            /* Armenian punctuation */
4964         {
4965         0x0589, 0x0589, 1},            /* Armenian full stop */
4966         {
4967         0x0700, 0x070d, 1},            /* Syriac punctuation */
4968         {
4969         0x104a, 0x104f, 1},            /* Myanmar punctuation */
4970         {
4971         0x10fb, 0x10fb, 1},            /* Georgian punctuation */
4972         {
4973         0x1361, 0x1368, 1},            /* Ethiopic punctuation */
4974         {
4975         0x166d, 0x166e, 1},            /* Canadian Syl. punctuation */
4976         {
4977         0x17d4, 0x17dc, 1},            /* Khmer punctuation */
4978         {
4979         0x1800, 0x180a, 1},            /* Mongolian punctuation */
4980         {
4981         0x2000, 0x200a, 0},            /* Various spaces */
4982         {
4983         0x2070, 0x207f, 2},            /* superscript */
4984         {
4985         0x2080, 0x208f, 2},            /* subscript */
4986         {
4987         0x200b, 0x27ff, 1},            /* punctuation and symbols */
4988         {
4989         0x3000, 0x3000, 0},            /* ideographic space */
4990         {
4991         0x3001, 0x3020, 1},            /* ideographic punctuation */
4992         {
4993         0x303f, 0x309f, 3},            /* Hiragana */
4994         {
4995         0x30a0, 0x30ff, 3},            /* Katakana */
4996         {
4997         0x3300, 0x9fff, 3},            /* CJK Ideographs */
4998         {
4999         0xac00, 0xd7a3, 3},            /* Hangul Syllables */
5000         {
5001         0xf900, 0xfaff, 3},            /* CJK Ideographs */
5002         {
5003         0xfe30, 0xfe6b, 1},            /* punctuation forms */
5004         {
5005         0xff00, 0xff0f, 1},            /* half/fullwidth ASCII */
5006         {
5007         0xff1a, 0xff20, 1},            /* half/fullwidth ASCII */
5008         {
5009         0xff3b, 0xff40, 1},            /* half/fullwidth ASCII */
5010         {
5011         0xff5b, 0xff64, 1},            /* half/fullwidth ASCII */
5012         {
5013         0xfff0, 0xffff, 0},            /* half/fullwidth ASCII */
5014         {
5015         0, 0, 0}
5016     };
5017     const struct ucsword *wptr;
5018
5019     switch (uc & CSET_MASK) {
5020       case CSET_LINEDRW:
5021         uc = term->ucsdata->unitab_xterm[uc & 0xFF];
5022         break;
5023       case CSET_ASCII:
5024         uc = term->ucsdata->unitab_line[uc & 0xFF];
5025         break;
5026       case CSET_SCOACS:  
5027         uc = term->ucsdata->unitab_scoacs[uc&0xFF]; 
5028         break;
5029     }
5030     switch (uc & CSET_MASK) {
5031       case CSET_ACP:
5032         uc = term->ucsdata->unitab_font[uc & 0xFF];
5033         break;
5034       case CSET_OEMCP:
5035         uc = term->ucsdata->unitab_oemcp[uc & 0xFF];
5036         break;
5037     }
5038
5039     /* For DBCS fonts I can't do anything useful. Even this will sometimes
5040      * fail as there's such a thing as a double width space. :-(
5041      */
5042     if (term->ucsdata->dbcs_screenfont &&
5043         term->ucsdata->font_codepage == term->ucsdata->line_codepage)
5044         return (uc != ' ');
5045
5046     if (uc < 0x80)
5047         return term->wordness[uc];
5048
5049     for (wptr = ucs_words; wptr->start; wptr++) {
5050         if (uc >= wptr->start && uc <= wptr->end)
5051             return wptr->ctype;
5052     }
5053
5054     return 2;
5055 }
5056
5057 /*
5058  * Spread the selection outwards according to the selection mode.
5059  */
5060 static pos sel_spread_half(Terminal *term, pos p, int dir)
5061 {
5062     termline *ldata;
5063     short wvalue;
5064     int topy = -sblines(term);
5065
5066     ldata = lineptr(p.y);
5067
5068     switch (term->selmode) {
5069       case SM_CHAR:
5070         /*
5071          * In this mode, every character is a separate unit, except
5072          * for runs of spaces at the end of a non-wrapping line.
5073          */
5074         if (!(ldata->lattr & LATTR_WRAPPED)) {
5075             termchar *q = ldata->chars + term->cols;
5076             while (q > ldata->chars && IS_SPACE_CHR(q[-1].chr))
5077                 q--;
5078             if (q == ldata->chars + term->cols)
5079                 q--;
5080             if (p.x >= q - ldata->chars)
5081                 p.x = (dir == -1 ? q - ldata->chars : term->cols - 1);
5082         }
5083         break;
5084       case SM_WORD:
5085         /*
5086          * In this mode, the units are maximal runs of characters
5087          * whose `wordness' has the same value.
5088          */
5089         wvalue = wordtype(term, UCSGET(ldata->chars, p.x));
5090         if (dir == +1) {
5091             while (1) {
5092                 int maxcols = (ldata->lattr & LATTR_WRAPPED2 ?
5093                                term->cols-1 : term->cols);
5094                 if (p.x < maxcols-1) {
5095                     if (wordtype(term, UCSGET(ldata->chars, p.x+1)) == wvalue)
5096                         p.x++;
5097                     else
5098                         break;
5099                 } else {
5100                     if (ldata->lattr & LATTR_WRAPPED) {
5101                         termline *ldata2;
5102                         ldata2 = lineptr(p.y+1);
5103                         if (wordtype(term, UCSGET(ldata2->chars, 0))
5104                             == wvalue) {
5105                             p.x = 0;
5106                             p.y++;
5107                             unlineptr(ldata);
5108                             ldata = ldata2;
5109                         } else {
5110                             unlineptr(ldata2);
5111                             break;
5112                         }
5113                     } else
5114                         break;
5115                 }
5116             }
5117         } else {
5118             while (1) {
5119                 if (p.x > 0) {
5120                     if (wordtype(term, UCSGET(ldata->chars, p.x-1)) == wvalue)
5121                         p.x--;
5122                     else
5123                         break;
5124                 } else {
5125                     termline *ldata2;
5126                     int maxcols;
5127                     if (p.y <= topy)
5128                         break;
5129                     ldata2 = lineptr(p.y-1);
5130                     maxcols = (ldata2->lattr & LATTR_WRAPPED2 ?
5131                               term->cols-1 : term->cols);
5132                     if (ldata2->lattr & LATTR_WRAPPED) {
5133                         if (wordtype(term, UCSGET(ldata2->chars, maxcols-1))
5134                             == wvalue) {
5135                             p.x = maxcols-1;
5136                             p.y--;
5137                             unlineptr(ldata);
5138                             ldata = ldata2;
5139                         } else {
5140                             unlineptr(ldata2);
5141                             break;
5142                         }
5143                     } else
5144                         break;
5145                 }
5146             }
5147         }
5148         break;
5149       case SM_LINE:
5150         /*
5151          * In this mode, every line is a unit.
5152          */
5153         p.x = (dir == -1 ? 0 : term->cols - 1);
5154         break;
5155     }
5156
5157     unlineptr(ldata);
5158     return p;
5159 }
5160
5161 static void sel_spread(Terminal *term)
5162 {
5163     if (term->seltype == LEXICOGRAPHIC) {
5164         term->selstart = sel_spread_half(term, term->selstart, -1);
5165         decpos(term->selend);
5166         term->selend = sel_spread_half(term, term->selend, +1);
5167         incpos(term->selend);
5168     }
5169 }
5170
5171 void term_do_paste(Terminal *term)
5172 {
5173     wchar_t *data;
5174     int len;
5175
5176     get_clip(term->frontend, &data, &len);
5177     if (data && len > 0) {
5178         wchar_t *p, *q;
5179
5180         term_seen_key_event(term);     /* pasted data counts */
5181
5182         if (term->paste_buffer)
5183             sfree(term->paste_buffer);
5184         term->paste_pos = term->paste_hold = term->paste_len = 0;
5185         term->paste_buffer = snewn(len, wchar_t);
5186
5187         p = q = data;
5188         while (p < data + len) {
5189             while (p < data + len &&
5190                    !(p <= data + len - sel_nl_sz &&
5191                      !memcmp(p, sel_nl, sizeof(sel_nl))))
5192                 p++;
5193
5194             {
5195                 int i;
5196                 for (i = 0; i < p - q; i++) {
5197                     term->paste_buffer[term->paste_len++] = q[i];
5198                 }
5199             }
5200
5201             if (p <= data + len - sel_nl_sz &&
5202                 !memcmp(p, sel_nl, sizeof(sel_nl))) {
5203                 term->paste_buffer[term->paste_len++] = '\015';
5204                 p += sel_nl_sz;
5205             }
5206             q = p;
5207         }
5208
5209         /* Assume a small paste will be OK in one go. */
5210         if (term->paste_len < 256) {
5211             if (term->ldisc)
5212                 luni_send(term->ldisc, term->paste_buffer, term->paste_len, 0);
5213             if (term->paste_buffer)
5214                 sfree(term->paste_buffer);
5215             term->paste_buffer = 0;
5216             term->paste_pos = term->paste_hold = term->paste_len = 0;
5217         }
5218     }
5219     get_clip(term->frontend, NULL, NULL);
5220 }
5221
5222 void term_mouse(Terminal *term, Mouse_Button braw, Mouse_Button bcooked,
5223                 Mouse_Action a, int x, int y, int shift, int ctrl, int alt)
5224 {
5225     pos selpoint;
5226     termline *ldata;
5227     int raw_mouse = (term->xterm_mouse &&
5228                      !term->cfg.no_mouse_rep &&
5229                      !(term->cfg.mouse_override && shift));
5230     int default_seltype;
5231
5232     if (y < 0) {
5233         y = 0;
5234         if (a == MA_DRAG && !raw_mouse)
5235             term_scroll(term, 0, -1);
5236     }
5237     if (y >= term->rows) {
5238         y = term->rows - 1;
5239         if (a == MA_DRAG && !raw_mouse)
5240             term_scroll(term, 0, +1);
5241     }
5242     if (x < 0) {
5243         if (y > 0) {
5244             x = term->cols - 1;
5245             y--;
5246         } else
5247             x = 0;
5248     }
5249     if (x >= term->cols)
5250         x = term->cols - 1;
5251
5252     selpoint.y = y + term->disptop;
5253     selpoint.x = x;
5254     ldata = lineptr(selpoint.y);
5255     if ((ldata->lattr & LATTR_MODE) != LATTR_NORM)
5256         selpoint.x /= 2;
5257     unlineptr(ldata);
5258
5259     if (raw_mouse) {
5260         int encstate = 0, r, c;
5261         char abuf[16];
5262
5263         if (term->ldisc) {
5264
5265             switch (braw) {
5266               case MBT_LEFT:
5267                 encstate = 0x20;               /* left button down */
5268                 break;
5269               case MBT_MIDDLE:
5270                 encstate = 0x21;
5271                 break;
5272               case MBT_RIGHT:
5273                 encstate = 0x22;
5274                 break;
5275               case MBT_WHEEL_UP:
5276                 encstate = 0x60;
5277                 break;
5278               case MBT_WHEEL_DOWN:
5279                 encstate = 0x61;
5280                 break;
5281               default: break;          /* placate gcc warning about enum use */
5282             }
5283             switch (a) {
5284               case MA_DRAG:
5285                 if (term->xterm_mouse == 1)
5286                     return;
5287                 encstate += 0x20;
5288                 break;
5289               case MA_RELEASE:
5290                 encstate = 0x23;
5291                 term->mouse_is_down = 0;
5292                 break;
5293               case MA_CLICK:
5294                 if (term->mouse_is_down == braw)
5295                     return;
5296                 term->mouse_is_down = braw;
5297                 break;
5298               default: break;          /* placate gcc warning about enum use */
5299             }
5300             if (shift)
5301                 encstate += 0x04;
5302             if (ctrl)
5303                 encstate += 0x10;
5304             r = y + 33;
5305             c = x + 33;
5306
5307             sprintf(abuf, "\033[M%c%c%c", encstate, c, r);
5308             ldisc_send(term->ldisc, abuf, 6, 0);
5309         }
5310         return;
5311     }
5312
5313     /*
5314      * Set the selection type (rectangular or normal) at the start
5315      * of a selection attempt, from the state of Alt.
5316      */
5317     if (!alt ^ !term->cfg.rect_select)
5318         default_seltype = RECTANGULAR;
5319     else
5320         default_seltype = LEXICOGRAPHIC;
5321         
5322     if (term->selstate == NO_SELECTION) {
5323         term->seltype = default_seltype;
5324     }
5325
5326     if (bcooked == MBT_SELECT && a == MA_CLICK) {
5327         deselect(term);
5328         term->selstate = ABOUT_TO;
5329         term->seltype = default_seltype;
5330         term->selanchor = selpoint;
5331         term->selmode = SM_CHAR;
5332     } else if (bcooked == MBT_SELECT && (a == MA_2CLK || a == MA_3CLK)) {
5333         deselect(term);
5334         term->selmode = (a == MA_2CLK ? SM_WORD : SM_LINE);
5335         term->selstate = DRAGGING;
5336         term->selstart = term->selanchor = selpoint;
5337         term->selend = term->selstart;
5338         incpos(term->selend);
5339         sel_spread(term);
5340     } else if ((bcooked == MBT_SELECT && a == MA_DRAG) ||
5341                (bcooked == MBT_EXTEND && a != MA_RELEASE)) {
5342         if (term->selstate == ABOUT_TO && poseq(term->selanchor, selpoint))
5343             return;
5344         if (bcooked == MBT_EXTEND && a != MA_DRAG &&
5345             term->selstate == SELECTED) {
5346             if (term->seltype == LEXICOGRAPHIC) {
5347                 /*
5348                  * For normal selection, we extend by moving
5349                  * whichever end of the current selection is closer
5350                  * to the mouse.
5351                  */
5352                 if (posdiff(selpoint, term->selstart) <
5353                     posdiff(term->selend, term->selstart) / 2) {
5354                     term->selanchor = term->selend;
5355                     decpos(term->selanchor);
5356                 } else {
5357                     term->selanchor = term->selstart;
5358                 }
5359             } else {
5360                 /*
5361                  * For rectangular selection, we have a choice of
5362                  * _four_ places to put selanchor and selpoint: the
5363                  * four corners of the selection.
5364                  */
5365                 if (2*selpoint.x < term->selstart.x + term->selend.x)
5366                     term->selanchor.x = term->selend.x-1;
5367                 else
5368                     term->selanchor.x = term->selstart.x;
5369
5370                 if (2*selpoint.y < term->selstart.y + term->selend.y)
5371                     term->selanchor.y = term->selend.y;
5372                 else
5373                     term->selanchor.y = term->selstart.y;
5374             }
5375             term->selstate = DRAGGING;
5376         }
5377         if (term->selstate != ABOUT_TO && term->selstate != DRAGGING)
5378             term->selanchor = selpoint;
5379         term->selstate = DRAGGING;
5380         if (term->seltype == LEXICOGRAPHIC) {
5381             /*
5382              * For normal selection, we set (selstart,selend) to
5383              * (selpoint,selanchor) in some order.
5384              */
5385             if (poslt(selpoint, term->selanchor)) {
5386                 term->selstart = selpoint;
5387                 term->selend = term->selanchor;
5388                 incpos(term->selend);
5389             } else {
5390                 term->selstart = term->selanchor;
5391                 term->selend = selpoint;
5392                 incpos(term->selend);
5393             }
5394         } else {
5395             /*
5396              * For rectangular selection, we may need to
5397              * interchange x and y coordinates (if the user has
5398              * dragged in the -x and +y directions, or vice versa).
5399              */
5400             term->selstart.x = min(term->selanchor.x, selpoint.x);
5401             term->selend.x = 1+max(term->selanchor.x, selpoint.x);
5402             term->selstart.y = min(term->selanchor.y, selpoint.y);
5403             term->selend.y =   max(term->selanchor.y, selpoint.y);
5404         }
5405         sel_spread(term);
5406     } else if ((bcooked == MBT_SELECT || bcooked == MBT_EXTEND) &&
5407                a == MA_RELEASE) {
5408         if (term->selstate == DRAGGING) {
5409             /*
5410              * We've completed a selection. We now transfer the
5411              * data to the clipboard.
5412              */
5413             clipme(term, term->selstart, term->selend,
5414                    (term->seltype == RECTANGULAR), FALSE);
5415             term->selstate = SELECTED;
5416         } else
5417             term->selstate = NO_SELECTION;
5418     } else if (bcooked == MBT_PASTE
5419                && (a == MA_CLICK
5420 #if MULTICLICK_ONLY_EVENT
5421                    || a == MA_2CLK || a == MA_3CLK
5422 #endif
5423                    )) {
5424         request_paste(term->frontend);
5425     }
5426
5427     term_update(term);
5428 }
5429
5430 void term_key(Terminal *term, Key_Sym keysym, wchar_t *text, size_t tlen,
5431               unsigned int modifiers, unsigned int flags)
5432 {
5433     char output[10];
5434     char *p = output;
5435     int prependesc = FALSE;
5436 #if 0
5437     int i;
5438
5439     fprintf(stderr, "keysym = %d, %d chars:", keysym, tlen);
5440     for (i = 0; i < tlen; i++)
5441         fprintf(stderr, " %04x", (unsigned)text[i]);
5442     fprintf(stderr, "\n");
5443 #endif
5444
5445     /* XXX Num Lock */
5446     if ((flags & PKF_REPEAT) && term->repeat_off)
5447         return;
5448
5449     /* Currently, Meta always just prefixes everything with ESC. */
5450     if (modifiers & PKM_META)
5451         prependesc = TRUE;
5452     modifiers &= ~PKM_META;
5453
5454     /*
5455      * Alt is only used for Alt+keypad, which isn't supported yet, so
5456      * ignore it.
5457      */
5458     modifiers &= ~PKM_ALT;
5459
5460     /* Standard local function keys */
5461     switch (modifiers & (PKM_SHIFT | PKM_CONTROL)) {
5462       case PKM_SHIFT:
5463         if (keysym == PK_PAGEUP)
5464             /* scroll up one page */;
5465         if (keysym == PK_PAGEDOWN)
5466             /* scroll down on page */;
5467         if (keysym == PK_INSERT)
5468             term_do_paste(term);
5469         break;
5470       case PKM_CONTROL:
5471         if (keysym == PK_PAGEUP)
5472             /* scroll up one line */;
5473         if (keysym == PK_PAGEDOWN)
5474             /* scroll down one line */;
5475         /* Control-Numlock for app-keypad mode switch */
5476         if (keysym == PK_PF1)
5477             term->app_keypad_keys ^= 1;
5478         break;
5479     }
5480
5481     if (modifiers & PKM_ALT) {
5482         /* Alt+F4 (close) */
5483         /* Alt+Return (full screen) */
5484         /* Alt+Space (system menu) */
5485     }
5486
5487     if (keysym == PK_NULL && (modifiers & PKM_CONTROL) && tlen == 1 &&
5488         text[0] >= 0x20 && text[0] <= 0x7e) {
5489         /* ASCII chars + Control */
5490         if ((text[0] >= 0x40 && text[0] <= 0x5f) ||
5491             (text[0] >= 0x61 && text[0] <= 0x7a))
5492             text[0] &= 0x1f;
5493         else {
5494             /*
5495              * Control-2 should return ^@ (0x00), Control-6 should return
5496              * ^^ (0x1E), and Control-Minus should return ^_ (0x1F). Since
5497              * the DOS keyboard handling did it, and we have nothing better
5498              * to do with the key combo in question, we'll also map
5499              * Control-Backquote to ^\ (0x1C).
5500              */
5501             switch (text[0]) {
5502               case ' ': text[0] = 0x00; break;
5503               case '-': text[0] = 0x1f; break;
5504               case '/': text[0] = 0x1f; break;
5505               case '2': text[0] = 0x00; break;
5506               case '3': text[0] = 0x1b; break;
5507               case '4': text[0] = 0x1c; break;
5508               case '5': text[0] = 0x1d; break;
5509               case '6': text[0] = 0x1e; break;
5510               case '7': text[0] = 0x1f; break;
5511               case '8': text[0] = 0x7f; break;
5512               case '`': text[0] = 0x1c; break;
5513             }
5514         }
5515     }
5516
5517     /* Nethack keypad */
5518     if (term->cfg.nethack_keypad) {
5519         char c = 0;
5520         switch (keysym) {
5521           case PK_KP1: c = 'b'; break;
5522           case PK_KP2: c = 'j'; break;
5523           case PK_KP3: c = 'n'; break;
5524           case PK_KP4: c = 'h'; break;
5525           case PK_KP5: c = '.'; break;
5526           case PK_KP6: c = 'l'; break;
5527           case PK_KP7: c = 'y'; break;
5528           case PK_KP8: c = 'k'; break;
5529           case PK_KP9: c = 'u'; break;
5530           default: break; /* else gcc warns `enum value not used' */
5531         }
5532         if (c != 0) {
5533             if (c != '.') {
5534                 if (modifiers & PKM_CONTROL)
5535                     c &= 0x1f;
5536                 else if (modifiers & PKM_SHIFT)
5537                     c = toupper(c);
5538             }
5539             *p++ = c;
5540             goto done;
5541         }
5542     }
5543
5544     /* Numeric Keypad */
5545     if (PK_ISKEYPAD(keysym)) {
5546         int xkey = 0;
5547
5548         /*
5549          * In VT400 mode, PFn always emits an escape sequence.  In
5550          * Linux and tilde modes, this only happens in app keypad mode.
5551          */
5552         if (term->cfg.funky_type == FUNKY_VT400 ||
5553             ((term->cfg.funky_type == FUNKY_LINUX ||
5554               term->cfg.funky_type == FUNKY_TILDE) &&
5555              term->app_keypad_keys && !term->cfg.no_applic_k)) {
5556             switch (keysym) {
5557               case PK_PF1: xkey = 'P'; break;
5558               case PK_PF2: xkey = 'Q'; break;
5559               case PK_PF3: xkey = 'R'; break;
5560               case PK_PF4: xkey = 'S'; break;
5561               default: break; /* else gcc warns `enum value not used' */
5562             }
5563         }
5564         if (term->app_keypad_keys && !term->cfg.no_applic_k) {
5565             switch (keysym) {
5566               case PK_KP0: xkey = 'p'; break;
5567               case PK_KP1: xkey = 'q'; break;
5568               case PK_KP2: xkey = 'r'; break;
5569               case PK_KP3: xkey = 's'; break;
5570               case PK_KP4: xkey = 't'; break;
5571               case PK_KP5: xkey = 'u'; break;
5572               case PK_KP6: xkey = 'v'; break;
5573               case PK_KP7: xkey = 'w'; break;
5574               case PK_KP8: xkey = 'x'; break;
5575               case PK_KP9: xkey = 'y'; break;
5576               case PK_KPDECIMAL: xkey = 'n'; break;
5577               case PK_KPENTER: xkey = 'M'; break;
5578               default: break; /* else gcc warns `enum value not used' */
5579             }
5580             if (term->cfg.funky_type == FUNKY_XTERM && tlen > 0) {
5581                 /*
5582                  * xterm can't see the layout of the keypad, so it has
5583                  * to rely on the X keysyms returned by the keys.
5584                  * Hence, we look at the strings here, not the PuTTY
5585                  * keysyms (which describe the layout).
5586                  */
5587                 switch (text[0]) {
5588                   case '+':
5589                     if (modifiers & PKM_SHIFT)
5590                         xkey = 'l';
5591                     else
5592                         xkey = 'k';
5593                     break;
5594                   case '/': xkey = 'o'; break;
5595                   case '*': xkey = 'j'; break;
5596                   case '-': xkey = 'm'; break;
5597                 }
5598             } else {
5599                 /*
5600                  * In all other modes, we try to retain the layout of
5601                  * the DEC keypad in application mode.
5602                  */
5603                 switch (keysym) {
5604                   case PK_KPBIGPLUS:
5605                     /* This key covers the '-' and ',' keys on a VT220 */
5606                     if (modifiers & PKM_SHIFT)
5607                         xkey = 'm'; /* VT220 '-' */
5608                     else
5609                         xkey = 'l'; /* VT220 ',' */
5610                     break;
5611                   case PK_KPMINUS: xkey = 'm'; break;
5612                   case PK_KPCOMMA: xkey = 'l'; break;
5613                   default: break; /* else gcc warns `enum value not used' */
5614                 }
5615             }
5616         }
5617         if (xkey) {
5618             if (term->vt52_mode) {
5619                 if (xkey >= 'P' && xkey <= 'S')
5620                     p += sprintf((char *) p, "\x1B%c", xkey);
5621                 else
5622                     p += sprintf((char *) p, "\x1B?%c", xkey);
5623             } else
5624                 p += sprintf((char *) p, "\x1BO%c", xkey);
5625             goto done;
5626         }
5627         /* Not in application mode -- treat the number pad as arrow keys? */
5628         if ((flags & PKF_NUMLOCK) == 0) {
5629             switch (keysym) {
5630               case PK_KP0: keysym = PK_INSERT; break;
5631               case PK_KP1: keysym = PK_END; break;
5632               case PK_KP2: keysym = PK_DOWN; break;
5633               case PK_KP3: keysym = PK_PAGEDOWN; break;
5634               case PK_KP4: keysym = PK_LEFT; break;
5635               case PK_KP5: keysym = PK_REST; break;
5636               case PK_KP6: keysym = PK_RIGHT; break;
5637               case PK_KP7: keysym = PK_HOME; break;
5638               case PK_KP8: keysym = PK_UP; break;
5639               case PK_KP9: keysym = PK_PAGEUP; break;
5640               default: break; /* else gcc warns `enum value not used' */
5641             }
5642         }
5643     }
5644
5645     /* Miscellaneous keys */
5646     switch (keysym) {
5647       case PK_ESCAPE:
5648         *p++ = 0x1b;
5649         goto done;
5650       case PK_BACKSPACE:
5651             if (modifiers == 0)
5652                 *p++ = (term->cfg.bksp_is_delete ? 0x7F : 0x08);
5653             else if (modifiers == PKM_SHIFT)
5654                 /* We do the opposite of what is configured */
5655                 *p++ = (term->cfg.bksp_is_delete ? 0x08 : 0x7F);
5656             else break;
5657             goto done;
5658       case PK_TAB:
5659         if (modifiers == 0)
5660             *p++ = 0x09;
5661         else if (modifiers == PKM_SHIFT)
5662             *p++ = 0x1B, *p++ = '[', *p++ = 'Z';
5663         else break;
5664         goto done;
5665         /* XXX window.c has ctrl+shift+space sending 0xa0 */
5666       case PK_PAUSE:
5667         if (modifiers == PKM_CONTROL)
5668             *p++ = 26;
5669         else break;
5670         goto done;
5671       case PK_RETURN:
5672       case PK_KPENTER: /* Odd keypad modes handled above */
5673         if (modifiers == 0) {
5674             *p++ = 0x0d;
5675             if (term->cr_lf_return)
5676                 *p++ = 0x0a;
5677             goto done;
5678         }
5679       default: break; /* else gcc warns `enum value not used' */
5680     }
5681
5682     /* SCO function keys and editing keys */
5683     if (term->cfg.funky_type == FUNKY_SCO) {
5684         if (PK_ISFKEY(keysym) && keysym <= PK_F12) {
5685             static char const codes[] =
5686                 "MNOPQRSTUVWX" "YZabcdefghij" "klmnopqrstuv" "wxyz@[\\]^_`{";
5687             int index = keysym - PK_F1;
5688
5689             if (modifiers & PKM_SHIFT) index += 12;
5690             if (modifiers & PKM_CONTROL) index += 24;
5691             p += sprintf((char *) p, "\x1B[%c", codes[index]);
5692             goto done;
5693         }
5694         if (PK_ISEDITING(keysym)) {
5695             int xkey = 0;
5696
5697             switch (keysym) {
5698               case PK_DELETE:   *p++ = 0x7f; goto done;
5699               case PK_HOME:     xkey = 'H'; break;
5700               case PK_INSERT:   xkey = 'L'; break;
5701               case PK_END:      xkey = 'F'; break;
5702               case PK_PAGEUP:   xkey = 'I'; break;
5703               case PK_PAGEDOWN: xkey = 'G'; break;
5704               default: break; /* else gcc warns `enum value not used' */
5705             }
5706             p += sprintf((char *) p, "\x1B[%c", xkey);
5707         }
5708     }
5709
5710     if (PK_ISEDITING(keysym) && (modifiers & PKM_SHIFT) == 0) {
5711         int code;
5712
5713         if (term->cfg.funky_type == FUNKY_XTERM) {
5714             /* Xterm shuffles these keys, apparently. */
5715             switch (keysym) {
5716               case PK_HOME:     keysym = PK_INSERT;   break;
5717               case PK_INSERT:   keysym = PK_HOME;     break;
5718               case PK_DELETE:   keysym = PK_END;      break;
5719               case PK_END:      keysym = PK_PAGEUP;   break;
5720               case PK_PAGEUP:   keysym = PK_DELETE;   break;
5721               case PK_PAGEDOWN: keysym = PK_PAGEDOWN; break;
5722               default: break; /* else gcc warns `enum value not used' */
5723             }
5724         }
5725
5726         /* RXVT Home/End */
5727         if (term->cfg.rxvt_homeend &&
5728             (keysym == PK_HOME || keysym == PK_END)) {
5729             p += sprintf((char *) p, keysym == PK_HOME ? "\x1B[H" : "\x1BOw");
5730             goto done;
5731         }
5732
5733         if (term->vt52_mode) {
5734             int xkey;
5735
5736             /*
5737              * A real VT52 doesn't have these, and a VT220 doesn't
5738              * send anything for them in VT52 mode.
5739              */
5740             switch (keysym) {
5741               case PK_HOME:     xkey = 'H'; break;
5742               case PK_INSERT:   xkey = 'L'; break;
5743               case PK_DELETE:   xkey = 'M'; break;
5744               case PK_END:      xkey = 'E'; break;
5745               case PK_PAGEUP:   xkey = 'I'; break;
5746               case PK_PAGEDOWN: xkey = 'G'; break;
5747               default: xkey=0; break; /* else gcc warns `enum value not used'*/
5748             }
5749             p += sprintf((char *) p, "\x1B%c", xkey);
5750             goto done;
5751         }
5752
5753         switch (keysym) {
5754           case PK_HOME:     code = 1; break;
5755           case PK_INSERT:   code = 2; break;
5756           case PK_DELETE:   code = 3; break;
5757           case PK_END:      code = 4; break;
5758           case PK_PAGEUP:   code = 5; break;
5759           case PK_PAGEDOWN: code = 6; break;
5760           default: code = 0; break; /* else gcc warns `enum value not used' */
5761         }
5762         p += sprintf((char *) p, "\x1B[%d~", code);
5763         goto done;
5764     }
5765
5766     if (PK_ISFKEY(keysym)) {
5767         /* Map Shift+F1-F10 to F11-F20 */
5768         if (keysym >= PK_F1 && keysym <= PK_F10 && (modifiers & PKM_SHIFT))
5769             keysym += 10;
5770         if ((term->vt52_mode || term->cfg.funky_type == FUNKY_VT100P) &&
5771             keysym <= PK_F14) {
5772             /* XXX This overrides the XTERM/VT52 mode below */
5773             int offt = 0;
5774             if (keysym >= PK_F6)  offt++;
5775             if (keysym >= PK_F12) offt++;
5776             p += sprintf((char *) p, term->vt52_mode ? "\x1B%c" : "\x1BO%c",
5777                          'P' + keysym - PK_F1 - offt);
5778             goto done;
5779         }
5780         if (term->cfg.funky_type == FUNKY_LINUX && keysym <= PK_F5) {
5781             p += sprintf((char *) p, "\x1B[[%c", 'A' + keysym - PK_F1);
5782             goto done;
5783         }
5784         if (term->cfg.funky_type == FUNKY_XTERM && keysym <= PK_F4) {
5785             if (term->vt52_mode)
5786                 p += sprintf((char *) p, "\x1B%c", 'P' + keysym - PK_F1);
5787             else
5788                 p += sprintf((char *) p, "\x1BO%c", 'P' + keysym - PK_F1);
5789             goto done;
5790         }
5791         p += sprintf((char *) p, "\x1B[%d~", 11 + keysym - PK_F1);
5792         goto done;
5793     }
5794
5795     if (PK_ISCURSOR(keysym)) {
5796         int xkey;
5797
5798         switch (keysym) {
5799           case PK_UP:    xkey = 'A'; break;
5800           case PK_DOWN:  xkey = 'B'; break;
5801           case PK_RIGHT: xkey = 'C'; break;
5802           case PK_LEFT:  xkey = 'D'; break;
5803           case PK_REST:  xkey = 'G'; break; /* centre key on number pad */
5804           default: xkey = 0; break; /* else gcc warns `enum value not used' */
5805         }
5806         if (term->vt52_mode)
5807             p += sprintf((char *) p, "\x1B%c", xkey);
5808         else {
5809             int app_flg = (term->app_cursor_keys && !term->cfg.no_applic_c);
5810
5811             /* Useful mapping of Ctrl-arrows */
5812             if (modifiers == PKM_CONTROL)
5813                 app_flg = !app_flg;
5814
5815             if (app_flg)
5816                 p += sprintf((char *) p, "\x1BO%c", xkey);
5817             else
5818                 p += sprintf((char *) p, "\x1B[%c", xkey);
5819         }
5820         goto done;
5821     }
5822
5823   done:
5824     if (p > output || tlen > 0) {
5825         /*
5826          * Interrupt an ongoing paste. I'm not sure
5827          * this is sensible, but for the moment it's
5828          * preferable to having to faff about buffering
5829          * things.
5830          */
5831         term_nopaste(term);
5832
5833         /*
5834          * We need not bother about stdin backlogs
5835          * here, because in GUI PuTTY we can't do
5836          * anything about it anyway; there's no means
5837          * of asking Windows to hold off on KEYDOWN
5838          * messages. We _have_ to buffer everything
5839          * we're sent.
5840          */
5841         term_seen_key_event(term);
5842
5843         if (prependesc) {
5844 #if 0
5845             fprintf(stderr, "sending ESC\n");
5846 #endif
5847             ldisc_send(term->ldisc, "\x1b", 1, 1);
5848         }
5849
5850         if (p > output) {
5851 #if 0
5852             fprintf(stderr, "sending %d bytes:", p - output);
5853             for (i = 0; i < p - output; i++)
5854                 fprintf(stderr, " %02x", output[i]);
5855             fprintf(stderr, "\n");
5856 #endif
5857             ldisc_send(term->ldisc, output, p - output, 1);
5858         } else if (tlen > 0) {
5859 #if 0
5860             fprintf(stderr, "sending %d unichars:", tlen);
5861             for (i = 0; i < tlen; i++)
5862                 fprintf(stderr, " %04x", (unsigned) text[i]);
5863             fprintf(stderr, "\n");
5864 #endif
5865             luni_send(term->ldisc, text, tlen, 1);
5866         }
5867     }
5868 }
5869
5870 void term_nopaste(Terminal *term)
5871 {
5872     if (term->paste_len == 0)
5873         return;
5874     sfree(term->paste_buffer);
5875     term->paste_buffer = NULL;
5876     term->paste_len = 0;
5877 }
5878
5879 int term_paste_pending(Terminal *term)
5880 {
5881     return term->paste_len != 0;
5882 }
5883
5884 void term_paste(Terminal *term)
5885 {
5886     long now, paste_diff;
5887
5888     if (term->paste_len == 0)
5889         return;
5890
5891     /* Don't wait forever to paste */
5892     if (term->paste_hold) {
5893         now = GETTICKCOUNT();
5894         paste_diff = now - term->last_paste;
5895         if (paste_diff >= 0 && paste_diff < 450)
5896             return;
5897     }
5898     term->paste_hold = 0;
5899
5900     while (term->paste_pos < term->paste_len) {
5901         int n = 0;
5902         while (n + term->paste_pos < term->paste_len) {
5903             if (term->paste_buffer[term->paste_pos + n++] == '\015')
5904                 break;
5905         }
5906         if (term->ldisc)
5907             luni_send(term->ldisc, term->paste_buffer + term->paste_pos, n, 0);
5908         term->paste_pos += n;
5909
5910         if (term->paste_pos < term->paste_len) {
5911             term->paste_hold = 1;
5912             return;
5913         }
5914     }
5915     sfree(term->paste_buffer);
5916     term->paste_buffer = NULL;
5917     term->paste_len = 0;
5918 }
5919
5920 static void deselect(Terminal *term)
5921 {
5922     term->selstate = NO_SELECTION;
5923     term->selstart.x = term->selstart.y = term->selend.x = term->selend.y = 0;
5924 }
5925
5926 void term_deselect(Terminal *term)
5927 {
5928     deselect(term);
5929     term_update(term);
5930 }
5931
5932 int term_ldisc(Terminal *term, int option)
5933 {
5934     if (option == LD_ECHO)
5935         return term->term_echoing;
5936     if (option == LD_EDIT)
5937         return term->term_editing;
5938     return FALSE;
5939 }
5940
5941 int term_data(Terminal *term, int is_stderr, const char *data, int len)
5942 {
5943     bufchain_add(&term->inbuf, data, len);
5944
5945     if (!term->in_term_out) {
5946         term->in_term_out = TRUE;
5947         term_blink(term, 1);
5948         term_out(term);
5949         term->in_term_out = FALSE;
5950     }
5951
5952     /*
5953      * term_out() always completely empties inbuf. Therefore,
5954      * there's no reason at all to return anything other than zero
5955      * from this function, because there _can't_ be a question of
5956      * the remote side needing to wait until term_out() has cleared
5957      * a backlog.
5958      *
5959      * This is a slightly suboptimal way to deal with SSH2 - in
5960      * principle, the window mechanism would allow us to continue
5961      * to accept data on forwarded ports and X connections even
5962      * while the terminal processing was going slowly - but we
5963      * can't do the 100% right thing without moving the terminal
5964      * processing into a separate thread, and that might hurt
5965      * portability. So we manage stdout buffering the old SSH1 way:
5966      * if the terminal processing goes slowly, the whole SSH
5967      * connection stops accepting data until it's ready.
5968      *
5969      * In practice, I can't imagine this causing serious trouble.
5970      */
5971     return 0;
5972 }
5973
5974 void term_provide_logctx(Terminal *term, void *logctx)
5975 {
5976     term->logctx = logctx;
5977 }