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