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