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