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