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