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