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