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