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