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