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