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