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