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