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