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