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