xref: /netbsd-src/external/bsd/tmux/dist/window-copy.c (revision 46f5119e40af2e51998f686b2fdcc76b5488f7f3)
1 /* $Id: window-copy.c,v 1.1.1.1 2011/03/10 09:15:40 jmmv Exp $ */
2 
3 /*
4  * Copyright (c) 2007 Nicholas Marriott <nicm@users.sourceforge.net>
5  *
6  * Permission to use, copy, modify, and distribute this software for any
7  * purpose with or without fee is hereby granted, provided that the above
8  * copyright notice and this permission notice appear in all copies.
9  *
10  * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
11  * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
12  * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
13  * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
14  * WHATSOEVER RESULTING FROM LOSS OF MIND, USE, DATA OR PROFITS, WHETHER
15  * IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING
16  * OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
17  */
18 
19 #include <sys/types.h>
20 
21 #include <stdlib.h>
22 #include <string.h>
23 
24 #include "tmux.h"
25 
26 struct screen *window_copy_init(struct window_pane *);
27 void	window_copy_free(struct window_pane *);
28 void	window_copy_resize(struct window_pane *, u_int, u_int);
29 void	window_copy_key(struct window_pane *, struct session *, int);
30 int	window_copy_key_input(struct window_pane *, int);
31 int	window_copy_key_numeric_prefix(struct window_pane *, int);
32 void	window_copy_mouse(
33 	    struct window_pane *, struct session *, struct mouse_event *);
34 
35 void	window_copy_redraw_lines(struct window_pane *, u_int, u_int);
36 void	window_copy_redraw_screen(struct window_pane *);
37 void	window_copy_write_line(
38 	    struct window_pane *, struct screen_write_ctx *, u_int);
39 void	window_copy_write_lines(
40 	    struct window_pane *, struct screen_write_ctx *, u_int, u_int);
41 
42 void	window_copy_scroll_to(struct window_pane *, u_int, u_int);
43 int	window_copy_search_compare(
44 	    struct grid *, u_int, u_int, struct grid *, u_int);
45 int	window_copy_search_lr(
46 	    struct grid *, struct grid *, u_int *, u_int, u_int, u_int);
47 int	window_copy_search_rl(
48 	    struct grid *, struct grid *, u_int *, u_int, u_int, u_int);
49 void	window_copy_search_up(struct window_pane *, const char *);
50 void	window_copy_search_down(struct window_pane *, const char *);
51 void	window_copy_goto_line(struct window_pane *, const char *);
52 void	window_copy_update_cursor(struct window_pane *, u_int, u_int);
53 void	window_copy_start_selection(struct window_pane *);
54 int	window_copy_update_selection(struct window_pane *);
55 void	window_copy_copy_selection(struct window_pane *, struct session *);
56 void	window_copy_clear_selection(struct window_pane *);
57 void	window_copy_copy_line(
58 	    struct window_pane *, char **, size_t *, u_int, u_int, u_int);
59 int	window_copy_in_set(struct window_pane *, u_int, u_int, const char *);
60 u_int	window_copy_find_length(struct window_pane *, u_int);
61 void	window_copy_cursor_start_of_line(struct window_pane *);
62 void	window_copy_cursor_back_to_indentation(struct window_pane *);
63 void	window_copy_cursor_end_of_line(struct window_pane *);
64 void	window_copy_cursor_left(struct window_pane *);
65 void	window_copy_cursor_right(struct window_pane *);
66 void	window_copy_cursor_up(struct window_pane *, int);
67 void	window_copy_cursor_down(struct window_pane *, int);
68 void	window_copy_cursor_jump(struct window_pane *);
69 void	window_copy_cursor_jump_back(struct window_pane *);
70 void	window_copy_cursor_next_word(struct window_pane *, const char *);
71 void	window_copy_cursor_next_word_end(struct window_pane *, const char *);
72 void	window_copy_cursor_previous_word(struct window_pane *, const char *);
73 void	window_copy_scroll_up(struct window_pane *, u_int);
74 void	window_copy_scroll_down(struct window_pane *, u_int);
75 void	window_copy_rectangle_toggle(struct window_pane *);
76 
77 const struct window_mode window_copy_mode = {
78 	window_copy_init,
79 	window_copy_free,
80 	window_copy_resize,
81 	window_copy_key,
82 	window_copy_mouse,
83 	NULL,
84 };
85 
86 enum window_copy_input_type {
87 	WINDOW_COPY_OFF,
88 	WINDOW_COPY_NUMERICPREFIX,
89 	WINDOW_COPY_SEARCHUP,
90 	WINDOW_COPY_SEARCHDOWN,
91 	WINDOW_COPY_JUMPFORWARD,
92 	WINDOW_COPY_JUMPBACK,
93 	WINDOW_COPY_GOTOLINE,
94 };
95 
96 /*
97  * Copy-mode's visible screen (the "screen" field) is filled from one of
98  * two sources: the original contents of the pane (used when we
99  * actually enter via the "copy-mode" command, to copy the contents of
100  * the current pane), or else a series of lines containing the output
101  * from an output-writing tmux command (such as any of the "show-*" or
102  * "list-*" commands).
103  *
104  * In either case, the full content of the copy-mode grid is pointed at
105  * by the "backing" field, and is copied into "screen" as needed (that
106  * is, when scrolling occurs). When copy-mode is backed by a pane,
107  * backing points directly at that pane's screen structure (&wp->base);
108  * when backed by a list of output-lines from a command, it points at
109  * a newly-allocated screen structure (which is deallocated when the
110  * mode ends).
111  */
112 struct window_copy_mode_data {
113 	struct screen	screen;
114 
115 	struct screen  *backing;
116 	int		backing_written; /* backing display has started */
117 
118 	struct mode_key_data mdata;
119 
120 	u_int		oy;
121 
122 	u_int		selx;
123 	u_int		sely;
124 
125 	u_int		rectflag; /* are we in rectangle copy mode? */
126 
127 	u_int		cx;
128 	u_int		cy;
129 
130 	u_int		lastcx; /* position in last line with content */
131 	u_int		lastsx; /* size of last line with content */
132 
133 	enum window_copy_input_type inputtype;
134 	const char     *inputprompt;
135 	char   	       *inputstr;
136 
137 	u_int		numprefix;
138 
139 	enum window_copy_input_type searchtype;
140 	char	       *searchstr;
141 
142 	enum window_copy_input_type jumptype;
143 	char		jumpchar;
144 };
145 
146 struct screen *
147 window_copy_init(struct window_pane *wp)
148 {
149 	struct window_copy_mode_data	*data;
150 	struct screen			*s;
151 	int				 keys;
152 
153 	wp->modedata = data = xmalloc(sizeof *data);
154 	data->oy = 0;
155 	data->cx = 0;
156 	data->cy = 0;
157 
158 	data->lastcx = 0;
159 	data->lastsx = 0;
160 
161 	data->backing_written = 0;
162 
163 	data->rectflag = 0;
164 
165 	data->inputtype = WINDOW_COPY_OFF;
166 	data->inputprompt = NULL;
167 	data->inputstr = xstrdup("");
168 	data->numprefix = 0;
169 
170 	data->searchtype = WINDOW_COPY_OFF;
171 	data->searchstr = NULL;
172 
173 	wp->flags |= PANE_FREEZE;
174 	if (wp->fd != -1)
175 		bufferevent_disable(wp->event, EV_READ|EV_WRITE);
176 
177 	data->jumptype = WINDOW_COPY_OFF;
178 	data->jumpchar = '\0';
179 
180 	s = &data->screen;
181 	screen_init(s, screen_size_x(&wp->base), screen_size_y(&wp->base), 0);
182 	if (options_get_number(&wp->window->options, "mode-mouse"))
183 		s->mode |= MODE_MOUSE;
184 
185 	keys = options_get_number(&wp->window->options, "mode-keys");
186 	if (keys == MODEKEY_EMACS)
187 		mode_key_init(&data->mdata, &mode_key_tree_emacs_copy);
188 	else
189 		mode_key_init(&data->mdata, &mode_key_tree_vi_copy);
190 
191 	data->backing = NULL;
192 
193 	return (s);
194 }
195 
196 void
197 window_copy_init_from_pane(struct window_pane *wp)
198 {
199 	struct window_copy_mode_data	*data = wp->modedata;
200 	struct screen			*s = &data->screen;
201 	struct screen_write_ctx	 	 ctx;
202 	u_int				 i;
203 
204 	if (wp->mode != &window_copy_mode)
205 		fatalx("not in copy mode");
206 
207 	data->backing = &wp->base;
208 	data->cx = data->backing->cx;
209 	data->cy = data->backing->cy;
210 
211 	s->cx = data->cx;
212 	s->cy = data->cy;
213 
214 	screen_write_start(&ctx, NULL, s);
215 	for (i = 0; i < screen_size_y(s); i++)
216 		window_copy_write_line(wp, &ctx, i);
217 	screen_write_cursormove(&ctx, data->cx, data->cy);
218 	screen_write_stop(&ctx);
219 }
220 
221 void
222 window_copy_init_for_output(struct window_pane *wp)
223 {
224 	struct window_copy_mode_data	*data = wp->modedata;
225 
226 	data->backing = xmalloc(sizeof *data->backing);
227 	screen_init(data->backing, screen_size_x(&wp->base),
228 	    screen_size_y(&wp->base), UINT_MAX);
229 	data->backing->mode &= ~MODE_WRAP;
230 }
231 
232 void
233 window_copy_free(struct window_pane *wp)
234 {
235 	struct window_copy_mode_data	*data = wp->modedata;
236 
237 	wp->flags &= ~PANE_FREEZE;
238 	if (wp->fd != -1)
239 		bufferevent_enable(wp->event, EV_READ|EV_WRITE);
240 
241 	if (data->searchstr != NULL)
242 		xfree(data->searchstr);
243 	xfree(data->inputstr);
244 
245 	if (data->backing != &wp->base) {
246 		screen_free(data->backing);
247 		xfree(data->backing);
248 	}
249 	screen_free(&data->screen);
250 
251 	xfree(data);
252 }
253 
254 void
255 window_copy_add(struct window_pane *wp, const char *fmt, ...)
256 {
257 	va_list	ap;
258 
259 	va_start(ap, fmt);
260 	window_copy_vadd(wp, fmt, ap);
261 	va_end(ap);
262 }
263 
264 void
265 window_copy_vadd(struct window_pane *wp, const char *fmt, va_list ap)
266 {
267 	struct window_copy_mode_data	*data = wp->modedata;
268 	struct screen			*backing = data->backing;
269 	struct screen_write_ctx	 	 back_ctx, ctx;
270 	struct grid_cell		 gc;
271 	int				 utf8flag;
272 	u_int				 old_hsize;
273 
274 	if (backing == &wp->base)
275 		return;
276 
277 	utf8flag = options_get_number(&wp->window->options, "utf8");
278 	memcpy(&gc, &grid_default_cell, sizeof gc);
279 
280 	old_hsize = screen_hsize(data->backing);
281 	screen_write_start(&back_ctx, NULL, backing);
282 	if (data->backing_written) {
283 		/*
284 		 * On the second or later line, do a CRLF before writing
285 		 * (so it's on a new line).
286 		 */
287 		screen_write_carriagereturn(&back_ctx);
288 		screen_write_linefeed(&back_ctx, 0);
289 	} else
290 		data->backing_written = 1;
291 	screen_write_vnputs(&back_ctx, 0, &gc, utf8flag, fmt, ap);
292 	screen_write_stop(&back_ctx);
293 
294 	data->oy += screen_hsize(data->backing) - old_hsize;
295 
296 	screen_write_start(&ctx, wp, &data->screen);
297 
298 	/*
299 	 * If the history has changed, draw the top line.
300 	 * (If there's any history at all, it has changed.)
301 	 */
302 	if (screen_hsize(data->backing))
303 		window_copy_redraw_lines(wp, 0, 1);
304 
305 	/* Write the line, if it's visible. */
306 	if (backing->cy + data->oy < screen_size_y(backing))
307 		window_copy_redraw_lines(wp, backing->cy, 1);
308 
309 	screen_write_stop(&ctx);
310 }
311 
312 void
313 window_copy_pageup(struct window_pane *wp)
314 {
315 	struct window_copy_mode_data	*data = wp->modedata;
316 	struct screen			*s = &data->screen;
317 	u_int				 n;
318 
319 	n = 1;
320 	if (screen_size_y(s) > 2)
321 		n = screen_size_y(s) - 2;
322 	if (data->oy + n > screen_hsize(data->backing))
323 		data->oy = screen_hsize(data->backing);
324 	else
325 		data->oy += n;
326 	window_copy_update_selection(wp);
327 	window_copy_redraw_screen(wp);
328 }
329 
330 void
331 window_copy_resize(struct window_pane *wp, u_int sx, u_int sy)
332 {
333 	struct window_copy_mode_data	*data = wp->modedata;
334 	struct screen			*s = &data->screen;
335 	struct screen_write_ctx	 	 ctx;
336 
337 	screen_resize(s, sx, sy);
338 	if (data->backing != &wp->base)
339 		screen_resize(data->backing, sx, sy);
340 
341 	if (data->cy > sy - 1)
342 		data->cy = sy - 1;
343 	if (data->cx > sx)
344 		data->cx = sx;
345 	if (data->oy > screen_hsize(data->backing))
346 		data->oy = screen_hsize(data->backing);
347 
348 	window_copy_clear_selection(wp);
349 
350 	screen_write_start(&ctx, NULL, s);
351 	window_copy_write_lines(wp, &ctx, 0, screen_size_y(s) - 1);
352 	screen_write_stop(&ctx);
353 
354 	window_copy_redraw_screen(wp);
355 }
356 
357 void
358 window_copy_key(struct window_pane *wp, struct session *sess, int key)
359 {
360 	const char			*word_separators;
361 	struct window_copy_mode_data	*data = wp->modedata;
362 	struct screen			*s = &data->screen;
363 	u_int				 n, np;
364 	int				 keys;
365 	enum mode_key_cmd		 cmd;
366 
367 	np = data->numprefix;
368 	if (np == 0)
369 		np = 1;
370 
371 	if (data->inputtype == WINDOW_COPY_JUMPFORWARD
372 	    || data->inputtype == WINDOW_COPY_JUMPBACK) {
373 		/* Ignore keys with modifiers. */
374 		if ((key & KEYC_MASK_MOD) == 0) {
375 			data->jumpchar = key;
376 			if (data->inputtype == WINDOW_COPY_JUMPFORWARD) {
377 				for (; np != 0; np--)
378 					window_copy_cursor_jump(wp);
379 			}  else {
380 				for (; np != 0; np--)
381 					window_copy_cursor_jump_back(wp);
382 			}
383 		}
384 		data->jumptype = data->inputtype;
385 		data->inputtype = WINDOW_COPY_OFF;
386 		window_copy_redraw_lines(wp, screen_size_y(s) - 1, 1);
387 		return;
388 	} if (data->inputtype == WINDOW_COPY_NUMERICPREFIX) {
389 		if (window_copy_key_numeric_prefix(wp, key) == 0)
390 			return;
391 		data->inputtype = WINDOW_COPY_OFF;
392 		window_copy_redraw_lines(wp, screen_size_y(s) - 1, 1);
393 	} else if (data->inputtype != WINDOW_COPY_OFF) {
394 		if (window_copy_key_input(wp, key) != 0)
395 			goto input_off;
396 		return;
397 	}
398 
399 	cmd = mode_key_lookup(&data->mdata, key);
400 	switch (cmd) {
401 	case MODEKEYCOPY_CANCEL:
402 		window_pane_reset_mode(wp);
403 		return;
404 	case MODEKEYCOPY_LEFT:
405 		for (; np != 0; np--)
406 			window_copy_cursor_left(wp);
407 		break;
408 	case MODEKEYCOPY_RIGHT:
409 		for (; np != 0; np--)
410 			window_copy_cursor_right(wp);
411 		break;
412 	case MODEKEYCOPY_UP:
413 		for (; np != 0; np--)
414 			window_copy_cursor_up(wp, 0);
415 		break;
416 	case MODEKEYCOPY_DOWN:
417 		for (; np != 0; np--)
418 			window_copy_cursor_down(wp, 0);
419 		break;
420 	case MODEKEYCOPY_SCROLLUP:
421 		for (; np != 0; np--)
422 			window_copy_cursor_up(wp, 1);
423 		break;
424 	case MODEKEYCOPY_SCROLLDOWN:
425 		for (; np != 0; np--)
426 			window_copy_cursor_down(wp, 1);
427 		break;
428 	case MODEKEYCOPY_PREVIOUSPAGE:
429 		for (; np != 0; np--)
430 			window_copy_pageup(wp);
431 		break;
432 	case MODEKEYCOPY_NEXTPAGE:
433 		n = 1;
434 		if (screen_size_y(s) > 2)
435 			n = screen_size_y(s) - 2;
436 		for (; np != 0; np--) {
437 			if (data->oy < n)
438 				data->oy = 0;
439 			else
440 				data->oy -= n;
441 		}
442 		window_copy_update_selection(wp);
443 		window_copy_redraw_screen(wp);
444 		break;
445 	case MODEKEYCOPY_HALFPAGEUP:
446 		n = screen_size_y(s) / 2;
447 		for (; np != 0; np--) {
448 			if (data->oy + n > screen_hsize(data->backing))
449 				data->oy = screen_hsize(data->backing);
450 			else
451 				data->oy += n;
452 		}
453 		window_copy_update_selection(wp);
454 		window_copy_redraw_screen(wp);
455 		break;
456 	case MODEKEYCOPY_HALFPAGEDOWN:
457 		n = screen_size_y(s) / 2;
458 		for (; np != 0; np--) {
459 			if (data->oy < n)
460 				data->oy = 0;
461 			else
462 				data->oy -= n;
463 		}
464 		window_copy_update_selection(wp);
465 		window_copy_redraw_screen(wp);
466 		break;
467 	case MODEKEYCOPY_TOPLINE:
468 		data->cx = 0;
469 		data->cy = 0;
470 		window_copy_update_selection(wp);
471 		window_copy_redraw_screen(wp);
472 		break;
473 	case MODEKEYCOPY_MIDDLELINE:
474 		data->cx = 0;
475 		data->cy = (screen_size_y(s) - 1) / 2;
476 		window_copy_update_selection(wp);
477 		window_copy_redraw_screen(wp);
478 		break;
479 	case MODEKEYCOPY_BOTTOMLINE:
480 		data->cx = 0;
481 		data->cy = screen_size_y(s) - 1;
482 		window_copy_update_selection(wp);
483 		window_copy_redraw_screen(wp);
484 		break;
485 	case MODEKEYCOPY_HISTORYTOP:
486 		data->cx = 0;
487 		data->cy = 0;
488 		data->oy = screen_hsize(data->backing);
489 		window_copy_update_selection(wp);
490 		window_copy_redraw_screen(wp);
491 		break;
492 	case MODEKEYCOPY_HISTORYBOTTOM:
493 		data->cx = 0;
494 		data->cy = screen_size_y(s) - 1;
495 		data->oy = 0;
496 		window_copy_update_selection(wp);
497 		window_copy_redraw_screen(wp);
498 		break;
499 	case MODEKEYCOPY_STARTSELECTION:
500 		window_copy_start_selection(wp);
501 		window_copy_redraw_screen(wp);
502 		break;
503 	case MODEKEYCOPY_CLEARSELECTION:
504 		window_copy_clear_selection(wp);
505 		window_copy_redraw_screen(wp);
506 		break;
507 	case MODEKEYCOPY_COPYSELECTION:
508 		if (sess != NULL) {
509 			window_copy_copy_selection(wp, sess);
510 			window_pane_reset_mode(wp);
511 			return;
512 		}
513 		break;
514 	case MODEKEYCOPY_STARTOFLINE:
515 		window_copy_cursor_start_of_line(wp);
516 		break;
517 	case MODEKEYCOPY_BACKTOINDENTATION:
518 		window_copy_cursor_back_to_indentation(wp);
519 		break;
520 	case MODEKEYCOPY_ENDOFLINE:
521 		window_copy_cursor_end_of_line(wp);
522 		break;
523 	case MODEKEYCOPY_NEXTSPACE:
524 		for (; np != 0; np--)
525 			window_copy_cursor_next_word(wp, " ");
526 		break;
527 	case MODEKEYCOPY_NEXTSPACEEND:
528 		for (; np != 0; np--)
529 			window_copy_cursor_next_word_end(wp, " ");
530 		break;
531 	case MODEKEYCOPY_NEXTWORD:
532 		word_separators =
533 		    options_get_string(&wp->window->options, "word-separators");
534 		for (; np != 0; np--)
535 			window_copy_cursor_next_word(wp, word_separators);
536 		break;
537 	case MODEKEYCOPY_NEXTWORDEND:
538 		word_separators =
539 		    options_get_string(&wp->window->options, "word-separators");
540 		for (; np != 0; np--)
541 			window_copy_cursor_next_word_end(wp, word_separators);
542 		break;
543 	case MODEKEYCOPY_PREVIOUSSPACE:
544 		for (; np != 0; np--)
545 			window_copy_cursor_previous_word(wp, " ");
546 		break;
547 	case MODEKEYCOPY_PREVIOUSWORD:
548 		word_separators =
549 		    options_get_string(&wp->window->options, "word-separators");
550 		for (; np != 0; np--)
551 			window_copy_cursor_previous_word(wp, word_separators);
552 		break;
553 	case MODEKEYCOPY_JUMP:
554 		data->inputtype = WINDOW_COPY_JUMPFORWARD;
555 		data->inputprompt = "Jump Forward";
556 		*data->inputstr = '\0';
557 		window_copy_redraw_lines(wp, screen_size_y(s) - 1, 1);
558 		return; /* skip numprefix reset */
559 	case MODEKEYCOPY_JUMPAGAIN:
560 		if (data->jumptype == WINDOW_COPY_JUMPFORWARD) {
561 			for (; np != 0; np--)
562 				window_copy_cursor_jump(wp);
563 		} else if (data->jumptype == WINDOW_COPY_JUMPBACK) {
564 			for (; np != 0; np--)
565 				window_copy_cursor_jump_back(wp);
566 		}
567 		break;
568 	case MODEKEYCOPY_JUMPREVERSE:
569 		if (data->jumptype == WINDOW_COPY_JUMPFORWARD) {
570 			for (; np != 0; np--)
571 				window_copy_cursor_jump_back(wp);
572 		} else if (data->jumptype == WINDOW_COPY_JUMPBACK) {
573 			for (; np != 0; np--)
574 				window_copy_cursor_jump(wp);
575 		}
576 		break;
577 	case MODEKEYCOPY_JUMPBACK:
578 		data->inputtype = WINDOW_COPY_JUMPBACK;
579 		data->inputprompt = "Jump Back";
580 		*data->inputstr = '\0';
581 		window_copy_redraw_lines(wp, screen_size_y(s) - 1, 1);
582 		return; /* skip numprefix reset */
583 	case MODEKEYCOPY_SEARCHUP:
584 		data->inputtype = WINDOW_COPY_SEARCHUP;
585 		data->inputprompt = "Search Up";
586 		goto input_on;
587 	case MODEKEYCOPY_SEARCHDOWN:
588 		data->inputtype = WINDOW_COPY_SEARCHDOWN;
589 		data->inputprompt = "Search Down";
590 		goto input_on;
591 	case MODEKEYCOPY_SEARCHAGAIN:
592 	case MODEKEYCOPY_SEARCHREVERSE:
593 		switch (data->searchtype) {
594 		case WINDOW_COPY_OFF:
595 		case WINDOW_COPY_GOTOLINE:
596 		case WINDOW_COPY_JUMPFORWARD:
597 		case WINDOW_COPY_JUMPBACK:
598 		case WINDOW_COPY_NUMERICPREFIX:
599 			break;
600 		case WINDOW_COPY_SEARCHUP:
601 			if (cmd == MODEKEYCOPY_SEARCHAGAIN) {
602 				for (; np != 0; np--) {
603 					window_copy_search_up(
604 					    wp, data->searchstr);
605 				}
606 			} else {
607 				for (; np != 0; np--) {
608 					window_copy_search_down(
609 					    wp, data->searchstr);
610 				}
611 			}
612 			break;
613 		case WINDOW_COPY_SEARCHDOWN:
614 			if (cmd == MODEKEYCOPY_SEARCHAGAIN) {
615 				for (; np != 0; np--) {
616 					window_copy_search_down(
617 					    wp, data->searchstr);
618 				}
619 			} else {
620 				for (; np != 0; np--) {
621 					window_copy_search_up(
622 					    wp, data->searchstr);
623 				}
624 			}
625 			break;
626 		}
627 		break;
628 	case MODEKEYCOPY_GOTOLINE:
629 		data->inputtype = WINDOW_COPY_GOTOLINE;
630 		data->inputprompt = "Goto Line";
631 		*data->inputstr = '\0';
632 		goto input_on;
633 	case MODEKEYCOPY_STARTNUMBERPREFIX:
634 		key &= KEYC_MASK_KEY;
635 		if (key >= '0' && key <= '9') {
636 			data->inputtype = WINDOW_COPY_NUMERICPREFIX;
637 			data->numprefix = 0;
638 			window_copy_key_numeric_prefix(wp, key);
639 			return;
640 		}
641 		break;
642 	case MODEKEYCOPY_RECTANGLETOGGLE:
643 		window_copy_rectangle_toggle(wp);
644 		break;
645 	default:
646 		break;
647 	}
648 
649 	data->numprefix = 0;
650 	return;
651 
652 input_on:
653 	keys = options_get_number(&wp->window->options, "mode-keys");
654 	if (keys == MODEKEY_EMACS)
655 		mode_key_init(&data->mdata, &mode_key_tree_emacs_edit);
656 	else
657 		mode_key_init(&data->mdata, &mode_key_tree_vi_edit);
658 
659 	window_copy_redraw_lines(wp, screen_size_y(s) - 1, 1);
660 	return;
661 
662 input_off:
663 	keys = options_get_number(&wp->window->options, "mode-keys");
664 	if (keys == MODEKEY_EMACS)
665 		mode_key_init(&data->mdata, &mode_key_tree_emacs_copy);
666 	else
667 		mode_key_init(&data->mdata, &mode_key_tree_vi_copy);
668 
669 	data->inputtype = WINDOW_COPY_OFF;
670 	data->inputprompt = NULL;
671 
672 	window_copy_redraw_lines(wp, screen_size_y(s) - 1, 1);
673 }
674 
675 int
676 window_copy_key_input(struct window_pane *wp, int key)
677 {
678 	struct window_copy_mode_data	*data = wp->modedata;
679 	struct screen			*s = &data->screen;
680 	size_t				 inputlen;
681 	u_int				 np;
682 
683 	switch (mode_key_lookup(&data->mdata, key)) {
684 	case MODEKEYEDIT_CANCEL:
685 		data->numprefix = 0;
686 		return (-1);
687 	case MODEKEYEDIT_BACKSPACE:
688 		inputlen = strlen(data->inputstr);
689 		if (inputlen > 0)
690 			data->inputstr[inputlen - 1] = '\0';
691 		break;
692 	case MODEKEYEDIT_DELETELINE:
693 		*data->inputstr = '\0';
694 		break;
695 	case MODEKEYEDIT_ENTER:
696 		np = data->numprefix;
697 		if (np == 0)
698 			np = 1;
699 
700 		switch (data->inputtype) {
701 		case WINDOW_COPY_OFF:
702 		case WINDOW_COPY_JUMPFORWARD:
703 		case WINDOW_COPY_JUMPBACK:
704 		case WINDOW_COPY_NUMERICPREFIX:
705 			break;
706 		case WINDOW_COPY_SEARCHUP:
707 			for (; np != 0; np--)
708 				window_copy_search_up(wp, data->inputstr);
709 			data->searchtype = data->inputtype;
710 			data->searchstr = xstrdup(data->inputstr);
711 			break;
712 		case WINDOW_COPY_SEARCHDOWN:
713 			for (; np != 0; np--)
714 				window_copy_search_down(wp, data->inputstr);
715 			data->searchtype = data->inputtype;
716 			data->searchstr = xstrdup(data->inputstr);
717 			break;
718 		case WINDOW_COPY_GOTOLINE:
719 			window_copy_goto_line(wp, data->inputstr);
720 			*data->inputstr = '\0';
721 			break;
722 		}
723 		data->numprefix = 0;
724 		return (1);
725 	case MODEKEY_OTHER:
726 		if (key < 32 || key > 126)
727 			break;
728 		inputlen = strlen(data->inputstr) + 2;
729 
730 		data->inputstr = xrealloc(data->inputstr, 1, inputlen);
731 		data->inputstr[inputlen - 2] = key;
732 		data->inputstr[inputlen - 1] = '\0';
733 		break;
734 	default:
735 		break;
736 	}
737 
738 	window_copy_redraw_lines(wp, screen_size_y(s) - 1, 1);
739 	return (0);
740 }
741 
742 int
743 window_copy_key_numeric_prefix(struct window_pane *wp, int key)
744 {
745 	struct window_copy_mode_data	*data = wp->modedata;
746 	struct screen			*s = &data->screen;
747 
748 	key &= KEYC_MASK_KEY;
749 	if (key < '0' || key > '9')
750 		return 1;
751 
752 	if (data->numprefix >= 100)	/* no more than three digits */
753 		return 0;
754 	data->numprefix = data->numprefix * 10 + key - '0';
755 
756 	window_copy_redraw_lines(wp, screen_size_y(s) - 1, 1);
757 	return 0;
758 }
759 
760 /* ARGSUSED */
761 void
762 window_copy_mouse(
763     struct window_pane *wp, unused struct session *sess, struct mouse_event *m)
764 {
765 	struct window_copy_mode_data	*data = wp->modedata;
766 	struct screen			*s = &data->screen;
767 	u_int				 i;
768 
769 	if (m->x >= screen_size_x(s))
770 		return;
771 	if (m->y >= screen_size_y(s))
772 		return;
773 
774 	/* If mouse wheel (buttons 4 and 5), scroll. */
775 	if ((m->b & MOUSE_45)) {
776 		if ((m->b & MOUSE_BUTTON) == MOUSE_1) {
777 			for (i = 0; i < 5; i++)
778 				window_copy_cursor_up(wp, 0);
779 		} else if ((m->b & MOUSE_BUTTON) == MOUSE_2) {
780 			for (i = 0; i < 5; i++)
781 				window_copy_cursor_down(wp, 0);
782 		}
783 		return;
784 	}
785 
786 	/*
787 	 * If already reading motion, move the cursor while buttons are still
788 	 * pressed, or stop the selection on their release.
789 	 */
790 	if (s->mode & MODE_MOUSEMOTION) {
791 		if ((m->b & MOUSE_BUTTON) != MOUSE_UP) {
792 			window_copy_update_cursor(wp, m->x, m->y);
793 			if (window_copy_update_selection(wp))
794 				window_copy_redraw_screen(wp);
795 		} else {
796 			s->mode &= ~MODE_MOUSEMOTION;
797 			if (sess != NULL) {
798 				window_copy_copy_selection(wp, sess);
799 				window_pane_reset_mode(wp);
800 			}
801 		}
802 		return;
803 	}
804 
805 	/* Otherwise i other buttons pressed, start selection and motion. */
806 	if ((m->b & MOUSE_BUTTON) != MOUSE_UP) {
807 		s->mode |= MODE_MOUSEMOTION;
808 
809 		window_copy_update_cursor(wp, m->x, m->y);
810 		window_copy_start_selection(wp);
811 		window_copy_redraw_screen(wp);
812 	}
813 }
814 
815 void
816 window_copy_scroll_to(struct window_pane *wp, u_int px, u_int py)
817 {
818 	struct window_copy_mode_data	*data = wp->modedata;
819 	struct grid			*gd = data->backing->grid;
820 	u_int				 offset, gap;
821 
822 	data->cx = px;
823 
824 	gap = gd->sy / 4;
825 	if (py < gd->sy) {
826 		offset = 0;
827 		data->cy = py;
828 	} else if (py > gd->hsize + gd->sy - gap) {
829 		offset = gd->hsize;
830 		data->cy = py - gd->hsize;
831 	} else {
832 		offset = py + gap - gd->sy;
833 		data->cy = py - offset;
834 	}
835 	data->oy = gd->hsize - offset;
836 
837 	window_copy_update_selection(wp);
838 	window_copy_redraw_screen(wp);
839 }
840 
841 int
842 window_copy_search_compare(
843     struct grid *gd, u_int px, u_int py, struct grid *sgd, u_int spx)
844 {
845 	const struct grid_cell	*gc, *sgc;
846 	const struct grid_utf8	*gu, *sgu;
847 
848 	gc = grid_peek_cell(gd, px, py);
849 	sgc = grid_peek_cell(sgd, spx, 0);
850 
851 	if ((gc->flags & GRID_FLAG_UTF8) != (sgc->flags & GRID_FLAG_UTF8))
852 		return (0);
853 
854 	if (gc->flags & GRID_FLAG_UTF8) {
855 		gu = grid_peek_utf8(gd, px, py);
856 		sgu = grid_peek_utf8(sgd, spx, 0);
857 		if (grid_utf8_compare(gu, sgu))
858 			return (1);
859 	} else {
860 		if (gc->data == sgc->data)
861 			return (1);
862 	}
863 	return (0);
864 }
865 
866 int
867 window_copy_search_lr(struct grid *gd,
868     struct grid *sgd, u_int *ppx, u_int py, u_int first, u_int last)
869 {
870 	u_int	ax, bx, px;
871 
872 	for (ax = first; ax < last; ax++) {
873 		if (ax + sgd->sx >= gd->sx)
874 			break;
875 		for (bx = 0; bx < sgd->sx; bx++) {
876 			px = ax + bx;
877 			if (!window_copy_search_compare(gd, px, py, sgd, bx))
878 				break;
879 		}
880 		if (bx == sgd->sx) {
881 			*ppx = ax;
882 			return (1);
883 		}
884 	}
885 	return (0);
886 }
887 
888 int
889 window_copy_search_rl(struct grid *gd,
890     struct grid *sgd, u_int *ppx, u_int py, u_int first, u_int last)
891 {
892 	u_int	ax, bx, px;
893 
894 	for (ax = last + 1; ax > first; ax--) {
895 		if (gd->sx - (ax - 1) < sgd->sx)
896 			continue;
897 		for (bx = 0; bx < sgd->sx; bx++) {
898 			px = ax - 1 + bx;
899 			if (!window_copy_search_compare(gd, px, py, sgd, bx))
900 				break;
901 		}
902 		if (bx == sgd->sx) {
903 			*ppx = ax - 1;
904 			return (1);
905 		}
906 	}
907 	return (0);
908 }
909 
910 void
911 window_copy_search_up(struct window_pane *wp, const char *searchstr)
912 {
913 	struct window_copy_mode_data	*data = wp->modedata;
914 	struct screen			*s = data->backing, ss;
915 	struct screen_write_ctx		 ctx;
916 	struct grid			*gd = s->grid, *sgd;
917 	struct grid_cell	 	 gc;
918 	size_t				 searchlen;
919 	u_int				 i, last, fx, fy, px;
920 	int				 utf8flag, n, wrapped;
921 
922 	if (*searchstr == '\0')
923 		return;
924 	utf8flag = options_get_number(&wp->window->options, "utf8");
925 	searchlen = screen_write_strlen(utf8flag, "%s", searchstr);
926 
927 	screen_init(&ss, searchlen, 1, 0);
928 	screen_write_start(&ctx, NULL, &ss);
929 	memcpy(&gc, &grid_default_cell, sizeof gc);
930 	screen_write_nputs(&ctx, -1, &gc, utf8flag, "%s", searchstr);
931 	screen_write_stop(&ctx);
932 
933 	fx = data->cx;
934 	fy = gd->hsize - data->oy + data->cy;
935 
936 	if (fx == 0) {
937 		if (fy == 0)
938 			return;
939 		fx = gd->sx - 1;
940 		fy--;
941 	} else
942 		fx--;
943 	n = wrapped = 0;
944 
945 retry:
946 	sgd = ss.grid;
947 	for (i = fy + 1; i > 0; i--) {
948 		last = screen_size_x(s);
949 		if (i == fy + 1)
950 			last = fx;
951 		n = window_copy_search_rl(gd, sgd, &px, i - 1, 0, last);
952 		if (n) {
953 			window_copy_scroll_to(wp, px, i - 1);
954 			break;
955 		}
956 	}
957 	if (!n && !wrapped) {
958 		fx = gd->sx - 1;
959 		fy = gd->hsize + gd->sy - 1;
960 		wrapped = 1;
961 		goto retry;
962 	}
963 
964 	screen_free(&ss);
965 }
966 
967 void
968 window_copy_search_down(struct window_pane *wp, const char *searchstr)
969 {
970 	struct window_copy_mode_data	*data = wp->modedata;
971 	struct screen			*s = data->backing, ss;
972 	struct screen_write_ctx		 ctx;
973 	struct grid			*gd = s->grid, *sgd;
974 	struct grid_cell	 	 gc;
975 	size_t				 searchlen;
976 	u_int				 i, first, fx, fy, px;
977 	int				 utf8flag, n, wrapped;
978 
979 	if (*searchstr == '\0')
980 		return;
981 	utf8flag = options_get_number(&wp->window->options, "utf8");
982 	searchlen = screen_write_strlen(utf8flag, "%s", searchstr);
983 
984 	screen_init(&ss, searchlen, 1, 0);
985 	screen_write_start(&ctx, NULL, &ss);
986 	memcpy(&gc, &grid_default_cell, sizeof gc);
987 	screen_write_nputs(&ctx, -1, &gc, utf8flag, "%s", searchstr);
988 	screen_write_stop(&ctx);
989 
990 	fx = data->cx;
991 	fy = gd->hsize - data->oy + data->cy;
992 
993 	if (fx == gd->sx - 1) {
994 		if (fy == gd->hsize + gd->sy)
995 			return;
996 		fx = 0;
997 		fy++;
998 	} else
999 		fx++;
1000 	n = wrapped = 0;
1001 
1002 retry:
1003 	sgd = ss.grid;
1004 	for (i = fy + 1; i < gd->hsize + gd->sy; i++) {
1005 		first = 0;
1006 		if (i == fy + 1)
1007 			first = fx;
1008 		n = window_copy_search_lr(gd, sgd, &px, i - 1, first, gd->sx);
1009 		if (n) {
1010 			window_copy_scroll_to(wp, px, i - 1);
1011 			break;
1012 		}
1013 	}
1014 	if (!n && !wrapped) {
1015 		fx = 0;
1016 		fy = 0;
1017 		wrapped = 1;
1018 		goto retry;
1019 	}
1020 
1021 	screen_free(&ss);
1022 }
1023 
1024 void
1025 window_copy_goto_line(struct window_pane *wp, const char *linestr)
1026 {
1027 	struct window_copy_mode_data	*data = wp->modedata;
1028 	const char			*errstr;
1029 	u_int				 lineno;
1030 
1031 	lineno = strtonum(linestr, 0, screen_hsize(data->backing), &errstr);
1032 	if (errstr != NULL)
1033 		return;
1034 
1035 	data->oy = lineno;
1036 	window_copy_update_selection(wp);
1037 	window_copy_redraw_screen(wp);
1038 }
1039 
1040 void
1041 window_copy_write_line(
1042     struct window_pane *wp, struct screen_write_ctx *ctx, u_int py)
1043 {
1044 	struct window_copy_mode_data	*data = wp->modedata;
1045 	struct screen			*s = &data->screen;
1046 	struct options			*oo = &wp->window->options;
1047 	struct grid_cell		 gc;
1048 	char				 hdr[32];
1049 	size_t	 			 last, xoff = 0, size = 0;
1050 
1051 	memcpy(&gc, &grid_default_cell, sizeof gc);
1052 	colour_set_fg(&gc, options_get_number(oo, "mode-fg"));
1053 	colour_set_bg(&gc, options_get_number(oo, "mode-bg"));
1054 	gc.attr |= options_get_number(oo, "mode-attr");
1055 
1056 	last = screen_size_y(s) - 1;
1057 	if (py == 0) {
1058 		size = xsnprintf(hdr, sizeof hdr,
1059 		    "[%u/%u]", data->oy, screen_hsize(data->backing));
1060 		if (size > screen_size_x(s))
1061 			size = screen_size_x(s);
1062 		screen_write_cursormove(ctx, screen_size_x(s) - size, 0);
1063 		screen_write_puts(ctx, &gc, "%s", hdr);
1064 	} else if (py == last && data->inputtype != WINDOW_COPY_OFF) {
1065 		if (data->inputtype == WINDOW_COPY_NUMERICPREFIX) {
1066 			xoff = size = xsnprintf(hdr, sizeof hdr,
1067 			    "Repeat: %u", data->numprefix);
1068 		} else {
1069 			xoff = size = xsnprintf(hdr, sizeof hdr,
1070 			    "%s: %s", data->inputprompt, data->inputstr);
1071 		}
1072 		screen_write_cursormove(ctx, 0, last);
1073 		screen_write_puts(ctx, &gc, "%s", hdr);
1074 	} else
1075 		size = 0;
1076 
1077 	screen_write_cursormove(ctx, xoff, py);
1078 	screen_write_copy(ctx, data->backing, xoff,
1079 	    (screen_hsize(data->backing) - data->oy) + py,
1080 	    screen_size_x(s) - size, 1);
1081 
1082 	if (py == data->cy && data->cx == screen_size_x(s)) {
1083 		memcpy(&gc, &grid_default_cell, sizeof gc);
1084 		screen_write_cursormove(ctx, screen_size_x(s) - 1, py);
1085 		screen_write_putc(ctx, &gc, '$');
1086 	}
1087 }
1088 
1089 void
1090 window_copy_write_lines(
1091     struct window_pane *wp, struct screen_write_ctx *ctx, u_int py, u_int ny)
1092 {
1093 	u_int	yy;
1094 
1095 	for (yy = py; yy < py + ny; yy++)
1096 		window_copy_write_line(wp, ctx, py);
1097 }
1098 
1099 void
1100 window_copy_redraw_lines(struct window_pane *wp, u_int py, u_int ny)
1101 {
1102 	struct window_copy_mode_data	*data = wp->modedata;
1103 	struct screen_write_ctx	 	 ctx;
1104 	u_int				 i;
1105 
1106 	screen_write_start(&ctx, wp, NULL);
1107 	for (i = py; i < py + ny; i++)
1108 		window_copy_write_line(wp, &ctx, i);
1109 	screen_write_cursormove(&ctx, data->cx, data->cy);
1110 	screen_write_stop(&ctx);
1111 }
1112 
1113 void
1114 window_copy_redraw_screen(struct window_pane *wp)
1115 {
1116 	struct window_copy_mode_data	*data = wp->modedata;
1117 
1118 	window_copy_redraw_lines(wp, 0, screen_size_y(&data->screen));
1119 }
1120 
1121 void
1122 window_copy_update_cursor(struct window_pane *wp, u_int cx, u_int cy)
1123 {
1124 	struct window_copy_mode_data	*data = wp->modedata;
1125 	struct screen			*s = &data->screen;
1126 	struct screen_write_ctx		 ctx;
1127 	u_int				 old_cx, old_cy;
1128 
1129 	old_cx = data->cx; old_cy = data->cy;
1130 	data->cx = cx; data->cy = cy;
1131 	if (old_cx == screen_size_x(s))
1132 		window_copy_redraw_lines(wp, old_cy, 1);
1133 	if (data->cx == screen_size_x(s))
1134 		window_copy_redraw_lines(wp, data->cy, 1);
1135 	else {
1136 		screen_write_start(&ctx, wp, NULL);
1137 		screen_write_cursormove(&ctx, data->cx, data->cy);
1138 		screen_write_stop(&ctx);
1139 	}
1140 }
1141 
1142 void
1143 window_copy_start_selection(struct window_pane *wp)
1144 {
1145 	struct window_copy_mode_data	*data = wp->modedata;
1146 	struct screen			*s = &data->screen;
1147 
1148 	data->selx = data->cx;
1149 	data->sely = screen_hsize(data->backing) + data->cy - data->oy;
1150 
1151 	s->sel.flag = 1;
1152 	window_copy_update_selection(wp);
1153 }
1154 
1155 int
1156 window_copy_update_selection(struct window_pane *wp)
1157 {
1158 	struct window_copy_mode_data	*data = wp->modedata;
1159 	struct screen			*s = &data->screen;
1160 	struct options			*oo = &wp->window->options;
1161 	struct grid_cell		 gc;
1162 	u_int				 sx, sy, ty, cy;
1163 
1164 	if (!s->sel.flag)
1165 		return (0);
1166 
1167 	/* Set colours. */
1168 	memcpy(&gc, &grid_default_cell, sizeof gc);
1169 	colour_set_fg(&gc, options_get_number(oo, "mode-fg"));
1170 	colour_set_bg(&gc, options_get_number(oo, "mode-bg"));
1171 	gc.attr |= options_get_number(oo, "mode-attr");
1172 
1173 	/* Find top of screen. */
1174 	ty = screen_hsize(data->backing) - data->oy;
1175 
1176 	/* Adjust the selection. */
1177 	sx = data->selx;
1178 	sy = data->sely;
1179 	if (sy < ty) {					/* above screen */
1180 		if (!data->rectflag)
1181 			sx = 0;
1182 		sy = 0;
1183 	} else if (sy > ty + screen_size_y(s) - 1) {	/* below screen */
1184 		if (!data->rectflag)
1185 			sx = screen_size_x(s) - 1;
1186 		sy = screen_size_y(s) - 1;
1187 	} else
1188 		sy -= ty;
1189 	sy = screen_hsize(s) + sy;
1190 
1191 	screen_set_selection(s,
1192 	    sx, sy, data->cx, screen_hsize(s) + data->cy, data->rectflag, &gc);
1193 
1194 	if (data->rectflag) {
1195 		/*
1196 		 * Can't rely on the caller to redraw the right lines for
1197 		 * rectangle selection - find the highest line and the number
1198 		 * of lines, and redraw just past that in both directions
1199 		 */
1200 		cy = data->cy;
1201 		if (sy < cy)
1202 			window_copy_redraw_lines(wp, sy, cy - sy + 1);
1203 		else
1204 			window_copy_redraw_lines(wp, cy, sy - cy + 1);
1205 	}
1206 
1207 	return (1);
1208 }
1209 
1210 void
1211 window_copy_copy_selection(struct window_pane *wp, struct session *sess)
1212 {
1213 	struct window_copy_mode_data	*data = wp->modedata;
1214 	struct screen			*s = &data->screen;
1215 	char				*buf;
1216 	size_t				 off;
1217 	u_int				 i, xx, yy, sx, sy, ex, ey, limit;
1218 	u_int				 firstsx, lastex, restex, restsx;
1219 
1220 	if (!s->sel.flag)
1221 		return;
1222 
1223 	buf = xmalloc(1);
1224 	off = 0;
1225 
1226 	*buf = '\0';
1227 
1228 	/*
1229 	 * The selection extends from selx,sely to (adjusted) cx,cy on
1230 	 * the base screen.
1231 	 */
1232 
1233 	/* Find start and end. */
1234 	xx = data->cx;
1235 	yy = screen_hsize(data->backing) + data->cy - data->oy;
1236 	if (yy < data->sely || (yy == data->sely && xx < data->selx)) {
1237 		sx = xx; sy = yy;
1238 		ex = data->selx; ey = data->sely;
1239 	} else {
1240 		sx = data->selx; sy = data->sely;
1241 		ex = xx; ey = yy;
1242 	}
1243 
1244 	/* Trim ex to end of line. */
1245 	xx = window_copy_find_length(wp, ey);
1246 	if (ex > xx)
1247 		ex = xx;
1248 
1249 	/*
1250 	 * Deal with rectangle-copy if necessary; four situations: start of
1251 	 * first line (firstsx), end of last line (lastex), start (restsx) and
1252 	 * end (restex) of all other lines.
1253 	 */
1254 	xx = screen_size_x(s);
1255 	if (data->rectflag) {
1256 		/*
1257 		 * Need to ignore the column with the cursor in it, which for
1258 		 * rectangular copy means knowing which side the cursor is on.
1259 		 */
1260 		if (data->selx < data->cx) {
1261 			/* Selection start is on the left. */
1262 			lastex = data->cx;
1263 			restex = data->cx;
1264 			firstsx = data->selx;
1265 			restsx = data->selx;
1266 		} else {
1267 			/* Cursor is on the left. */
1268 			lastex = data->selx + 1;
1269 			restex = data->selx + 1;
1270 			firstsx = data->cx;
1271 			restsx = data->cx;
1272 		}
1273 	} else {
1274 		/*
1275 		 * Like emacs, keep the top-left-most character, and drop the
1276 		 * bottom-right-most, regardless of copy direction.
1277 		 */
1278 		lastex = ex;
1279 		restex = xx;
1280 		firstsx = sx;
1281 		restsx = 0;
1282 	}
1283 
1284 	/* Copy the lines. */
1285 	if (sy == ey)
1286 		window_copy_copy_line(wp, &buf, &off, sy, firstsx, lastex);
1287 	else {
1288 		window_copy_copy_line(wp, &buf, &off, sy, firstsx, restex);
1289 		if (ey - sy > 1) {
1290 			for (i = sy + 1; i < ey; i++) {
1291 				window_copy_copy_line(
1292 				    wp, &buf, &off, i, restsx, restex);
1293 			}
1294 		}
1295 		window_copy_copy_line(wp, &buf, &off, ey, restsx, lastex);
1296 	}
1297 
1298 	/* Don't bother if no data. */
1299 	if (off == 0) {
1300 		xfree(buf);
1301 		return;
1302 	}
1303 	off--;	/* remove final \n */
1304 
1305 	/* Add the buffer to the stack. */
1306 	limit = options_get_number(&sess->options, "buffer-limit");
1307 	paste_add(&sess->buffers, buf, off, limit);
1308 }
1309 
1310 void
1311 window_copy_copy_line(struct window_pane *wp,
1312     char **buf, size_t *off, u_int sy, u_int sx, u_int ex)
1313 {
1314 	struct window_copy_mode_data	*data = wp->modedata;
1315 	struct grid			*gd = data->backing->grid;
1316 	const struct grid_cell		*gc;
1317 	const struct grid_utf8		*gu;
1318 	struct grid_line		*gl;
1319 	u_int				 i, xx, wrapped = 0;
1320 	size_t				 size;
1321 
1322 	if (sx > ex)
1323 		return;
1324 
1325 	/*
1326 	 * Work out if the line was wrapped at the screen edge and all of it is
1327 	 * on screen.
1328 	 */
1329 	gl = &gd->linedata[sy];
1330 	if (gl->flags & GRID_LINE_WRAPPED && gl->cellsize <= gd->sx)
1331 		wrapped = 1;
1332 
1333 	/* If the line was wrapped, don't strip spaces (use the full length). */
1334 	if (wrapped)
1335 		xx = gl->cellsize;
1336 	else
1337 		xx = window_copy_find_length(wp, sy);
1338 	if (ex > xx)
1339 		ex = xx;
1340 	if (sx > xx)
1341 		sx = xx;
1342 
1343 	if (sx < ex) {
1344 		for (i = sx; i < ex; i++) {
1345 			gc = grid_peek_cell(gd, i, sy);
1346 			if (gc->flags & GRID_FLAG_PADDING)
1347 				continue;
1348 			if (!(gc->flags & GRID_FLAG_UTF8)) {
1349 				*buf = xrealloc(*buf, 1, (*off) + 1);
1350 				(*buf)[(*off)++] = gc->data;
1351 			} else {
1352 				gu = grid_peek_utf8(gd, i, sy);
1353 				size = grid_utf8_size(gu);
1354 				*buf = xrealloc(*buf, 1, (*off) + size);
1355 				*off += grid_utf8_copy(gu, *buf + *off, size);
1356 			}
1357 		}
1358 	}
1359 
1360 	/* Only add a newline if the line wasn't wrapped. */
1361 	if (!wrapped || ex != xx) {
1362 		*buf = xrealloc(*buf, 1, (*off) + 1);
1363 		(*buf)[(*off)++] = '\n';
1364 	}
1365 }
1366 
1367 void
1368 window_copy_clear_selection(struct window_pane *wp)
1369 {
1370 	struct window_copy_mode_data   *data = wp->modedata;
1371 	u_int				px, py;
1372 
1373 	screen_clear_selection(&data->screen);
1374 
1375 	py = screen_hsize(data->backing) + data->cy - data->oy;
1376 	px = window_copy_find_length(wp, py);
1377 	if (data->cx > px)
1378 		window_copy_update_cursor(wp, px, data->cy);
1379 }
1380 
1381 int
1382 window_copy_in_set(struct window_pane *wp, u_int px, u_int py, const char *set)
1383 {
1384 	struct window_copy_mode_data	*data = wp->modedata;
1385 	const struct grid_cell		*gc;
1386 
1387 	gc = grid_peek_cell(data->backing->grid, px, py);
1388 	if (gc->flags & (GRID_FLAG_PADDING|GRID_FLAG_UTF8))
1389 		return (0);
1390 	if (gc->data == 0x00 || gc->data == 0x7f)
1391 		return (0);
1392 	return (strchr(set, gc->data) != NULL);
1393 }
1394 
1395 u_int
1396 window_copy_find_length(struct window_pane *wp, u_int py)
1397 {
1398 	struct window_copy_mode_data	*data = wp->modedata;
1399 	struct screen			*s = data->backing;
1400 	const struct grid_cell		*gc;
1401 	u_int				 px;
1402 
1403 	/*
1404 	 * If the pane has been resized, its grid can contain old overlong
1405 	 * lines. grid_peek_cell does not allow accessing cells beyond the
1406 	 * width of the grid, and screen_write_copy treats them as spaces, so
1407 	 * ignore them here too.
1408 	 */
1409 	px = s->grid->linedata[py].cellsize;
1410 	if (px > screen_size_x(s))
1411 		px = screen_size_x(s);
1412 	while (px > 0) {
1413 		gc = grid_peek_cell(s->grid, px - 1, py);
1414 		if (gc->flags & GRID_FLAG_UTF8)
1415 			break;
1416 		if (gc->data != ' ')
1417 			break;
1418 		px--;
1419 	}
1420 	return (px);
1421 }
1422 
1423 void
1424 window_copy_cursor_start_of_line(struct window_pane *wp)
1425 {
1426 	struct window_copy_mode_data	*data = wp->modedata;
1427 	struct screen			*back_s = data->backing;
1428 	struct grid			*gd = back_s->grid;
1429 	u_int				 py;
1430 
1431 	if (data->cx == 0) {
1432 		py = screen_hsize(back_s) + data->cy - data->oy;
1433 		while (py > 0 && gd->linedata[py-1].flags & GRID_LINE_WRAPPED) {
1434 			window_copy_cursor_up(wp, 0);
1435 			py = screen_hsize(back_s) + data->cy - data->oy;
1436 		}
1437 	}
1438 	window_copy_update_cursor(wp, 0, data->cy);
1439 	if (window_copy_update_selection(wp))
1440 		window_copy_redraw_lines(wp, data->cy, 1);
1441 }
1442 
1443 void
1444 window_copy_cursor_back_to_indentation(struct window_pane *wp)
1445 {
1446 	struct window_copy_mode_data	*data = wp->modedata;
1447 	u_int				 px, py, xx;
1448 	const struct grid_cell		*gc;
1449 
1450 	px = 0;
1451 	py = screen_hsize(data->backing) + data->cy - data->oy;
1452 	xx = window_copy_find_length(wp, py);
1453 
1454 	while (px < xx) {
1455 		gc = grid_peek_cell(data->backing->grid, px, py);
1456 		if (gc->flags & GRID_FLAG_UTF8)
1457 			break;
1458 		if (gc->data != ' ')
1459 			break;
1460 		px++;
1461 	}
1462 
1463 	window_copy_update_cursor(wp, px, data->cy);
1464 	if (window_copy_update_selection(wp))
1465 		window_copy_redraw_lines(wp, data->cy, 1);
1466 }
1467 
1468 void
1469 window_copy_cursor_end_of_line(struct window_pane *wp)
1470 {
1471 	struct window_copy_mode_data	*data = wp->modedata;
1472 	struct screen			*back_s = data->backing;
1473 	struct grid			*gd = back_s->grid;
1474 	u_int				 px, py;
1475 
1476 	py = screen_hsize(back_s) + data->cy - data->oy;
1477 	px = window_copy_find_length(wp, py);
1478 
1479 	if (data->cx == px) {
1480 		if (data->screen.sel.flag && data->rectflag)
1481 			px = screen_size_x(back_s);
1482 		if (gd->linedata[py].flags & GRID_LINE_WRAPPED) {
1483 			while (py < gd->sy + gd->hsize &&
1484 			    gd->linedata[py].flags & GRID_LINE_WRAPPED) {
1485 				window_copy_cursor_down(wp, 0);
1486 				py = screen_hsize(back_s)
1487 				     + data->cy - data->oy;
1488 			}
1489 			px = window_copy_find_length(wp, py);
1490 		}
1491 	}
1492 	window_copy_update_cursor(wp, px, data->cy);
1493 
1494 	if (window_copy_update_selection(wp))
1495 		window_copy_redraw_lines(wp, data->cy, 1);
1496 }
1497 
1498 void
1499 window_copy_cursor_left(struct window_pane *wp)
1500 {
1501 	struct window_copy_mode_data	*data = wp->modedata;
1502 
1503 	if (data->cx == 0) {
1504 		window_copy_cursor_up(wp, 0);
1505 		window_copy_cursor_end_of_line(wp);
1506 	} else {
1507 		window_copy_update_cursor(wp, data->cx - 1, data->cy);
1508 		if (window_copy_update_selection(wp))
1509 			window_copy_redraw_lines(wp, data->cy, 1);
1510 	}
1511 }
1512 
1513 void
1514 window_copy_cursor_right(struct window_pane *wp)
1515 {
1516 	struct window_copy_mode_data	*data = wp->modedata;
1517 	u_int				 px, py;
1518 
1519 	if (data->screen.sel.flag && data->rectflag)
1520 		px = screen_size_x(&data->screen);
1521 	else {
1522 		py = screen_hsize(data->backing) + data->cy - data->oy;
1523 		px = window_copy_find_length(wp, py);
1524 	}
1525 
1526 	if (data->cx >= px) {
1527 		window_copy_cursor_start_of_line(wp);
1528 		window_copy_cursor_down(wp, 0);
1529 	} else {
1530 		window_copy_update_cursor(wp, data->cx + 1, data->cy);
1531 		if (window_copy_update_selection(wp))
1532 			window_copy_redraw_lines(wp, data->cy, 1);
1533 	}
1534 }
1535 
1536 void
1537 window_copy_cursor_up(struct window_pane *wp, int scroll_only)
1538 {
1539 	struct window_copy_mode_data	*data = wp->modedata;
1540 	struct screen			*s = &data->screen;
1541 	u_int				 ox, oy, px, py;
1542 
1543 	oy = screen_hsize(data->backing) + data->cy - data->oy;
1544 	ox = window_copy_find_length(wp, oy);
1545 	if (ox != 0) {
1546 		data->lastcx = data->cx;
1547 		data->lastsx = ox;
1548 	}
1549 
1550 	data->cx = data->lastcx;
1551 	if (scroll_only || data->cy == 0) {
1552 		window_copy_scroll_down(wp, 1);
1553 		if (scroll_only) {
1554 			if (data->cy == screen_size_y(s) - 1)
1555 				window_copy_redraw_lines(wp, data->cy, 1);
1556 			else
1557 				window_copy_redraw_lines(wp, data->cy, 2);
1558 		}
1559 	} else {
1560 		window_copy_update_cursor(wp, data->cx, data->cy - 1);
1561 		if (window_copy_update_selection(wp)) {
1562 			if (data->cy == screen_size_y(s) - 1)
1563 				window_copy_redraw_lines(wp, data->cy, 1);
1564 			else
1565 				window_copy_redraw_lines(wp, data->cy, 2);
1566 		}
1567 	}
1568 
1569 	if (!data->screen.sel.flag || !data->rectflag) {
1570 		py = screen_hsize(data->backing) + data->cy - data->oy;
1571 		px = window_copy_find_length(wp, py);
1572 		if ((data->cx >= data->lastsx && data->cx != px) ||
1573 		    data->cx > px)
1574 			window_copy_cursor_end_of_line(wp);
1575 	}
1576 }
1577 
1578 void
1579 window_copy_cursor_down(struct window_pane *wp, int scroll_only)
1580 {
1581 	struct window_copy_mode_data	*data = wp->modedata;
1582 	struct screen			*s = &data->screen;
1583 	u_int				 ox, oy, px, py;
1584 
1585 	oy = screen_hsize(data->backing) + data->cy - data->oy;
1586 	ox = window_copy_find_length(wp, oy);
1587 	if (ox != 0) {
1588 		data->lastcx = data->cx;
1589 		data->lastsx = ox;
1590 	}
1591 
1592 	data->cx = data->lastcx;
1593 	if (scroll_only || data->cy == screen_size_y(s) - 1) {
1594 		window_copy_scroll_up(wp, 1);
1595 		if (scroll_only && data->cy > 0)
1596 			window_copy_redraw_lines(wp, data->cy - 1, 2);
1597 	} else {
1598 		window_copy_update_cursor(wp, data->cx, data->cy + 1);
1599 		if (window_copy_update_selection(wp))
1600 			window_copy_redraw_lines(wp, data->cy - 1, 2);
1601 	}
1602 
1603 	if (!data->screen.sel.flag || !data->rectflag) {
1604 		py = screen_hsize(data->backing) + data->cy - data->oy;
1605 		px = window_copy_find_length(wp, py);
1606 		if ((data->cx >= data->lastsx && data->cx != px) ||
1607 		    data->cx > px)
1608 			window_copy_cursor_end_of_line(wp);
1609 	}
1610 }
1611 
1612 void
1613 window_copy_cursor_jump(struct window_pane *wp)
1614 {
1615 	struct window_copy_mode_data	*data = wp->modedata;
1616 	struct screen			*back_s = data->backing;
1617 	const struct grid_cell		*gc;
1618 	uint				 px, py, xx;
1619 
1620 	px = data->cx + 1;
1621 	py = screen_hsize(back_s) + data->cy - data->oy;
1622 	xx = window_copy_find_length(wp, py);
1623 
1624 	while (px < xx) {
1625 		gc = grid_peek_cell(back_s->grid, px, py);
1626 		if ((gc->flags & (GRID_FLAG_PADDING|GRID_FLAG_UTF8)) == 0
1627 		    && gc->data == data->jumpchar) {
1628 
1629 			window_copy_update_cursor(wp, px, data->cy);
1630 			if (window_copy_update_selection(wp))
1631 				window_copy_redraw_lines(wp, data->cy, 1);
1632 			return;
1633 		}
1634 		px++;
1635 	}
1636 }
1637 
1638 void
1639 window_copy_cursor_jump_back(struct window_pane *wp)
1640 {
1641 	struct window_copy_mode_data	*data = wp->modedata;
1642 	struct screen			*back_s = data->backing;
1643 	const struct grid_cell		*gc;
1644 	uint				 px, py;
1645 
1646 	px = data->cx;
1647 	py = screen_hsize(back_s) + data->cy - data->oy;
1648 
1649 	if (px > 0)
1650 		px--;
1651 
1652 	for (;;) {
1653 		gc = grid_peek_cell(back_s->grid, px, py);
1654 		if ((gc->flags & (GRID_FLAG_PADDING|GRID_FLAG_UTF8)) == 0
1655 		    && gc->data == data->jumpchar) {
1656 
1657 			window_copy_update_cursor(wp, px, data->cy);
1658 			if (window_copy_update_selection(wp))
1659 				window_copy_redraw_lines(wp, data->cy, 1);
1660 			return;
1661 		}
1662 		if (px == 0)
1663 			break;
1664 		px--;
1665 	}
1666 }
1667 
1668 void
1669 window_copy_cursor_next_word(struct window_pane *wp, const char *separators)
1670 {
1671 	struct window_copy_mode_data	*data = wp->modedata;
1672 	struct screen			*back_s = data->backing;
1673 	u_int				 px, py, xx, yy;
1674 	int				 expected = 0;
1675 
1676 	px = data->cx;
1677 	py = screen_hsize(back_s) + data->cy - data->oy;
1678 	xx = window_copy_find_length(wp, py);
1679 	yy = screen_hsize(back_s) + screen_size_y(back_s) - 1;
1680 
1681 	/*
1682 	 * First skip past any nonword characters and then any word characters.
1683 	 *
1684 	 * expected is initially set to 0 for the former and then 1 for the
1685 	 * latter.
1686 	 */
1687 	do {
1688 		while (px > xx ||
1689 		    window_copy_in_set(wp, px, py, separators) == expected) {
1690 			/* Move down if we're past the end of the line. */
1691 			if (px > xx) {
1692 				if (py == yy)
1693 					return;
1694 				window_copy_cursor_down(wp, 0);
1695 				px = 0;
1696 
1697 				py = screen_hsize(back_s) + data->cy - data->oy;
1698 				xx = window_copy_find_length(wp, py);
1699 			} else
1700 				px++;
1701 		}
1702 		expected = !expected;
1703 	} while (expected == 1);
1704 
1705 	window_copy_update_cursor(wp, px, data->cy);
1706 	if (window_copy_update_selection(wp))
1707 		window_copy_redraw_lines(wp, data->cy, 1);
1708 }
1709 
1710 void
1711 window_copy_cursor_next_word_end(struct window_pane *wp, const char *separators)
1712 {
1713 	struct window_copy_mode_data	*data = wp->modedata;
1714 	struct screen			*back_s = data->backing;
1715 	u_int				 px, py, xx, yy;
1716 	int				 expected = 1;
1717 
1718 	px = data->cx;
1719 	py = screen_hsize(back_s) + data->cy - data->oy;
1720 	xx = window_copy_find_length(wp, py);
1721 	yy = screen_hsize(back_s) + screen_size_y(back_s) - 1;
1722 
1723 	/*
1724 	 * First skip past any word characters, then any nonword characters.
1725 	 *
1726 	 * expected is initially set to 1 for the former and then 0 for the
1727 	 * latter.
1728 	 */
1729 	do {
1730 		while (px > xx ||
1731 		    window_copy_in_set(wp, px, py, separators) == expected) {
1732 			/* Move down if we're past the end of the line. */
1733 			if (px > xx) {
1734 				if (py == yy)
1735 					return;
1736 				window_copy_cursor_down(wp, 0);
1737 				px = 0;
1738 
1739 				py = screen_hsize(back_s) + data->cy - data->oy;
1740 				xx = window_copy_find_length(wp, py);
1741 			} else
1742 				px++;
1743 		}
1744 		expected = !expected;
1745 	} while (expected == 0);
1746 
1747 	window_copy_update_cursor(wp, px, data->cy);
1748 	if (window_copy_update_selection(wp))
1749 		window_copy_redraw_lines(wp, data->cy, 1);
1750 }
1751 
1752 /* Move to the previous place where a word begins. */
1753 void
1754 window_copy_cursor_previous_word(struct window_pane *wp, const char *separators)
1755 {
1756 	struct window_copy_mode_data	*data = wp->modedata;
1757 	u_int				 px, py;
1758 
1759 	px = data->cx;
1760 	py = screen_hsize(data->backing) + data->cy - data->oy;
1761 
1762 	/* Move back to the previous word character. */
1763 	for (;;) {
1764 		if (px > 0) {
1765 			px--;
1766 			if (!window_copy_in_set(wp, px, py, separators))
1767 				break;
1768 		} else {
1769 			if (data->cy == 0 &&
1770 			    (screen_hsize(data->backing) == 0 ||
1771 			    data->oy >= screen_hsize(data->backing) - 1))
1772 				goto out;
1773 			window_copy_cursor_up(wp, 0);
1774 
1775 			py = screen_hsize(data->backing) + data->cy - data->oy;
1776 			px = window_copy_find_length(wp, py);
1777 		}
1778 	}
1779 
1780 	/* Move back to the beginning of this word. */
1781 	while (px > 0 && !window_copy_in_set(wp, px - 1, py, separators))
1782 		px--;
1783 
1784 out:
1785 	window_copy_update_cursor(wp, px, data->cy);
1786 	if (window_copy_update_selection(wp))
1787 		window_copy_redraw_lines(wp, data->cy, 1);
1788 }
1789 
1790 void
1791 window_copy_scroll_up(struct window_pane *wp, u_int ny)
1792 {
1793 	struct window_copy_mode_data	*data = wp->modedata;
1794 	struct screen			*s = &data->screen;
1795 	struct screen_write_ctx		 ctx;
1796 
1797 	if (data->oy < ny)
1798 		ny = data->oy;
1799 	if (ny == 0)
1800 		return;
1801 	data->oy -= ny;
1802 
1803 	screen_write_start(&ctx, wp, NULL);
1804 	screen_write_cursormove(&ctx, 0, 0);
1805 	screen_write_deleteline(&ctx, ny);
1806 	window_copy_write_lines(wp, &ctx, screen_size_y(s) - ny, ny);
1807 	window_copy_write_line(wp, &ctx, 0);
1808 	if (screen_size_y(s) > 1)
1809 		window_copy_write_line(wp, &ctx, 1);
1810 	if (screen_size_y(s) > 3)
1811 		window_copy_write_line(wp, &ctx, screen_size_y(s) - 2);
1812 	if (s->sel.flag && screen_size_y(s) > ny) {
1813 		window_copy_update_selection(wp);
1814 		window_copy_write_line(wp, &ctx, screen_size_y(s) - ny - 1);
1815 	}
1816 	screen_write_cursormove(&ctx, data->cx, data->cy);
1817 	window_copy_update_selection(wp);
1818 	screen_write_stop(&ctx);
1819 }
1820 
1821 void
1822 window_copy_scroll_down(struct window_pane *wp, u_int ny)
1823 {
1824 	struct window_copy_mode_data	*data = wp->modedata;
1825 	struct screen			*s = &data->screen;
1826 	struct screen_write_ctx		 ctx;
1827 
1828 	if (ny > screen_hsize(data->backing))
1829 		return;
1830 
1831 	if (data->oy > screen_hsize(data->backing) - ny)
1832 		ny = screen_hsize(data->backing) - data->oy;
1833 	if (ny == 0)
1834 		return;
1835 	data->oy += ny;
1836 
1837 	screen_write_start(&ctx, wp, NULL);
1838 	screen_write_cursormove(&ctx, 0, 0);
1839 	screen_write_insertline(&ctx, ny);
1840 	window_copy_write_lines(wp, &ctx, 0, ny);
1841 	if (s->sel.flag && screen_size_y(s) > ny) {
1842 		window_copy_update_selection(wp);
1843 		window_copy_write_line(wp, &ctx, ny);
1844 	} else if (ny == 1) /* nuke position */
1845 		window_copy_write_line(wp, &ctx, 1);
1846 	screen_write_cursormove(&ctx, data->cx, data->cy);
1847 	window_copy_update_selection(wp);
1848 	screen_write_stop(&ctx);
1849 }
1850 
1851 void
1852 window_copy_rectangle_toggle(struct window_pane *wp)
1853 {
1854 	struct window_copy_mode_data	*data = wp->modedata;
1855 	u_int				 px, py;
1856 
1857 	data->rectflag = !data->rectflag;
1858 
1859 	py = screen_hsize(data->backing) + data->cy - data->oy;
1860 	px = window_copy_find_length(wp, py);
1861 	if (data->cx > px)
1862 		window_copy_update_cursor(wp, px, data->cy);
1863 
1864 	window_copy_update_selection(wp);
1865 	window_copy_redraw_screen(wp);
1866 }
1867