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