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