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