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