]> asedeno.scripts.mit.edu Git - PuTTY.git/blob - terminal.c
Robert de Bath's patch: a few more character translations for OEM
[PuTTY.git] / terminal.c
1 #include <windows.h>
2
3 #include <stdio.h>
4 #include <stdlib.h>
5
6 #include "putty.h"
7
8 static unsigned long *text;            /* buffer of text on terminal screen */
9 static unsigned long *scrtop;          /* top of working screen */
10 static unsigned long *disptop;         /* top of displayed screen */
11 static unsigned long *sbtop;           /* top of scrollback */
12 static unsigned long *cpos;            /* cursor position (convenience) */
13 static unsigned long *disptext;        /* buffer of text on real screen */
14 static unsigned long *wanttext;        /* buffer of text we want on screen */
15 static unsigned long *alttext;         /* buffer of text on alt. screen */
16
17 static unsigned char *selspace;        /* buffer for building selections in */
18
19 #define TSIZE (sizeof(*text))
20 #define fix_cpos  do { cpos = scrtop + curs_y * (cols+1) + curs_x; } while(0)
21
22 static unsigned long curr_attr, save_attr;
23
24 static int curs_x, curs_y;             /* cursor */
25 static int save_x, save_y;             /* saved cursor position */
26 static int marg_t, marg_b;             /* scroll margins */
27 static int dec_om;                     /* DEC origin mode flag */
28 static int wrap, wrapnext;             /* wrap flags */
29 static int insert;                     /* insert-mode flag */
30 static int cset;                       /* 0 or 1: which char set */
31 static int save_cset, save_csattr;     /* saved with cursor position */
32 static int rvideo;                     /* global reverse video flag */
33
34 static unsigned long cset_attr[2];
35
36 /*
37  * Saved settings on the alternate screen.
38  */
39 static int alt_x, alt_y, alt_om, alt_wrap, alt_wnext, alt_ins, alt_cset;
40 static int alt_t, alt_b;
41 static int alt_which;
42
43 #define ARGS_MAX 32                    /* max # of esc sequence arguments */
44 #define ARG_DEFAULT -1                 /* if an arg isn't specified */
45 #define def(a,d) ( (a) == ARG_DEFAULT ? (d) : (a) )
46 static int esc_args[ARGS_MAX];
47 static int esc_nargs;
48 static int esc_query;
49 #define ANSI(x,y)       ((x)+((y)<<8))
50 #define ANSI_QUE(x)     ANSI(x,TRUE)
51
52 #define OSC_STR_MAX 2048
53 static int osc_strlen;
54 static char osc_string[OSC_STR_MAX+1];
55 static int osc_w;
56
57 static unsigned char *tabs;
58
59 #define MAXNL 5
60 static int nl_count;
61
62 static int scroll_heuristic;
63
64 static enum {
65     TOPLEVEL,
66     SEEN_ESC,
67     SEEN_CSI,
68     SEEN_OSC,
69     SEEN_OSC_W,
70
71     DO_CTRLS,
72
73     IGNORE_NEXT,
74     SET_GL, SET_GR,
75     SEEN_OSC_P,
76     OSC_STRING, OSC_MAYBE_ST,
77     SEEN_ESCHASH
78 } termstate;
79
80 static enum {
81     NO_SELECTION, ABOUT_TO, DRAGGING, SELECTED
82 } selstate;
83 static enum {
84     SM_CHAR, SM_WORD, SM_LINE
85 } selmode;
86 static unsigned long *selstart, *selend, *selanchor;
87
88 static short wordness[256] = {
89     0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, /* 01 */
90     0,1,2,1,1,1,1,1,1,1,1,1,1,2,2,2, 2,2,2,2,2,2,2,2,2,2,1,1,1,1,1,1, /* 23 */
91     1,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2, 2,2,2,2,2,2,2,2,2,2,2,1,1,1,1,2, /* 45 */
92     1,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2, 2,2,2,2,2,2,2,2,2,2,2,1,1,1,1,1, /* 67 */
93     1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1, 1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1, /* 89 */
94     1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1, 1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1, /* AB */
95     2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2, 2,2,2,2,2,2,2,1,2,2,2,2,2,2,2,2, /* CD */
96     2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2, 2,2,2,2,2,2,2,1,2,2,2,2,2,2,2,2, /* EF */
97 };
98
99 static unsigned char sel_nl[] = SEL_NL;
100
101 /*
102  * Internal prototypes.
103  */
104 static void do_paint (Context, int);
105 static void erase_lots (int, int, int);
106 static void swap_screen (int);
107 static void update_sbar (void);
108 static void deselect (void);
109
110 /*
111  * Set up power-on settings for the terminal.
112  */
113 static void power_on(void) {
114     curs_x = curs_y = alt_x = alt_y = save_x = save_y = 0;
115     alt_t = marg_t = 0;
116     if (rows != -1)
117         alt_b = marg_b = rows - 1;
118     else
119         alt_b = marg_b = 0;
120     if (cols != -1) {
121         int i;
122         for (i = 0; i < cols; i++)
123             tabs[i] = (i % 8 == 0 ? TRUE : FALSE);
124     }
125     alt_om = dec_om = cfg.dec_om;
126     alt_wnext = wrapnext = alt_ins = insert = FALSE;
127     alt_wrap = wrap = cfg.wrap_mode;
128     alt_cset = cset = 0;
129     cset_attr[0] = cset_attr[1] = ATTR_ASCII;
130     rvideo = 0;
131     save_attr = curr_attr = ATTR_DEFAULT;
132     app_cursor_keys = cfg.app_cursor;
133     app_keypad_keys = cfg.app_keypad;
134     alt_which = 0;
135     {
136         int i;
137         for (i = 0; i < 256; i++)
138             wordness[i] = cfg.wordness[i];
139     }
140     if (text) {
141         swap_screen (1);
142         erase_lots (FALSE, TRUE, TRUE);
143         swap_screen (0);
144         erase_lots (FALSE, TRUE, TRUE);
145     }
146 }
147
148 /*
149  * Force a screen update.
150  */
151 void term_update(void) {
152     Context ctx;
153     ctx = get_ctx();
154     if (ctx) {
155         if ( (seen_key_event && (unscroll_event & US_KEY)) ||
156              (seen_disp_event && (unscroll_event & US_DISP)) ) {
157             disptop = scrtop;
158             seen_disp_event = seen_key_event = 0;
159         }
160         do_paint (ctx, TRUE);
161         free_ctx (ctx);
162         nl_count = 0;
163         scroll_heuristic = 0;
164     }
165 }
166
167 /*
168  * Same as power_on(), but an external function.
169  */
170 void term_pwron(void) {
171     power_on();
172     fix_cpos;
173     disptop = scrtop;
174     deselect();
175     term_update();
176 }
177
178 /*
179  * Clear the scrollback.
180  */
181 void term_clrsb(void) {
182     disptop = sbtop = scrtop;
183     update_sbar();
184 }
185
186 /*
187  * Initialise the terminal.
188  */
189 void term_init(void) {
190     text = sbtop = scrtop = disptop = cpos = NULL;
191     disptext = wanttext = NULL;
192     tabs = NULL;
193     selspace = NULL;
194     deselect();
195     rows = cols = -1;
196     nl_count = 0;
197     power_on();
198 }
199
200 /*
201  * Set up the terminal for a given size.
202  */
203 void term_size(int newrows, int newcols, int newsavelines) {
204     unsigned long *newtext, *newdisp, *newwant, *newalt;
205     int i, j, crows, ccols;
206
207     int save_alt_which = alt_which;
208
209     if (newrows == rows && newcols == cols && newsavelines == savelines)
210         return;                        /* nothing to do */
211
212     deselect();
213     swap_screen(0);
214
215     alt_t = marg_t = 0;
216     alt_b = marg_b = newrows - 1;
217
218     newtext = smalloc ((newrows+newsavelines)*(newcols+1)*TSIZE);
219     disptop = newtext + newsavelines*(newcols+1);
220     for (i=0; i<(newrows+newsavelines)*(newcols+1); i++)
221         newtext[i] = ERASE_CHAR;
222     if (rows != -1) {
223         crows = rows + (scrtop - sbtop) / (cols+1);
224         if (crows > newrows+newsavelines)
225             crows = newrows+newsavelines;
226         ccols = (cols < newcols ? cols : newcols);
227         for (i=0; i<crows; i++) {
228             int oldidx = (rows + savelines - crows + i) * (cols+1);
229             int newidx = (newrows + newsavelines - crows + i) * (newcols+1);
230             for (j=0; j<ccols; j++)
231                 newtext[newidx+j] = text[oldidx+j];
232             newtext[newidx+newcols] =
233                 (cols == newcols ? text[oldidx+cols] : 0);
234         }
235         sbtop = disptop - (crows - newrows) * (newcols+1);
236         if (sbtop > disptop)
237             sbtop = disptop;
238     } else
239         sbtop = disptop;
240     scrtop = disptop;
241     sfree (text);
242     text = newtext;
243
244     newdisp = smalloc (newrows*(newcols+1)*TSIZE);
245     for (i=0; i<newrows*(newcols+1); i++)
246         newdisp[i] = ATTR_INVALID;
247     sfree (disptext);
248     disptext = newdisp;
249
250     newwant = smalloc (newrows*(newcols+1)*TSIZE);
251     for (i=0; i<newrows*(newcols+1); i++)
252         newwant[i] = ATTR_INVALID;
253     sfree (wanttext);
254     wanttext = newwant;
255
256     newalt = smalloc (newrows*(newcols+1)*TSIZE);
257     for (i=0; i<newrows*(newcols+1); i++)
258         newalt[i] = ERASE_CHAR;
259     sfree (alttext);
260     alttext = newalt;
261
262     sfree (selspace);
263     selspace = smalloc ( (newrows+newsavelines) * (newcols+sizeof(sel_nl)) );
264
265     tabs = srealloc (tabs, newcols*sizeof(*tabs));
266     {
267         int i;
268         for (i = (cols > 0 ? cols : 0); i < newcols; i++)
269             tabs[i] = (i % 8 == 0 ? TRUE : FALSE);
270     }
271
272     if (rows > 0)
273         curs_y += newrows - rows;
274     if (curs_y < 0)
275         curs_y = 0;
276     if (curs_y >= newrows)
277         curs_y = newrows-1;
278     if (curs_x >= newcols)
279         curs_x = newcols-1;
280     alt_x = alt_y = 0;
281     wrapnext = alt_wnext = FALSE;
282
283     rows = newrows;
284     cols = newcols;
285     savelines = newsavelines;
286     fix_cpos;
287
288     swap_screen(save_alt_which);
289
290     update_sbar();
291     term_update();
292 }
293
294 /*
295  * Swap screens.
296  */
297 static void swap_screen (int which) {
298     int t;
299     unsigned long tt;
300
301     if (which == alt_which)
302         return;
303
304     alt_which = which;
305
306     for (t=0; t<rows*(cols+1); t++) {
307         tt = scrtop[t]; scrtop[t] = alttext[t]; alttext[t] = tt;
308     }
309
310     t = curs_x; curs_x = alt_x; alt_x = t;
311     t = curs_y; curs_y = alt_y; alt_y = t;
312     t = marg_t; marg_t = alt_t; alt_t = t;
313     t = marg_b; marg_b = alt_b; alt_b = t;
314     t = dec_om; dec_om = alt_om; alt_om = t;
315     t = wrap; wrap = alt_wrap; alt_wrap = t;
316     t = wrapnext; wrapnext = alt_wnext; alt_wnext = t;
317     t = insert; insert = alt_ins; alt_ins = t;
318     t = cset; cset = alt_cset; alt_cset = t;
319
320     fix_cpos;
321 }
322
323 /*
324  * Retrieve a character from `inbuf'.
325  */
326 static int inbuf_getc(void) {
327     if (inbuf_head == inbuf_reap)
328         return -1;                     /* EOF */
329     else {
330         int n = inbuf_reap;
331         inbuf_reap = (inbuf_reap+1) & INBUF_MASK;
332         return inbuf[n];
333     }
334 }
335
336 /*
337  * Update the scroll bar.
338  */
339 static void update_sbar(void) {
340     int min;
341
342     min = (sbtop - text) / (cols+1);
343     set_sbar ((scrtop - text) / (cols+1) + rows - min,
344               (disptop - text) / (cols+1) - min,
345               rows);
346 }
347
348 /*
349  * Check whether the region bounded by the two pointers intersects
350  * the scroll region, and de-select the on-screen selection if so.
351  */
352 static void check_selection (unsigned long *from, unsigned long *to) {
353     if (from < selend && selstart < to)
354         deselect();
355 }
356
357 /*
358  * Scroll the screen. (`lines' is +ve for scrolling forward, -ve
359  * for backward.) `sb' is TRUE if the scrolling is permitted to
360  * affect the scrollback buffer.
361  */
362 static void scroll (int topline, int botline, int lines, int sb) {
363     unsigned long *scroll_top;
364     int scroll_size, size, i;
365
366     scroll_top = scrtop + topline*(cols+1);
367     size = (lines < 0 ? -lines : lines) * (cols+1);
368     scroll_size = (botline - topline + 1) * (cols+1) - size;
369
370     if (lines > 0 && topline == 0 && alt_which == 0 && sb) {
371         /*
372          * Since we're going to scroll the top line and we're on the 
373          * scrolling screen let's also affect the scrollback buffer.
374          */
375         sbtop -= lines * (cols+1);
376         if (sbtop < text)
377             sbtop = text;
378         scroll_size += scroll_top - sbtop;
379         scroll_top = sbtop;
380         update_sbar();
381     }
382
383     if (scroll_size < 0) {
384         size += scroll_size;
385         scroll_size = 0;
386     }
387
388     if (lines > 0) {
389         if (scroll_size)
390             memmove (scroll_top, scroll_top + size, scroll_size*TSIZE);
391         for (i = 0; i < size; i++)
392             scroll_top[i+scroll_size] = ERASE_CHAR;
393         if (selstart > scroll_top &&
394             selstart < scroll_top + size + scroll_size) {
395             selstart -= size;
396             if (selstart < scroll_top)
397                 selstart = scroll_top;
398         }
399         if (selend > scroll_top &&
400             selend < scroll_top + size + scroll_size) {
401             selend -= size;
402             if (selend < scroll_top)
403                 selend = scroll_top;
404         }
405     } else {
406         if (scroll_size)
407             memmove (scroll_top + size, scroll_top, scroll_size*TSIZE);
408         for (i = 0; i < size; i++)
409             scroll_top[i] = ERASE_CHAR;
410         if (selstart > scroll_top &&
411             selstart < scroll_top + size + scroll_size) {
412             selstart += size;
413             if (selstart > scroll_top + size + scroll_size)
414                 selstart = scroll_top + size + scroll_size;
415         }
416         if (selend > scroll_top &&
417             selend < scroll_top + size + scroll_size) {
418             selend += size;
419             if (selend > scroll_top + size + scroll_size)
420                 selend = scroll_top + size + scroll_size;
421         }
422     }
423
424     scroll_heuristic += lines;
425 }
426
427 /*
428  * Move the cursor to a given position, clipping at boundaries. We
429  * may or may not want to clip at the scroll margin: marg_clip is 0
430  * not to, 1 to disallow _passing_ the margins, and 2 to disallow
431  * even _being_ outside the margins.
432  */
433 static void move (int x, int y, int marg_clip) {
434     if (x < 0)
435         x = 0;
436     if (x >= cols)
437         x = cols-1;
438     if (marg_clip) {
439         if ((curs_y >= marg_t || marg_clip == 2) && y < marg_t)
440             y = marg_t;
441         if ((curs_y <= marg_b || marg_clip == 2) && y > marg_b)
442             y = marg_b;
443     }
444     if (y < 0)
445         y = 0;
446     if (y >= rows)
447         y = rows-1;
448     curs_x = x;
449     curs_y = y;
450     fix_cpos;
451     wrapnext = FALSE;
452 }
453
454 /*
455  * Save or restore the cursor and SGR mode.
456  */
457 static void save_cursor(int save) {
458     if (save) {
459         save_x = curs_x;
460         save_y = curs_y;
461         save_attr = curr_attr;
462         save_cset = cset;
463         save_csattr = cset_attr[cset];
464     } else {
465         curs_x = save_x;
466         curs_y = save_y;
467         curr_attr = save_attr;
468         cset = save_cset;
469         cset_attr[cset] = save_csattr;
470         fix_cpos;
471     }
472 }
473
474 /*
475  * Erase a large portion of the screen: the whole screen, or the
476  * whole line, or parts thereof.
477  */
478 static void erase_lots (int line_only, int from_begin, int to_end) {
479     unsigned long *startpos, *endpos;
480
481     if (line_only) {
482         startpos = cpos - curs_x;
483         endpos = startpos + cols+1;
484     } else {
485         startpos = scrtop;
486         endpos = startpos + rows * (cols+1);
487     }
488     if (!from_begin)
489         startpos = cpos;
490     if (!to_end)
491         endpos = cpos;
492     check_selection (startpos, endpos);
493     while (startpos < endpos)
494         *startpos++ = ERASE_CHAR;
495 }
496
497 /*
498  * Insert or delete characters within the current line. n is +ve if
499  * insertion is desired, and -ve for deletion.
500  */
501 static void insch (int n) {
502     int dir = (n < 0 ? -1 : +1);
503     int m;
504
505     n = (n < 0 ? -n : n);
506     if (n > cols - curs_x)
507         n = cols - curs_x;
508     m = cols - curs_x - n;
509     check_selection (cpos, cpos+n);
510     if (dir < 0) {
511         memmove (cpos, cpos+n, m*TSIZE);
512         while (n--)
513             cpos[m++] = ERASE_CHAR;
514     } else {
515         memmove (cpos+n, cpos, m*TSIZE);
516         while (n--)
517             cpos[n] = ERASE_CHAR;
518     }
519 }
520
521 /*
522  * Toggle terminal mode `mode' to state `state'. (`query' indicates
523  * whether the mode is a DEC private one or a normal one.)
524  */
525 static void toggle_mode (int mode, int query, int state) {
526     if (query) switch (mode) {
527       case 1:                          /* application cursor keys */
528         app_cursor_keys = state;
529         break;
530       case 3:                          /* 80/132 columns */
531         deselect();
532         request_resize (state ? 132 : 80, rows);
533         break;
534       case 5:                          /* reverse video */
535         rvideo = state;
536         seen_disp_event = TRUE;
537         break;
538       case 6:                          /* DEC origin mode */
539         dec_om = state;
540         break;
541       case 7:                          /* auto wrap */
542         wrap = state;
543         break;
544       case 47:                         /* alternate screen */
545         deselect();
546         swap_screen (state);
547         disptop = scrtop;
548         break;
549     } else switch (mode) {
550       case 4:                          /* set insert mode */
551         insert = state;
552         break;
553     }
554 }
555
556 /*
557  * Process an OSC sequence: set window title or icon name.
558  */
559 static void do_osc(void) {
560     if (osc_w) {
561         while (osc_strlen--)
562             wordness[(unsigned char)osc_string[osc_strlen]] = esc_args[0];
563     } else {
564         osc_string[osc_strlen] = '\0';
565         switch (esc_args[0]) {
566           case 0:
567           case 1:
568             set_icon (osc_string);
569             if (esc_args[0] == 1)
570                 break;
571             /* fall through: parameter 0 means set both */
572           case 2:
573           case 21:
574             set_title (osc_string);
575             break;
576         }
577     }
578 }
579
580 /*
581  * Remove everything currently in `inbuf' and stick it up on the
582  * in-memory display. There's a big state machine in here to
583  * process escape sequences...
584  */
585 void term_out(void) {
586     int c;
587
588     while ( (c = inbuf_getc()) != -1) {
589         /*
590          * Optionally log the session traffic to a file. Useful for
591          * debugging and possibly also useful for actual logging.
592          */
593         if (logfile) {
594             static FILE *fp = NULL;
595             if (!fp) fp = fopen(logfile, "wb");
596             if (fp) fputc (c, fp);
597         }
598         if( termstate < DO_CTRLS && (c&0x60) == 0 ) {
599             switch (c) {
600               case '\005':             /* terminal type query */
601                 ldisc->send ("PuTTY\r", 6);
602                 break;
603               case '\007':
604                 beep();
605                 disptop = scrtop;
606                 break;
607               case '\b':
608                 if (curs_x == 0 && curs_y > 0)
609                     curs_x = cols-1, curs_y--;
610                 else if (wrapnext)
611                     wrapnext = FALSE;
612                 else
613                     curs_x--;
614                 fix_cpos;
615                 seen_disp_event = TRUE;
616                 break;
617               case '\016':
618                 cset = 1;
619                 break;
620               case '\017':
621                 cset = 0;
622                 break;
623               case '\033':
624                 termstate = SEEN_ESC;
625                 break;
626               case 0233:
627                 termstate = SEEN_CSI;
628                 esc_nargs = 1;
629                 esc_args[0] = ARG_DEFAULT;
630                 esc_query = FALSE;
631                 break;
632               case 0235:
633                 termstate = SEEN_OSC;
634                 esc_args[0] = 0;
635                 break;
636               case '\r':
637                 curs_x = 0;
638                 wrapnext = FALSE;
639                 fix_cpos;
640                 seen_disp_event = TRUE;
641                 break;
642               case '\013':
643               case '\014':
644               case '\n':
645                 if (curs_y == marg_b)
646                     scroll (marg_t, marg_b, 1, TRUE);
647                 else if (curs_y < rows-1)
648                     curs_y++;
649                 if (cfg.lfhascr)
650                     curs_x = 0;
651                 fix_cpos;
652                 wrapnext = FALSE;
653                 seen_disp_event = 1;
654                 nl_count++;
655                 break;
656               case '\t':
657                 do {
658                     curs_x++;
659                 } while (curs_x < cols-1 && !tabs[curs_x]);
660                 if (curs_x >= cols)
661                     curs_x = cols-1;
662                 {
663                     unsigned long *old_cpos = cpos;
664                     fix_cpos;
665                     check_selection (old_cpos, cpos);
666                 }
667                 seen_disp_event = TRUE;
668                 break;
669             }
670         }
671         else switch (termstate) {
672           case TOPLEVEL:
673           /* Only graphic characters get this far, ctrls are stripped above */
674             if (wrapnext) {
675                 cpos[1] = ATTR_WRAPPED;
676                 if (curs_y == marg_b)
677                     scroll (marg_t, marg_b, 1, TRUE);
678                 else if (curs_y < rows-1)
679                     curs_y++;
680                 curs_x = 0;
681                 fix_cpos;
682                 wrapnext = FALSE;
683                 nl_count++;
684             }
685             if (insert)
686                 insch (1);
687             check_selection (cpos, cpos+1);
688             *cpos++ = xlat_tty2scr((unsigned char)c) | curr_attr |
689                 (c <= 0x7F ? cset_attr[cset] : ATTR_ASCII);
690             curs_x++;
691             if (curs_x == cols) {
692                 cpos--;
693                 curs_x--;
694                 wrapnext = wrap;
695             }
696             seen_disp_event = 1;
697             break;
698
699           case IGNORE_NEXT:
700             termstate = TOPLEVEL;
701             break;
702           case OSC_MAYBE_ST:
703             /*
704              * This state is virtually identical to SEEN_ESC, with the
705              * exception that we have an OSC sequence in the pipeline,
706              * and _if_ we see a backslash, we process it.
707              */
708             if (c == '\\') {
709                 do_osc();
710                 termstate = TOPLEVEL;
711                 break;
712             }
713             /* else fall through */
714           case SEEN_ESC:
715             termstate = TOPLEVEL;
716             switch (c) {
717               case ' ':                /* some weird sequence? */
718                 termstate = IGNORE_NEXT;
719                 break;
720               case '[':                /* enter CSI mode */
721                 termstate = SEEN_CSI;
722                 esc_nargs = 1;
723                 esc_args[0] = ARG_DEFAULT;
724                 esc_query = FALSE;
725                 break;
726               case ']':                /* xterm escape sequences */
727                 termstate = SEEN_OSC;
728                 esc_args[0] = 0;
729                 break;
730               case '(':                /* should set GL */
731                 termstate = SET_GL;
732                 break;
733               case ')':                /* should set GR */
734                 termstate = SET_GR;
735                 break;
736               case '7':                /* save cursor */
737                 save_cursor (TRUE);
738                 break;
739               case '8':                /* restore cursor */
740                 save_cursor (FALSE);
741                 seen_disp_event = TRUE;
742                 break;
743               case '=':
744                 app_keypad_keys = TRUE;
745                 break;
746               case '>':
747                 app_keypad_keys = FALSE;
748                 break;
749               case 'D':                /* exactly equivalent to LF */
750                 if (curs_y == marg_b)
751                     scroll (marg_t, marg_b, 1, TRUE);
752                 else if (curs_y < rows-1)
753                     curs_y++;
754                 fix_cpos;
755                 wrapnext = FALSE;
756                 seen_disp_event = TRUE;
757                 nl_count++;
758                 break;
759               case 'E':                /* exactly equivalent to CR-LF */
760                 curs_x = 0;
761                 wrapnext = FALSE;
762                 if (curs_y == marg_b)
763                     scroll (marg_t, marg_b, 1, TRUE);
764                 else if (curs_y < rows-1)
765                     curs_y++;
766                 fix_cpos;
767                 wrapnext = FALSE;
768                 nl_count++;
769                 seen_disp_event = TRUE;
770                 break;
771               case 'M':                /* reverse index - backwards LF */
772                 if (curs_y == marg_t)
773                     scroll (marg_t, marg_b, -1, TRUE);
774                 else if (curs_y > 0)
775                     curs_y--;
776                 fix_cpos;
777                 wrapnext = FALSE;
778                 seen_disp_event = TRUE;
779                 break;
780               case 'Z':                /* terminal type query */
781                 ldisc->send ("\033[?6c", 5);
782                 break;
783               case 'c':                /* restore power-on settings */
784                 power_on();
785                 fix_cpos;
786                 disptop = scrtop;
787                 seen_disp_event = TRUE;
788                 break;
789               case '#':                /* ESC # 8 fills screen with Es :-) */
790                 termstate = SEEN_ESCHASH;
791                 break;
792               case 'H':                /* set a tab */
793                 tabs[curs_x] = TRUE;
794                 break;
795             }
796             break;
797           case SEEN_CSI:
798             termstate = TOPLEVEL;      /* default */
799             if( isdigit(c) )
800             {
801                 if (esc_nargs <= ARGS_MAX) {
802                     if (esc_args[esc_nargs-1] == ARG_DEFAULT)
803                         esc_args[esc_nargs-1] = 0;
804                     esc_args[esc_nargs-1] =
805                         10 * esc_args[esc_nargs-1] + c - '0';
806                 }
807                 termstate = SEEN_CSI;
808             }
809             else if( c == ';' )
810             {
811                 if (++esc_nargs <= ARGS_MAX)
812                     esc_args[esc_nargs-1] = ARG_DEFAULT;
813                 termstate = SEEN_CSI;
814             }
815             else if( c < '@' )
816             {
817                 if( esc_query )     esc_query = -1;
818                 else if( c == '?' ) esc_query = TRUE;
819                 else                esc_query = c;
820                 termstate = SEEN_CSI;
821             }
822             else switch (ANSI(c,esc_query)) {
823               case 'A':                /* move up N lines */
824                 move (curs_x, curs_y - def(esc_args[0], 1), 1);
825                 seen_disp_event = TRUE;
826                 break;
827               case 'B': case 'e':      /* move down N lines */
828                 move (curs_x, curs_y + def(esc_args[0], 1), 1);
829                 seen_disp_event = TRUE;
830                 break;
831               case 'C': case 'a':      /* move right N cols */
832                 move (curs_x + def(esc_args[0], 1), curs_y, 1);
833                 seen_disp_event = TRUE;
834                 break;
835               case 'D':                /* move left N cols */
836                 move (curs_x - def(esc_args[0], 1), curs_y, 1);
837                 seen_disp_event = TRUE;
838                 break;
839               case 'E':                /* move down N lines and CR */
840                 move (0, curs_y + def(esc_args[0], 1), 1);
841                 seen_disp_event = TRUE;
842                 break;
843               case 'F':                /* move up N lines and CR */
844                 move (0, curs_y - def(esc_args[0], 1), 1);
845                 seen_disp_event = TRUE;
846                 break;
847               case 'G': case '`':      /* set horizontal posn */
848                 move (def(esc_args[0], 1) - 1, curs_y, 0);
849                 seen_disp_event = TRUE;
850                 break;
851               case 'd':                /* set vertical posn */
852                 move (curs_x, (dec_om ? marg_t : 0) + def(esc_args[0], 1) - 1,
853                       (dec_om ? 2 : 0));
854                 seen_disp_event = TRUE;
855                 break;
856               case 'H': case 'f':      /* set horz and vert posns at once */
857                 if (esc_nargs < 2)
858                     esc_args[1] = ARG_DEFAULT;
859                 move (def(esc_args[1], 1) - 1,
860                       (dec_om ? marg_t : 0) + def(esc_args[0], 1) - 1,
861                       (dec_om ? 2 : 0));
862                 seen_disp_event = TRUE;
863                 break;
864               case 'J':                /* erase screen or parts of it */
865                 {
866                     unsigned int i = def(esc_args[0], 0) + 1;
867                     if (i > 3)
868                         i = 0;
869                     erase_lots(FALSE, !!(i & 2), !!(i & 1));
870                 }
871                 disptop = scrtop;
872                 seen_disp_event = TRUE;
873                 break;
874               case 'K':                /* erase line or parts of it */
875                 {
876                     unsigned int i = def(esc_args[0], 0) + 1;
877                     if (i > 3)
878                         i = 0;
879                     erase_lots(TRUE, !!(i & 2), !!(i & 1));
880                 }
881                 seen_disp_event = TRUE;
882                 break;
883               case 'L':                /* insert lines */
884                 if (curs_y <= marg_b)
885                     scroll (curs_y, marg_b, -def(esc_args[0], 1), FALSE);
886                 seen_disp_event = TRUE;
887                 break;
888               case 'M':                /* delete lines */
889                 if (curs_y <= marg_b)
890                     scroll (curs_y, marg_b, def(esc_args[0], 1), TRUE);
891                 seen_disp_event = TRUE;
892                 break;
893               case '@':                /* insert chars */
894                 insch (def(esc_args[0], 1));
895                 seen_disp_event = TRUE;
896                 break;
897               case 'P':                /* delete chars */
898                 insch (-def(esc_args[0], 1));
899                 seen_disp_event = TRUE;
900                 break;
901               case 'c':                /* terminal type query */
902                 ldisc->send ("\033[?6c", 5);
903                 break;
904               case 'n':                /* cursor position query */
905                 if (esc_args[0] == 6) {
906                     char buf[32];
907                     sprintf (buf, "\033[%d;%dR", curs_y + 1, curs_x + 1);
908                     ldisc->send (buf, strlen(buf));
909                 }
910                 break;
911               case 'h':                /* toggle a mode to high */
912               case ANSI_QUE('h'):
913                 toggle_mode (esc_args[0], esc_query, TRUE);
914                 break;
915               case 'l':                /* toggle a mode to low */
916               case ANSI_QUE('l'):
917                 toggle_mode (esc_args[0], esc_query, FALSE);
918                 break;
919               case 'g':                /* clear tabs */
920                 if (esc_nargs == 1) {
921                     if (esc_args[0] == 0) {
922                         tabs[curs_x] = FALSE;
923                     } else if (esc_args[0] == 3) {
924                         int i;
925                         for (i = 0; i < cols; i++)
926                             tabs[i] = FALSE;
927                     }
928                 }
929                 break;
930               case 'r':                /* set scroll margins */
931                 if (esc_nargs <= 2) {
932                     int top, bot;
933                     top = def(esc_args[0], 1) - 1;
934                     if (top < 0)
935                         top = 0;
936                     bot = (esc_nargs <= 1 || esc_args[1] == 0 ? rows :
937                            def(esc_args[1], rows)) - 1;
938                     if (bot >= rows)
939                         bot = rows-1;
940                     if (top <= bot) {
941                         marg_t = top;
942                         marg_b = bot;
943                         curs_x = 0;
944                         /*
945                          * I used to think the cursor should be
946                          * placed at the top of the newly marginned
947                          * area. Apparently not: VMS TPU falls over
948                          * if so.
949                          */
950                         curs_y = 0;
951                         fix_cpos;
952                         seen_disp_event = TRUE;
953                     }
954                 }
955                 break;
956               case 'm':                /* set graphics rendition */
957                 {
958                     int i;
959                     for (i=0; i<esc_nargs; i++) {
960                         switch (def(esc_args[i], 0)) {
961                           case 0:      /* restore defaults */
962                             curr_attr = ATTR_DEFAULT; break;
963                           case 1:      /* enable bold */
964                             curr_attr |= ATTR_BOLD; break;
965                           case 4:      /* enable underline */
966                           case 21:     /* (enable double underline) */
967                             curr_attr |= ATTR_UNDER; break;
968                           case 7:      /* enable reverse video */
969                             curr_attr |= ATTR_REVERSE; break;
970                           case 22:     /* disable bold */
971                             curr_attr &= ~ATTR_BOLD; break;
972                           case 24:     /* disable underline */
973                             curr_attr &= ~ATTR_UNDER; break;
974                           case 27:     /* disable reverse video */
975                             curr_attr &= ~ATTR_REVERSE; break;
976                           case 30: case 31: case 32: case 33:
977                           case 34: case 35: case 36: case 37:
978                             /* foreground */
979                             curr_attr &= ~ATTR_FGMASK;
980                             curr_attr |= (esc_args[i] - 30) << ATTR_FGSHIFT;
981                             break;
982                           case 39:     /* default-foreground */
983                             curr_attr &= ~ATTR_FGMASK;
984                             curr_attr |= ATTR_DEFFG;
985                             break;
986                           case 40: case 41: case 42: case 43:
987                           case 44: case 45: case 46: case 47:
988                             /* background */
989                             curr_attr &= ~ATTR_BGMASK;
990                             curr_attr |= (esc_args[i] - 40) << ATTR_BGSHIFT;
991                             break;
992                           case 49:     /* default-background */
993                             curr_attr &= ~ATTR_BGMASK;
994                             curr_attr |= ATTR_DEFBG;
995                             break;
996                         }
997                     }
998                 }
999                 break;
1000               case 's':                /* save cursor */
1001                 save_cursor (TRUE);
1002                 break;
1003               case 'u':                /* restore cursor */
1004                 save_cursor (FALSE);
1005                 seen_disp_event = TRUE;
1006                 break;
1007               case 't':                /* set page size - ie window height */
1008                 request_resize (cols, def(esc_args[0], 24));
1009                 deselect();
1010                 break;
1011               case 'X':                /* write N spaces w/o moving cursor */
1012                 {
1013                     int n = def(esc_args[0], 1);
1014                     unsigned long *p = cpos;
1015                     if (n > cols - curs_x)
1016                         n = cols - curs_x;
1017                     check_selection (cpos, cpos+n);
1018                     while (n--)
1019                         *p++ = ERASE_CHAR;
1020                     seen_disp_event = TRUE;
1021                 }
1022                 break;
1023               case 'x':                /* report terminal characteristics */
1024                 {
1025                     char buf[32];
1026                     int i = def(esc_args[0], 0);
1027                     if (i == 0 || i == 1) {
1028                         strcpy (buf, "\033[2;1;1;112;112;1;0x");
1029                         buf[2] += i;
1030                         ldisc->send (buf, 20);
1031                     }
1032                 }
1033                 break;
1034             }
1035             break;
1036           case SET_GL:
1037           case SET_GR:
1038             switch (c) {
1039               case 'A':
1040                 cset_attr[termstate == SET_GL ? 0 : 1] = ATTR_GBCHR;
1041                 break;
1042               case '0':
1043                 cset_attr[termstate == SET_GL ? 0 : 1] = ATTR_LINEDRW;
1044                 break;
1045               default:                 /* specifically, 'B' */
1046                 cset_attr[termstate == SET_GL ? 0 : 1] = ATTR_ASCII;
1047                 break;
1048             }
1049             if( c != '%' )
1050                 termstate = TOPLEVEL;
1051             break;
1052           case SEEN_OSC:
1053             osc_w = FALSE;
1054             switch (c) {
1055               case 'P':                /* Linux palette sequence */
1056                 termstate = SEEN_OSC_P;
1057                 osc_strlen = 0;
1058                 break;
1059               case 'R':                /* Linux palette reset */
1060                 palette_reset();
1061                 term_invalidate();
1062                 termstate = TOPLEVEL;
1063                 break;
1064               case 'W':                /* word-set */
1065                 termstate = SEEN_OSC_W;
1066                 osc_w = TRUE;
1067                 break;
1068               case '0': case '1': case '2': case '3': case '4':
1069               case '5': case '6': case '7': case '8': case '9':
1070                 esc_args[0] = 10 * esc_args[0] + c - '0';
1071                 break;
1072               case 'L':
1073                 /*
1074                  * Grotty hack to support xterm and DECterm title
1075                  * sequences concurrently.
1076                  */
1077                 if (esc_args[0] == 2) {
1078                     esc_args[0] = 1;
1079                     break;
1080                 }
1081                 /* else fall through */
1082               default:
1083                 termstate = OSC_STRING;
1084                 osc_strlen = 0;
1085             }
1086             break;
1087           case OSC_STRING:
1088             /*
1089              * This OSC stuff is EVIL. It takes just one character to get into
1090              * sysline mode and it's not initially obvious how to get out.
1091              * So I've added CR and LF as string aborts.
1092              * This shouldn't effect compatibility as I believe embedded 
1093              * control characters are supposed to be interpreted (maybe?) 
1094              * and they don't display anything useful anyway.
1095              *
1096              * -- RDB
1097              */
1098             if (c == '\n' || c == '\r') {
1099                 termstate = TOPLEVEL;
1100             } else if (c == 0234 || c == '\007' ) {
1101                 /*
1102                  * These characters terminate the string; ST and BEL
1103                  * terminate the sequence and trigger instant
1104                  * processing of it, whereas ESC goes back to SEEN_ESC
1105                  * mode unless it is followed by \, in which case it is
1106                  * synonymous with ST in the first place.
1107                  */
1108                 do_osc();
1109                 termstate = TOPLEVEL;
1110             } else if (c == '\033')
1111                     termstate = OSC_MAYBE_ST;
1112             else if (osc_strlen < OSC_STR_MAX)
1113                 osc_string[osc_strlen++] = c;
1114             break;
1115           case SEEN_OSC_P:
1116             {
1117                 int max = (osc_strlen == 0 ? 21 : 16);
1118                 int val;
1119                 if (c >= '0' && c <= '9')
1120                     val = c - '0';
1121                 else if (c >= 'A' && c <= 'A'+max-10)
1122                     val = c - 'A' + 10;
1123                 else if (c >= 'a' && c <= 'a'+max-10)
1124                     val = c - 'a' + 10;
1125                 else
1126                     termstate = TOPLEVEL;
1127                 osc_string[osc_strlen++] = val;
1128                 if (osc_strlen >= 7) {
1129                     palette_set (osc_string[0],
1130                                  osc_string[1] * 16 + osc_string[2],
1131                                  osc_string[3] * 16 + osc_string[4],
1132                                  osc_string[5] * 16 + osc_string[6]);
1133                     term_invalidate();
1134                     termstate = TOPLEVEL;
1135                 }
1136             }
1137             break;
1138           case SEEN_OSC_W:
1139             switch (c) {
1140               case '0': case '1': case '2': case '3': case '4':
1141               case '5': case '6': case '7': case '8': case '9':
1142                 esc_args[0] = 10 * esc_args[0] + c - '0';
1143                 break;
1144               default:
1145                 termstate = OSC_STRING;
1146                 osc_strlen = 0;
1147             }
1148             break;
1149           case SEEN_ESCHASH:
1150             if (c == '8') {
1151                 unsigned long *p = scrtop;
1152                 int n = rows * (cols+1);
1153                 while (n--)
1154                     *p++ = ATTR_DEFAULT | 'E';
1155                 disptop = scrtop;
1156                 seen_disp_event = TRUE;
1157                 check_selection (scrtop, scrtop + rows * (cols+1));
1158             }
1159             termstate = TOPLEVEL;
1160             break;
1161         }
1162         check_selection (cpos, cpos+1);
1163     }
1164         
1165     if (nl_count > MAXNL)
1166         term_update();
1167 }
1168
1169 /*
1170  * Compare two lines to determine whether they are sufficiently
1171  * alike to scroll-optimise one to the other. Return the degree of
1172  * similarity.
1173  */
1174 static int linecmp (unsigned long *a, unsigned long *b) {
1175     int i, n;
1176
1177     for (i=n=0; i < cols; i++)
1178         n += (*a++ == *b++);
1179     return n;
1180 }
1181
1182 /*
1183  * Given a context, update the window. Out of paranoia, we don't
1184  * allow WM_PAINT responses to do scrolling optimisations.
1185  */
1186 static void do_paint (Context ctx, int may_optimise){ 
1187     int i, j, start, our_curs_y;
1188     unsigned long attr, rv, cursor;
1189     char ch[1024];
1190
1191     cursor = (has_focus ? ATTR_ACTCURS : ATTR_PASCURS);
1192     rv = (rvideo ? ATTR_REVERSE : 0);
1193     our_curs_y = curs_y + (scrtop - disptop) / (cols+1);
1194
1195     for (i=0; i<rows; i++) {
1196         int idx = i*(cols+1);
1197         for (j=0; j<=cols; j++,idx++) {
1198             unsigned long *d = disptop+idx;
1199             wanttext[idx] = ((*d ^ rv
1200                               ^ (selstart <= d && d < selend ?
1201                                  ATTR_REVERSE : 0)) |
1202                              (i==our_curs_y && j==curs_x ? cursor : 0));
1203         }
1204     }
1205
1206     /*
1207      * We would perform scrolling optimisations in here, if they
1208      * didn't have a nasty tendency to cause the whole sodding
1209      * program to hang for a second at speed-critical moments.
1210      * We'll leave it well alone...
1211      */
1212
1213     for (i=0; i<rows; i++) {
1214         int idx = i*(cols+1);
1215         start = -1;
1216         for (j=0; j<=cols; j++,idx++) {
1217             unsigned long t = wanttext[idx];
1218             int needs_update = (j < cols && t != disptext[idx]);
1219             int keep_going = (start != -1 && needs_update &&
1220                               (t & ATTR_MASK) == attr &&
1221                               j-start < sizeof(ch));
1222             if (start != -1 && !keep_going) {
1223                 do_text (ctx, start, i, ch, j-start, attr);
1224                 start = -1;
1225             }
1226             if (needs_update) {
1227                 if (start == -1) {
1228                     start = j;
1229                     attr = t & ATTR_MASK;
1230                 }
1231                 ch[j-start] = (char) (t & CHAR_MASK);
1232             }
1233             disptext[idx] = t;
1234         }
1235     }
1236 }
1237
1238 /*
1239  * Invalidate the whole screen so it will be repainted in full.
1240  */
1241 void term_invalidate(void) {
1242     int i;
1243
1244     for (i=0; i<rows*(cols+1); i++)
1245         disptext[i] = ATTR_INVALID;
1246 }
1247
1248 /*
1249  * Paint the window in response to a WM_PAINT message.
1250  */
1251 void term_paint (Context ctx, int l, int t, int r, int b) {
1252     int i, j, left, top, right, bottom;
1253
1254     left = l / font_width;
1255     right = (r - 1) / font_width;
1256     top = t / font_height;
1257     bottom = (b - 1) / font_height;
1258     for (i = top; i <= bottom && i < rows ; i++)
1259       for (j = left; j <= right && j < cols ; j++)
1260             disptext[i*(cols+1)+j] = ATTR_INVALID;
1261
1262     do_paint (ctx, FALSE);
1263 }
1264
1265 /*
1266  * Attempt to scroll the scrollback. The second parameter gives the
1267  * position we want to scroll to; the first is +1 to denote that
1268  * this position is relative to the beginning of the scrollback, -1
1269  * to denote it is relative to the end, and 0 to denote that it is
1270  * relative to the current position.
1271  */
1272 void term_scroll (int rel, int where) {
1273     int n = where * (cols+1);
1274
1275     disptop = (rel < 0 ? scrtop :
1276                rel > 0 ? sbtop : disptop) + n;
1277     if (disptop < sbtop)
1278         disptop = sbtop;
1279     if (disptop > scrtop)
1280         disptop = scrtop;
1281     update_sbar();
1282     term_update();
1283 }
1284
1285 /*
1286  * Spread the selection outwards according to the selection mode.
1287  */
1288 static unsigned long *sel_spread_half (unsigned long *p, int dir) {
1289     unsigned long *linestart, *lineend;
1290     int x;
1291     short wvalue;
1292
1293     x = (p - text) % (cols+1);
1294     linestart = p - x;
1295     lineend = linestart + cols;
1296
1297     switch (selmode) {
1298       case SM_CHAR:
1299         /*
1300          * In this mode, every character is a separate unit, except
1301          * for runs of spaces at the end of a non-wrapping line.
1302          */
1303         if (!(linestart[cols] & ATTR_WRAPPED)) {
1304             unsigned long *q = lineend;
1305             while (q > linestart && (q[-1] & CHAR_MASK) == 0x20)
1306                 q--;
1307             if (q == lineend)
1308                 q--;
1309             if (p >= q)
1310                 p = (dir == -1 ? q : lineend - 1);
1311         }
1312         break;
1313       case SM_WORD:
1314         /*
1315          * In this mode, the units are maximal runs of characters
1316          * whose `wordness' has the same value.
1317          */
1318         wvalue = wordness[*p & CHAR_MASK];
1319         if (dir == +1) {
1320             while (p < lineend && wordness[p[1] & CHAR_MASK] == wvalue)
1321                 p++;
1322         } else {
1323             while (p > linestart && wordness[p[-1] & CHAR_MASK] == wvalue)
1324                 p--;
1325         }
1326         break;
1327       case SM_LINE:
1328         /*
1329          * In this mode, every line is a unit.
1330          */
1331         p = (dir == -1 ? linestart : lineend - 1);
1332         break;
1333     }
1334     return p;
1335 }
1336
1337 static void sel_spread (void) {
1338     selstart = sel_spread_half (selstart, -1);
1339     selend = sel_spread_half (selend - 1, +1) + 1;
1340 }
1341
1342 void term_mouse (Mouse_Button b, Mouse_Action a, int x, int y) {
1343     unsigned long *selpoint;
1344     
1345     if (y<0) y = 0;
1346     if (y>=rows) y = rows-1;
1347     if (x<0) {
1348         if (y > 0) {
1349             x = cols-1;
1350             y--;
1351         } else
1352             x = 0;
1353     }
1354     if (x>=cols) x = cols-1;
1355
1356     selpoint = disptop + y * (cols+1) + x;
1357
1358     if (b == MB_SELECT && a == MA_CLICK) {
1359         deselect();
1360         selstate = ABOUT_TO;
1361         selanchor = selpoint;
1362         selmode = SM_CHAR;
1363     } else if (b == MB_SELECT && (a == MA_2CLK || a == MA_3CLK)) {
1364         deselect();
1365         selmode = (a == MA_2CLK ? SM_WORD : SM_LINE);
1366         selstate = DRAGGING;
1367         selstart = selanchor = selpoint;
1368         selend = selstart + 1;
1369         sel_spread();
1370     } else if ((b == MB_SELECT && a == MA_DRAG) ||
1371                (b == MB_EXTEND && a != MA_RELEASE)) {
1372         if (selstate == ABOUT_TO && selanchor == selpoint)
1373             return;
1374         if (b == MB_EXTEND && a != MA_DRAG && selstate == SELECTED) {
1375             if (selpoint-selstart < (selend-selstart)/2)
1376                 selanchor = selend - 1;
1377             else
1378                 selanchor = selstart;
1379             selstate = DRAGGING;
1380         }
1381         if (selstate != ABOUT_TO && selstate != DRAGGING)
1382             selanchor = selpoint;
1383         selstate = DRAGGING;
1384         if (selpoint < selanchor) {
1385             selstart = selpoint;
1386             selend = selanchor + 1;
1387         } else {
1388             selstart = selanchor;
1389             selend = selpoint + 1;
1390         }
1391         sel_spread();
1392     } else if ((b == MB_SELECT || b == MB_EXTEND) && a == MA_RELEASE) {
1393         if (selstate == DRAGGING) {
1394             /*
1395              * We've completed a selection. We now transfer the
1396              * data to the clipboard.
1397              */
1398             unsigned char *p = selspace;
1399             unsigned long *q = selstart;
1400
1401             while (q < selend) {
1402                 int nl = FALSE;
1403                 unsigned long *lineend = q - (q-text) % (cols+1) + cols;
1404                 unsigned long *nlpos = lineend;
1405
1406                 if (!(*nlpos & ATTR_WRAPPED)) {
1407                     while ((nlpos[-1] & CHAR_MASK) == 0x20 && nlpos > q)
1408                         nlpos--;
1409                     if (nlpos < selend)
1410                         nl = TRUE;
1411                 }
1412                 while (q < nlpos && q < selend)
1413                     *p++ = (unsigned char) (*q++ & CHAR_MASK);
1414                 if (nl) {
1415                     int i;
1416                     for (i=0; i<sizeof(sel_nl); i++)
1417                         *p++ = sel_nl[i];
1418                 }
1419                 q = lineend + 1;       /* start of next line */
1420             }
1421             write_clip (selspace, p - selspace);
1422             selstate = SELECTED;
1423         } else
1424             selstate = NO_SELECTION;
1425     } else if (b == MB_PASTE && (a==MA_CLICK || a==MA_2CLK || a==MA_3CLK)) {
1426         char *data;
1427         int len;
1428
1429         get_clip((void **) &data, &len);
1430         if (data) {
1431             char *p, *q;
1432             p = q = data;
1433             while (p < data+len) {
1434                 while (p < data+len &&
1435                        !(p <= data+len-sizeof(sel_nl) &&
1436                          !memcmp(p, sel_nl, sizeof(sel_nl))))
1437                     p++;
1438
1439                 {
1440                     int i;
1441                     unsigned char c;
1442                     for(i=0;i<p-q;i++)
1443                     {
1444                         c=xlat_kbd2tty(q[i]);
1445                         ldisc->send(&c,1);
1446                     }
1447                 }
1448
1449                 if (p <= data+len-sizeof(sel_nl) &&
1450                     !memcmp(p, sel_nl, sizeof(sel_nl))) {
1451                     ldisc->send ("\r", 1);
1452                     p += sizeof(sel_nl);
1453                 }
1454                 q = p;
1455             }
1456         }
1457         get_clip(NULL, NULL);
1458     }
1459
1460     term_update();
1461 }
1462
1463 static void deselect (void) {
1464     selstate = NO_SELECTION;
1465     selstart = selend = scrtop;
1466 }
1467
1468 void term_deselect (void) {
1469     deselect();
1470     term_update();
1471 }