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