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