xref: /openbsd-src/usr.bin/tmux/grid.c (revision 25c4e8bd056e974b28f4a0ffd39d76c190a56013)
1 /* $OpenBSD: grid.c,v 1.126 2022/07/06 07:36:36 nicm Exp $ */
2 
3 /*
4  * Copyright (c) 2008 Nicholas Marriott <nicholas.marriott@gmail.com>
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 /*
27  * Grid data. This is the basic data structure that represents what is shown on
28  * screen.
29  *
30  * A grid is a grid of cells (struct grid_cell). Lines are not allocated until
31  * cells in that line are written to. The grid is split into history and
32  * viewable data with the history starting at row (line) 0 and extending to
33  * (hsize - 1); from hsize to hsize + (sy - 1) is the viewable data. All
34  * functions in this file work on absolute coordinates, grid-view.c has
35  * functions which work on the screen data.
36  */
37 
38 /* Default grid cell data. */
39 const struct grid_cell grid_default_cell = {
40 	{ { ' ' }, 0, 1, 1 }, 0, 0, 8, 8, 0, 0
41 };
42 
43 /*
44  * Padding grid cell data. Padding cells are the only zero width cell that
45  * appears in the grid - because of this, they are always extended cells.
46  */
47 static const struct grid_cell grid_padding_cell = {
48 	{ { '!' }, 0, 0, 0 }, 0, GRID_FLAG_PADDING, 8, 8, 0, 0
49 };
50 
51 /* Cleared grid cell data. */
52 static const struct grid_cell grid_cleared_cell = {
53 	{ { ' ' }, 0, 1, 1 }, 0, GRID_FLAG_CLEARED, 8, 8, 0, 0
54 };
55 static const struct grid_cell_entry grid_cleared_entry = {
56 	GRID_FLAG_CLEARED, { .data = { 0, 8, 8, ' ' } }
57 };
58 
59 /* Store cell in entry. */
60 static void
61 grid_store_cell(struct grid_cell_entry *gce, const struct grid_cell *gc,
62     u_char c)
63 {
64 	gce->flags = (gc->flags & ~GRID_FLAG_CLEARED);
65 
66 	gce->data.fg = gc->fg & 0xff;
67 	if (gc->fg & COLOUR_FLAG_256)
68 		gce->flags |= GRID_FLAG_FG256;
69 
70 	gce->data.bg = gc->bg & 0xff;
71 	if (gc->bg & COLOUR_FLAG_256)
72 		gce->flags |= GRID_FLAG_BG256;
73 
74 	gce->data.attr = gc->attr;
75 	gce->data.data = c;
76 }
77 
78 /* Check if a cell should be an extended cell. */
79 static int
80 grid_need_extended_cell(const struct grid_cell_entry *gce,
81     const struct grid_cell *gc)
82 {
83 	if (gce->flags & GRID_FLAG_EXTENDED)
84 		return (1);
85 	if (gc->attr > 0xff)
86 		return (1);
87 	if (gc->data.size != 1 || gc->data.width != 1)
88 		return (1);
89 	if ((gc->fg & COLOUR_FLAG_RGB) || (gc->bg & COLOUR_FLAG_RGB))
90 		return (1);
91 	if (gc->us != 0) /* only supports 256 or RGB */
92 		return (1);
93 	if (gc->link != 0)
94 		return (1);
95 	return (0);
96 }
97 
98 /* Get an extended cell. */
99 static void
100 grid_get_extended_cell(struct grid_line *gl, struct grid_cell_entry *gce,
101     int flags)
102 {
103 	u_int at = gl->extdsize + 1;
104 
105 	gl->extddata = xreallocarray(gl->extddata, at, sizeof *gl->extddata);
106 	gl->extdsize = at;
107 
108 	gce->offset = at - 1;
109 	gce->flags = (flags | GRID_FLAG_EXTENDED);
110 }
111 
112 /* Set cell as extended. */
113 static struct grid_extd_entry *
114 grid_extended_cell(struct grid_line *gl, struct grid_cell_entry *gce,
115     const struct grid_cell *gc)
116 {
117 	struct grid_extd_entry	*gee;
118 	int			 flags = (gc->flags & ~GRID_FLAG_CLEARED);
119 	utf8_char		 uc;
120 
121 	if (~gce->flags & GRID_FLAG_EXTENDED)
122 		grid_get_extended_cell(gl, gce, flags);
123 	else if (gce->offset >= gl->extdsize)
124 		fatalx("offset too big");
125 	gl->flags |= GRID_LINE_EXTENDED;
126 
127 	utf8_from_data(&gc->data, &uc);
128 
129 	gee = &gl->extddata[gce->offset];
130 	gee->data = uc;
131 	gee->attr = gc->attr;
132 	gee->flags = flags;
133 	gee->fg = gc->fg;
134 	gee->bg = gc->bg;
135 	gee->us = gc->us;
136 	gee->link = gc->link;
137 	return (gee);
138 }
139 
140 /* Free up unused extended cells. */
141 static void
142 grid_compact_line(struct grid_line *gl)
143 {
144 	int			 new_extdsize = 0;
145 	struct grid_extd_entry	*new_extddata;
146 	struct grid_cell_entry	*gce;
147 	struct grid_extd_entry	*gee;
148 	u_int			 px, idx;
149 
150 	if (gl->extdsize == 0)
151 		return;
152 
153 	for (px = 0; px < gl->cellsize; px++) {
154 		gce = &gl->celldata[px];
155 		if (gce->flags & GRID_FLAG_EXTENDED)
156 			new_extdsize++;
157 	}
158 
159 	if (new_extdsize == 0) {
160 		free(gl->extddata);
161 		gl->extddata = NULL;
162 		gl->extdsize = 0;
163 		return;
164 	}
165 	new_extddata = xreallocarray(NULL, new_extdsize, sizeof *gl->extddata);
166 
167 	idx = 0;
168 	for (px = 0; px < gl->cellsize; px++) {
169 		gce = &gl->celldata[px];
170 		if (gce->flags & GRID_FLAG_EXTENDED) {
171 			gee = &gl->extddata[gce->offset];
172 			memcpy(&new_extddata[idx], gee, sizeof *gee);
173 			gce->offset = idx++;
174 		}
175 	}
176 
177 	free(gl->extddata);
178 	gl->extddata = new_extddata;
179 	gl->extdsize = new_extdsize;
180 }
181 
182 /* Get line data. */
183 struct grid_line *
184 grid_get_line(struct grid *gd, u_int line)
185 {
186 	return (&gd->linedata[line]);
187 }
188 
189 /* Adjust number of lines. */
190 void
191 grid_adjust_lines(struct grid *gd, u_int lines)
192 {
193 	gd->linedata = xreallocarray(gd->linedata, lines, sizeof *gd->linedata);
194 }
195 
196 /* Copy default into a cell. */
197 static void
198 grid_clear_cell(struct grid *gd, u_int px, u_int py, u_int bg)
199 {
200 	struct grid_line	*gl = &gd->linedata[py];
201 	struct grid_cell_entry	*gce = &gl->celldata[px];
202 	struct grid_extd_entry	*gee;
203 
204 	memcpy(gce, &grid_cleared_entry, sizeof *gce);
205 	if (bg != 8) {
206 		if (bg & COLOUR_FLAG_RGB) {
207 			grid_get_extended_cell(gl, gce, gce->flags);
208 			gee = grid_extended_cell(gl, gce, &grid_cleared_cell);
209 			gee->bg = bg;
210 		} else {
211 			if (bg & COLOUR_FLAG_256)
212 				gce->flags |= GRID_FLAG_BG256;
213 			gce->data.bg = bg;
214 		}
215 	}
216 }
217 
218 /* Check grid y position. */
219 static int
220 grid_check_y(struct grid *gd, const char *from, u_int py)
221 {
222 	if (py >= gd->hsize + gd->sy) {
223 		log_debug("%s: y out of range: %u", from, py);
224 		return (-1);
225 	}
226 	return (0);
227 }
228 
229 /* Check if two styles are (visibly) the same. */
230 int
231 grid_cells_look_equal(const struct grid_cell *gc1, const struct grid_cell *gc2)
232 {
233 	if (gc1->fg != gc2->fg || gc1->bg != gc2->bg)
234 		return (0);
235 	if (gc1->attr != gc2->attr || gc1->flags != gc2->flags)
236 		return (0);
237 	if (gc1->link != gc2->link)
238 		return (0);
239 	return (1);
240 }
241 
242 /* Compare grid cells. Return 1 if equal, 0 if not. */
243 int
244 grid_cells_equal(const struct grid_cell *gc1, const struct grid_cell *gc2)
245 {
246 	if (!grid_cells_look_equal(gc1, gc2))
247 		return (0);
248 	if (gc1->data.width != gc2->data.width)
249 		return (0);
250 	if (gc1->data.size != gc2->data.size)
251 		return (0);
252 	return (memcmp(gc1->data.data, gc2->data.data, gc1->data.size) == 0);
253 }
254 
255 /* Free one line. */
256 static void
257 grid_free_line(struct grid *gd, u_int py)
258 {
259 	free(gd->linedata[py].celldata);
260 	gd->linedata[py].celldata = NULL;
261 	free(gd->linedata[py].extddata);
262 	gd->linedata[py].extddata = NULL;
263 }
264 
265 /* Free several lines. */
266 static void
267 grid_free_lines(struct grid *gd, u_int py, u_int ny)
268 {
269 	u_int	yy;
270 
271 	for (yy = py; yy < py + ny; yy++)
272 		grid_free_line(gd, yy);
273 }
274 
275 /* Create a new grid. */
276 struct grid *
277 grid_create(u_int sx, u_int sy, u_int hlimit)
278 {
279 	struct grid	*gd;
280 
281 	gd = xmalloc(sizeof *gd);
282 	gd->sx = sx;
283 	gd->sy = sy;
284 
285 	if (hlimit != 0)
286 		gd->flags = GRID_HISTORY;
287 	else
288 		gd->flags = 0;
289 
290 	gd->hscrolled = 0;
291 	gd->hsize = 0;
292 	gd->hlimit = hlimit;
293 
294 	if (gd->sy != 0)
295 		gd->linedata = xcalloc(gd->sy, sizeof *gd->linedata);
296 	else
297 		gd->linedata = NULL;
298 
299 	return (gd);
300 }
301 
302 /* Destroy grid. */
303 void
304 grid_destroy(struct grid *gd)
305 {
306 	grid_free_lines(gd, 0, gd->hsize + gd->sy);
307 
308 	free(gd->linedata);
309 
310 	free(gd);
311 }
312 
313 /* Compare grids. */
314 int
315 grid_compare(struct grid *ga, struct grid *gb)
316 {
317 	struct grid_line	*gla, *glb;
318 	struct grid_cell	 gca, gcb;
319 	u_int			 xx, yy;
320 
321 	if (ga->sx != gb->sx || ga->sy != gb->sy)
322 		return (1);
323 
324 	for (yy = 0; yy < ga->sy; yy++) {
325 		gla = &ga->linedata[yy];
326 		glb = &gb->linedata[yy];
327 		if (gla->cellsize != glb->cellsize)
328 			return (1);
329 		for (xx = 0; xx < gla->cellsize; xx++) {
330 			grid_get_cell(ga, xx, yy, &gca);
331 			grid_get_cell(gb, xx, yy, &gcb);
332 			if (!grid_cells_equal(&gca, &gcb))
333 				return (1);
334 		}
335 	}
336 
337 	return (0);
338 }
339 
340 /* Trim lines from the history. */
341 static void
342 grid_trim_history(struct grid *gd, u_int ny)
343 {
344 	grid_free_lines(gd, 0, ny);
345 	memmove(&gd->linedata[0], &gd->linedata[ny],
346 	    (gd->hsize + gd->sy - ny) * (sizeof *gd->linedata));
347 }
348 
349 /*
350  * Collect lines from the history if at the limit. Free the top (oldest) 10%
351  * and shift up.
352  */
353 void
354 grid_collect_history(struct grid *gd)
355 {
356 	u_int	ny;
357 
358 	if (gd->hsize == 0 || gd->hsize < gd->hlimit)
359 		return;
360 
361 	ny = gd->hlimit / 10;
362 	if (ny < 1)
363 		ny = 1;
364 	if (ny > gd->hsize)
365 		ny = gd->hsize;
366 
367 	/*
368 	 * Free the lines from 0 to ny then move the remaining lines over
369 	 * them.
370 	 */
371 	grid_trim_history(gd, ny);
372 
373 	gd->hsize -= ny;
374 	if (gd->hscrolled > gd->hsize)
375 		gd->hscrolled = gd->hsize;
376 }
377 
378 /* Remove lines from the bottom of the history. */
379 void
380 grid_remove_history(struct grid *gd, u_int ny)
381 {
382 	u_int	yy;
383 
384 	if (ny > gd->hsize)
385 		return;
386 	for (yy = 0; yy < ny; yy++)
387 		grid_free_line(gd, gd->hsize + gd->sy - 1 - yy);
388 	gd->hsize -= ny;
389 }
390 
391 /*
392  * Scroll the entire visible screen, moving one line into the history. Just
393  * allocate a new line at the bottom and move the history size indicator.
394  */
395 void
396 grid_scroll_history(struct grid *gd, u_int bg)
397 {
398 	u_int	yy;
399 
400 	yy = gd->hsize + gd->sy;
401 	gd->linedata = xreallocarray(gd->linedata, yy + 1,
402 	    sizeof *gd->linedata);
403 	grid_empty_line(gd, yy, bg);
404 
405 	gd->hscrolled++;
406 	grid_compact_line(&gd->linedata[gd->hsize]);
407 	gd->linedata[gd->hsize].time = current_time;
408 	gd->hsize++;
409 }
410 
411 /* Clear the history. */
412 void
413 grid_clear_history(struct grid *gd)
414 {
415 	grid_trim_history(gd, gd->hsize);
416 
417 	gd->hscrolled = 0;
418 	gd->hsize = 0;
419 
420 	gd->linedata = xreallocarray(gd->linedata, gd->sy,
421 	    sizeof *gd->linedata);
422 }
423 
424 /* Scroll a region up, moving the top line into the history. */
425 void
426 grid_scroll_history_region(struct grid *gd, u_int upper, u_int lower, u_int bg)
427 {
428 	struct grid_line	*gl_history, *gl_upper;
429 	u_int			 yy;
430 
431 	/* Create a space for a new line. */
432 	yy = gd->hsize + gd->sy;
433 	gd->linedata = xreallocarray(gd->linedata, yy + 1,
434 	    sizeof *gd->linedata);
435 
436 	/* Move the entire screen down to free a space for this line. */
437 	gl_history = &gd->linedata[gd->hsize];
438 	memmove(gl_history + 1, gl_history, gd->sy * sizeof *gl_history);
439 
440 	/* Adjust the region and find its start and end. */
441 	upper++;
442 	gl_upper = &gd->linedata[upper];
443 	lower++;
444 
445 	/* Move the line into the history. */
446 	memcpy(gl_history, gl_upper, sizeof *gl_history);
447 	gl_history->time = current_time;
448 
449 	/* Then move the region up and clear the bottom line. */
450 	memmove(gl_upper, gl_upper + 1, (lower - upper) * sizeof *gl_upper);
451 	grid_empty_line(gd, lower, bg);
452 
453 	/* Move the history offset down over the line. */
454 	gd->hscrolled++;
455 	gd->hsize++;
456 }
457 
458 /* Expand line to fit to cell. */
459 static void
460 grid_expand_line(struct grid *gd, u_int py, u_int sx, u_int bg)
461 {
462 	struct grid_line	*gl;
463 	u_int			 xx;
464 
465 	gl = &gd->linedata[py];
466 	if (sx <= gl->cellsize)
467 		return;
468 
469 	if (sx < gd->sx / 4)
470 		sx = gd->sx / 4;
471 	else if (sx < gd->sx / 2)
472 		sx = gd->sx / 2;
473 	else if (gd->sx > sx)
474 		sx = gd->sx;
475 
476 	gl->celldata = xreallocarray(gl->celldata, sx, sizeof *gl->celldata);
477 	for (xx = gl->cellsize; xx < sx; xx++)
478 		grid_clear_cell(gd, xx, py, bg);
479 	gl->cellsize = sx;
480 }
481 
482 /* Empty a line and set background colour if needed. */
483 void
484 grid_empty_line(struct grid *gd, u_int py, u_int bg)
485 {
486 	memset(&gd->linedata[py], 0, sizeof gd->linedata[py]);
487 	if (!COLOUR_DEFAULT(bg))
488 		grid_expand_line(gd, py, gd->sx, bg);
489 }
490 
491 /* Peek at grid line. */
492 const struct grid_line *
493 grid_peek_line(struct grid *gd, u_int py)
494 {
495 	if (grid_check_y(gd, __func__, py) != 0)
496 		return (NULL);
497 	return (&gd->linedata[py]);
498 }
499 
500 /* Get cell from line. */
501 static void
502 grid_get_cell1(struct grid_line *gl, u_int px, struct grid_cell *gc)
503 {
504 	struct grid_cell_entry	*gce = &gl->celldata[px];
505 	struct grid_extd_entry	*gee;
506 
507 	if (gce->flags & GRID_FLAG_EXTENDED) {
508 		if (gce->offset >= gl->extdsize)
509 			memcpy(gc, &grid_default_cell, sizeof *gc);
510 		else {
511 			gee = &gl->extddata[gce->offset];
512 			gc->flags = gee->flags;
513 			gc->attr = gee->attr;
514 			gc->fg = gee->fg;
515 			gc->bg = gee->bg;
516 			gc->us = gee->us;
517 			gc->link = gee->link;
518 			utf8_to_data(gee->data, &gc->data);
519 		}
520 		return;
521 	}
522 
523 	gc->flags = gce->flags & ~(GRID_FLAG_FG256|GRID_FLAG_BG256);
524 	gc->attr = gce->data.attr;
525 	gc->fg = gce->data.fg;
526 	if (gce->flags & GRID_FLAG_FG256)
527 		gc->fg |= COLOUR_FLAG_256;
528 	gc->bg = gce->data.bg;
529 	if (gce->flags & GRID_FLAG_BG256)
530 		gc->bg |= COLOUR_FLAG_256;
531 	gc->us = 0;
532 	utf8_set(&gc->data, gce->data.data);
533 	gc->link = 0;
534 }
535 
536 /* Get cell for reading. */
537 void
538 grid_get_cell(struct grid *gd, u_int px, u_int py, struct grid_cell *gc)
539 {
540 	if (grid_check_y(gd, __func__, py) != 0 ||
541 	    px >= gd->linedata[py].cellsize)
542 		memcpy(gc, &grid_default_cell, sizeof *gc);
543 	else
544 		grid_get_cell1(&gd->linedata[py], px, gc);
545 }
546 
547 /* Set cell at position. */
548 void
549 grid_set_cell(struct grid *gd, u_int px, u_int py, const struct grid_cell *gc)
550 {
551 	struct grid_line	*gl;
552 	struct grid_cell_entry	*gce;
553 
554 	if (grid_check_y(gd, __func__, py) != 0)
555 		return;
556 
557 	grid_expand_line(gd, py, px + 1, 8);
558 
559 	gl = &gd->linedata[py];
560 	if (px + 1 > gl->cellused)
561 		gl->cellused = px + 1;
562 
563 	gce = &gl->celldata[px];
564 	if (grid_need_extended_cell(gce, gc))
565 		grid_extended_cell(gl, gce, gc);
566 	else
567 		grid_store_cell(gce, gc, gc->data.data[0]);
568 }
569 
570 /* Set padding at position. */
571 void
572 grid_set_padding(struct grid *gd, u_int px, u_int py)
573 {
574 	grid_set_cell(gd, px, py, &grid_padding_cell);
575 }
576 
577 /* Set cells at position. */
578 void
579 grid_set_cells(struct grid *gd, u_int px, u_int py, const struct grid_cell *gc,
580     const char *s, size_t slen)
581 {
582 	struct grid_line	*gl;
583 	struct grid_cell_entry	*gce;
584 	struct grid_extd_entry	*gee;
585 	u_int			 i;
586 
587 	if (grid_check_y(gd, __func__, py) != 0)
588 		return;
589 
590 	grid_expand_line(gd, py, px + slen, 8);
591 
592 	gl = &gd->linedata[py];
593 	if (px + slen > gl->cellused)
594 		gl->cellused = px + slen;
595 
596 	for (i = 0; i < slen; i++) {
597 		gce = &gl->celldata[px + i];
598 		if (grid_need_extended_cell(gce, gc)) {
599 			gee = grid_extended_cell(gl, gce, gc);
600 			gee->data = utf8_build_one(s[i]);
601 		} else
602 			grid_store_cell(gce, gc, s[i]);
603 	}
604 }
605 
606 /* Clear area. */
607 void
608 grid_clear(struct grid *gd, u_int px, u_int py, u_int nx, u_int ny, u_int bg)
609 {
610 	struct grid_line	*gl;
611 	u_int			 xx, yy, ox, sx;
612 
613 	if (nx == 0 || ny == 0)
614 		return;
615 
616 	if (px == 0 && nx == gd->sx) {
617 		grid_clear_lines(gd, py, ny, bg);
618 		return;
619 	}
620 
621 	if (grid_check_y(gd, __func__, py) != 0)
622 		return;
623 	if (grid_check_y(gd, __func__, py + ny - 1) != 0)
624 		return;
625 
626 	for (yy = py; yy < py + ny; yy++) {
627 		gl = &gd->linedata[yy];
628 
629 		sx = gd->sx;
630 		if (sx > gl->cellsize)
631 			sx = gl->cellsize;
632 		ox = nx;
633 		if (COLOUR_DEFAULT(bg)) {
634 			if (px > sx)
635 				continue;
636 			if (px + nx > sx)
637 				ox = sx - px;
638 		}
639 
640 		grid_expand_line(gd, yy, px + ox, 8); /* default bg first */
641 		for (xx = px; xx < px + ox; xx++)
642 			grid_clear_cell(gd, xx, yy, bg);
643 	}
644 }
645 
646 /* Clear lines. This just frees and truncates the lines. */
647 void
648 grid_clear_lines(struct grid *gd, u_int py, u_int ny, u_int bg)
649 {
650 	u_int	yy;
651 
652 	if (ny == 0)
653 		return;
654 
655 	if (grid_check_y(gd, __func__, py) != 0)
656 		return;
657 	if (grid_check_y(gd, __func__, py + ny - 1) != 0)
658 		return;
659 
660 	for (yy = py; yy < py + ny; yy++) {
661 		grid_free_line(gd, yy);
662 		grid_empty_line(gd, yy, bg);
663 	}
664 	if (py != 0)
665 		gd->linedata[py - 1].flags &= ~GRID_LINE_WRAPPED;
666 }
667 
668 /* Move a group of lines. */
669 void
670 grid_move_lines(struct grid *gd, u_int dy, u_int py, u_int ny, u_int bg)
671 {
672 	u_int	yy;
673 
674 	if (ny == 0 || py == dy)
675 		return;
676 
677 	if (grid_check_y(gd, __func__, py) != 0)
678 		return;
679 	if (grid_check_y(gd, __func__, py + ny - 1) != 0)
680 		return;
681 	if (grid_check_y(gd, __func__, dy) != 0)
682 		return;
683 	if (grid_check_y(gd, __func__, dy + ny - 1) != 0)
684 		return;
685 
686 	/* Free any lines which are being replaced. */
687 	for (yy = dy; yy < dy + ny; yy++) {
688 		if (yy >= py && yy < py + ny)
689 			continue;
690 		grid_free_line(gd, yy);
691 	}
692 	if (dy != 0)
693 		gd->linedata[dy - 1].flags &= ~GRID_LINE_WRAPPED;
694 
695 	memmove(&gd->linedata[dy], &gd->linedata[py],
696 	    ny * (sizeof *gd->linedata));
697 
698 	/*
699 	 * Wipe any lines that have been moved (without freeing them - they are
700 	 * still present).
701 	 */
702 	for (yy = py; yy < py + ny; yy++) {
703 		if (yy < dy || yy >= dy + ny)
704 			grid_empty_line(gd, yy, bg);
705 	}
706 	if (py != 0 && (py < dy || py >= dy + ny))
707 		gd->linedata[py - 1].flags &= ~GRID_LINE_WRAPPED;
708 }
709 
710 /* Move a group of cells. */
711 void
712 grid_move_cells(struct grid *gd, u_int dx, u_int px, u_int py, u_int nx,
713     u_int bg)
714 {
715 	struct grid_line	*gl;
716 	u_int			 xx;
717 
718 	if (nx == 0 || px == dx)
719 		return;
720 
721 	if (grid_check_y(gd, __func__, py) != 0)
722 		return;
723 	gl = &gd->linedata[py];
724 
725 	grid_expand_line(gd, py, px + nx, 8);
726 	grid_expand_line(gd, py, dx + nx, 8);
727 	memmove(&gl->celldata[dx], &gl->celldata[px],
728 	    nx * sizeof *gl->celldata);
729 	if (dx + nx > gl->cellused)
730 		gl->cellused = dx + nx;
731 
732 	/* Wipe any cells that have been moved. */
733 	for (xx = px; xx < px + nx; xx++) {
734 		if (xx >= dx && xx < dx + nx)
735 			continue;
736 		grid_clear_cell(gd, xx, py, bg);
737 	}
738 }
739 
740 /* Get ANSI foreground sequence. */
741 static size_t
742 grid_string_cells_fg(const struct grid_cell *gc, int *values)
743 {
744 	size_t	n;
745 	u_char	r, g, b;
746 
747 	n = 0;
748 	if (gc->fg & COLOUR_FLAG_256) {
749 		values[n++] = 38;
750 		values[n++] = 5;
751 		values[n++] = gc->fg & 0xff;
752 	} else if (gc->fg & COLOUR_FLAG_RGB) {
753 		values[n++] = 38;
754 		values[n++] = 2;
755 		colour_split_rgb(gc->fg, &r, &g, &b);
756 		values[n++] = r;
757 		values[n++] = g;
758 		values[n++] = b;
759 	} else {
760 		switch (gc->fg) {
761 		case 0:
762 		case 1:
763 		case 2:
764 		case 3:
765 		case 4:
766 		case 5:
767 		case 6:
768 		case 7:
769 			values[n++] = gc->fg + 30;
770 			break;
771 		case 8:
772 			values[n++] = 39;
773 			break;
774 		case 90:
775 		case 91:
776 		case 92:
777 		case 93:
778 		case 94:
779 		case 95:
780 		case 96:
781 		case 97:
782 			values[n++] = gc->fg;
783 			break;
784 		}
785 	}
786 	return (n);
787 }
788 
789 /* Get ANSI background sequence. */
790 static size_t
791 grid_string_cells_bg(const struct grid_cell *gc, int *values)
792 {
793 	size_t	n;
794 	u_char	r, g, b;
795 
796 	n = 0;
797 	if (gc->bg & COLOUR_FLAG_256) {
798 		values[n++] = 48;
799 		values[n++] = 5;
800 		values[n++] = gc->bg & 0xff;
801 	} else if (gc->bg & COLOUR_FLAG_RGB) {
802 		values[n++] = 48;
803 		values[n++] = 2;
804 		colour_split_rgb(gc->bg, &r, &g, &b);
805 		values[n++] = r;
806 		values[n++] = g;
807 		values[n++] = b;
808 	} else {
809 		switch (gc->bg) {
810 		case 0:
811 		case 1:
812 		case 2:
813 		case 3:
814 		case 4:
815 		case 5:
816 		case 6:
817 		case 7:
818 			values[n++] = gc->bg + 40;
819 			break;
820 		case 8:
821 			values[n++] = 49;
822 			break;
823 		case 90:
824 		case 91:
825 		case 92:
826 		case 93:
827 		case 94:
828 		case 95:
829 		case 96:
830 		case 97:
831 			values[n++] = gc->bg + 10;
832 			break;
833 		}
834 	}
835 	return (n);
836 }
837 
838 /* Get underscore colour sequence. */
839 static size_t
840 grid_string_cells_us(const struct grid_cell *gc, int *values)
841 {
842 	size_t	n;
843 	u_char	r, g, b;
844 
845 	n = 0;
846 	if (gc->us & COLOUR_FLAG_256) {
847 		values[n++] = 58;
848 		values[n++] = 5;
849 		values[n++] = gc->us & 0xff;
850 	} else if (gc->us & COLOUR_FLAG_RGB) {
851 		values[n++] = 58;
852 		values[n++] = 2;
853 		colour_split_rgb(gc->us, &r, &g, &b);
854 		values[n++] = r;
855 		values[n++] = g;
856 		values[n++] = b;
857 	}
858 	return (n);
859 }
860 
861 /* Add on SGR code. */
862 static void
863 grid_string_cells_add_code(char *buf, size_t len, u_int n, int *s, int *newc,
864     int *oldc, size_t nnewc, size_t noldc, int escape_c0)
865 {
866 	u_int	i;
867 	char	tmp[64];
868 
869 	if (nnewc != 0 &&
870 	    (nnewc != noldc ||
871 	    memcmp(newc, oldc, nnewc * sizeof newc[0]) != 0 ||
872 	    (n != 0 && s[0] == 0))) {
873 		if (escape_c0)
874 			strlcat(buf, "\\033[", len);
875 		else
876 			strlcat(buf, "\033[", len);
877 		for (i = 0; i < nnewc; i++) {
878 			if (i + 1 < nnewc)
879 				xsnprintf(tmp, sizeof tmp, "%d;", newc[i]);
880 			else
881 				xsnprintf(tmp, sizeof tmp, "%d", newc[i]);
882 			strlcat(buf, tmp, len);
883 		}
884 		strlcat(buf, "m", len);
885 	}
886 }
887 
888 static int
889 grid_string_cells_add_hyperlink(char *buf, size_t len, const char *id,
890     const char *uri, int escape_c0)
891 {
892 	char	*tmp;
893 
894 	if (strlen(uri) + strlen(id) + 17 >= len)
895 		return (0);
896 
897 	if (escape_c0)
898 		strlcat(buf, "\\033]8;", len);
899 	else
900 		strlcat(buf, "\033]8;", len);
901 	if (*id != '\0') {
902 		xasprintf(&tmp, "id=%s;", id);
903 		strlcat(buf, tmp, len);
904 		free(tmp);
905 	} else
906 		strlcat(buf, ";", len);
907 	strlcat(buf, uri, len);
908 	if (escape_c0)
909 		strlcat(buf, "\\033\\\\", len);
910 	else
911 		strlcat(buf, "\033\\", len);
912 	return (1);
913 }
914 
915 /*
916  * Returns ANSI code to set particular attributes (colour, bold and so on)
917  * given a current state.
918  */
919 static void
920 grid_string_cells_code(const struct grid_cell *lastgc,
921     const struct grid_cell *gc, char *buf, size_t len, int escape_c0,
922     struct screen *sc, int *has_link)
923 {
924 	int			 oldc[64], newc[64], s[128];
925 	size_t			 noldc, nnewc, n, i;
926 	u_int			 attr = gc->attr, lastattr = lastgc->attr;
927 	char			 tmp[64];
928 	const char		*uri, *id;
929 
930 	struct {
931 		u_int	mask;
932 		u_int	code;
933 	} attrs[] = {
934 		{ GRID_ATTR_BRIGHT, 1 },
935 		{ GRID_ATTR_DIM, 2 },
936 		{ GRID_ATTR_ITALICS, 3 },
937 		{ GRID_ATTR_UNDERSCORE, 4 },
938 		{ GRID_ATTR_BLINK, 5 },
939 		{ GRID_ATTR_REVERSE, 7 },
940 		{ GRID_ATTR_HIDDEN, 8 },
941 		{ GRID_ATTR_STRIKETHROUGH, 9 },
942 		{ GRID_ATTR_UNDERSCORE_2, 42 },
943 		{ GRID_ATTR_UNDERSCORE_3, 43 },
944 		{ GRID_ATTR_UNDERSCORE_4, 44 },
945 		{ GRID_ATTR_UNDERSCORE_5, 45 },
946 		{ GRID_ATTR_OVERLINE, 53 },
947 	};
948 	n = 0;
949 
950 	/* If any attribute is removed, begin with 0. */
951 	for (i = 0; i < nitems(attrs); i++) {
952 		if (((~attr & attrs[i].mask) &&
953 		    (lastattr & attrs[i].mask)) ||
954 		    (lastgc->us != 0 && gc->us == 0)) {
955 			s[n++] = 0;
956 			lastattr &= GRID_ATTR_CHARSET;
957 			break;
958 		}
959 	}
960 	/* For each attribute that is newly set, add its code. */
961 	for (i = 0; i < nitems(attrs); i++) {
962 		if ((attr & attrs[i].mask) && !(lastattr & attrs[i].mask))
963 			s[n++] = attrs[i].code;
964 	}
965 
966 	/* Write the attributes. */
967 	*buf = '\0';
968 	if (n > 0) {
969 		if (escape_c0)
970 			strlcat(buf, "\\033[", len);
971 		else
972 			strlcat(buf, "\033[", len);
973 		for (i = 0; i < n; i++) {
974 			if (s[i] < 10)
975 				xsnprintf(tmp, sizeof tmp, "%d", s[i]);
976 			else {
977 				xsnprintf(tmp, sizeof tmp, "%d:%d", s[i] / 10,
978 				    s[i] % 10);
979 			}
980 			strlcat(buf, tmp, len);
981 			if (i + 1 < n)
982 				strlcat(buf, ";", len);
983 		}
984 		strlcat(buf, "m", len);
985 	}
986 
987 	/* If the foreground colour changed, write its parameters. */
988 	nnewc = grid_string_cells_fg(gc, newc);
989 	noldc = grid_string_cells_fg(lastgc, oldc);
990 	grid_string_cells_add_code(buf, len, n, s, newc, oldc, nnewc, noldc,
991 	    escape_c0);
992 
993 	/* If the background colour changed, append its parameters. */
994 	nnewc = grid_string_cells_bg(gc, newc);
995 	noldc = grid_string_cells_bg(lastgc, oldc);
996 	grid_string_cells_add_code(buf, len, n, s, newc, oldc, nnewc, noldc,
997 	    escape_c0);
998 
999 	/* If the underscore colour changed, append its parameters. */
1000 	nnewc = grid_string_cells_us(gc, newc);
1001 	noldc = grid_string_cells_us(lastgc, oldc);
1002 	grid_string_cells_add_code(buf, len, n, s, newc, oldc, nnewc, noldc,
1003 	    escape_c0);
1004 
1005 	/* Append shift in/shift out if needed. */
1006 	if ((attr & GRID_ATTR_CHARSET) && !(lastattr & GRID_ATTR_CHARSET)) {
1007 		if (escape_c0)
1008 			strlcat(buf, "\\016", len); /* SO */
1009 		else
1010 			strlcat(buf, "\016", len);  /* SO */
1011 	}
1012 	if (!(attr & GRID_ATTR_CHARSET) && (lastattr & GRID_ATTR_CHARSET)) {
1013 		if (escape_c0)
1014 			strlcat(buf, "\\017", len); /* SI */
1015 		else
1016 			strlcat(buf, "\017", len);  /* SI */
1017 	}
1018 
1019 	/* Add hyperlink if changed. */
1020 	if (sc != NULL && sc->hyperlinks != NULL && lastgc->link != gc->link) {
1021 		if (hyperlinks_get(sc->hyperlinks, gc->link, &uri, &id, NULL)) {
1022 			*has_link = grid_string_cells_add_hyperlink(buf, len,
1023 			    id, uri, escape_c0);
1024 		} else if (*has_link) {
1025 			grid_string_cells_add_hyperlink(buf, len, "", "",
1026 			    escape_c0);
1027 			*has_link = 0;
1028 		}
1029 	}
1030 }
1031 
1032 /* Convert cells into a string. */
1033 char *
1034 grid_string_cells(struct grid *gd, u_int px, u_int py, u_int nx,
1035     struct grid_cell **lastgc, int with_codes, int escape_c0, int trim,
1036     struct screen *s)
1037 {
1038 	struct grid_cell	 gc;
1039 	static struct grid_cell	 lastgc1;
1040 	const char		*data;
1041 	char			*buf, code[8192];
1042 	size_t			 len, off, size, codelen;
1043 	u_int			 xx, has_link = 0;
1044 	const struct grid_line	*gl;
1045 
1046 	if (lastgc != NULL && *lastgc == NULL) {
1047 		memcpy(&lastgc1, &grid_default_cell, sizeof lastgc1);
1048 		*lastgc = &lastgc1;
1049 	}
1050 
1051 	len = 128;
1052 	buf = xmalloc(len);
1053 	off = 0;
1054 
1055 	gl = grid_peek_line(gd, py);
1056 	for (xx = px; xx < px + nx; xx++) {
1057 		if (gl == NULL || xx >= gl->cellused)
1058 			break;
1059 		grid_get_cell(gd, xx, py, &gc);
1060 		if (gc.flags & GRID_FLAG_PADDING)
1061 			continue;
1062 
1063 		if (with_codes) {
1064 			grid_string_cells_code(*lastgc, &gc, code, sizeof code,
1065 			    escape_c0, s, &has_link);
1066 			codelen = strlen(code);
1067 			memcpy(*lastgc, &gc, sizeof **lastgc);
1068 		} else
1069 			codelen = 0;
1070 
1071 		data = gc.data.data;
1072 		size = gc.data.size;
1073 		if (escape_c0 && size == 1 && *data == '\\') {
1074 			data = "\\\\";
1075 			size = 2;
1076 		}
1077 
1078 		while (len < off + size + codelen + 1) {
1079 			buf = xreallocarray(buf, 2, len);
1080 			len *= 2;
1081 		}
1082 
1083 		if (codelen != 0) {
1084 			memcpy(buf + off, code, codelen);
1085 			off += codelen;
1086 		}
1087 		memcpy(buf + off, data, size);
1088 		off += size;
1089 	}
1090 
1091 	if (has_link) {
1092 		grid_string_cells_add_hyperlink(code, sizeof code, "", "",
1093 		    escape_c0);
1094 		codelen = strlen(code);
1095 		while (len < off + size + codelen + 1) {
1096 			buf = xreallocarray(buf, 2, len);
1097 			len *= 2;
1098 		}
1099 		memcpy(buf + off, code, codelen);
1100 		off += codelen;
1101 	}
1102 
1103 	if (trim) {
1104 		while (off > 0 && buf[off - 1] == ' ')
1105 			off--;
1106 	}
1107 	buf[off] = '\0';
1108 
1109 	return (buf);
1110 }
1111 
1112 /*
1113  * Duplicate a set of lines between two grids. Both source and destination
1114  * should be big enough.
1115  */
1116 void
1117 grid_duplicate_lines(struct grid *dst, u_int dy, struct grid *src, u_int sy,
1118     u_int ny)
1119 {
1120 	struct grid_line	*dstl, *srcl;
1121 	u_int			 yy;
1122 
1123 	if (dy + ny > dst->hsize + dst->sy)
1124 		ny = dst->hsize + dst->sy - dy;
1125 	if (sy + ny > src->hsize + src->sy)
1126 		ny = src->hsize + src->sy - sy;
1127 	grid_free_lines(dst, dy, ny);
1128 
1129 	for (yy = 0; yy < ny; yy++) {
1130 		srcl = &src->linedata[sy];
1131 		dstl = &dst->linedata[dy];
1132 
1133 		memcpy(dstl, srcl, sizeof *dstl);
1134 		if (srcl->cellsize != 0) {
1135 			dstl->celldata = xreallocarray(NULL,
1136 			    srcl->cellsize, sizeof *dstl->celldata);
1137 			memcpy(dstl->celldata, srcl->celldata,
1138 			    srcl->cellsize * sizeof *dstl->celldata);
1139 		} else
1140 			dstl->celldata = NULL;
1141 		if (srcl->extdsize != 0) {
1142 			dstl->extdsize = srcl->extdsize;
1143 			dstl->extddata = xreallocarray(NULL, dstl->extdsize,
1144 			    sizeof *dstl->extddata);
1145 			memcpy(dstl->extddata, srcl->extddata, dstl->extdsize *
1146 			    sizeof *dstl->extddata);
1147 		} else
1148 			dstl->extddata = NULL;
1149 
1150 		sy++;
1151 		dy++;
1152 	}
1153 }
1154 
1155 /* Mark line as dead. */
1156 static void
1157 grid_reflow_dead(struct grid_line *gl)
1158 {
1159 	memset(gl, 0, sizeof *gl);
1160 	gl->flags = GRID_LINE_DEAD;
1161 }
1162 
1163 /* Add lines, return the first new one. */
1164 static struct grid_line *
1165 grid_reflow_add(struct grid *gd, u_int n)
1166 {
1167 	struct grid_line	*gl;
1168 	u_int			 sy = gd->sy + n;
1169 
1170 	gd->linedata = xreallocarray(gd->linedata, sy, sizeof *gd->linedata);
1171 	gl = &gd->linedata[gd->sy];
1172 	memset(gl, 0, n * (sizeof *gl));
1173 	gd->sy = sy;
1174 	return (gl);
1175 }
1176 
1177 /* Move a line across. */
1178 static struct grid_line *
1179 grid_reflow_move(struct grid *gd, struct grid_line *from)
1180 {
1181 	struct grid_line	*to;
1182 
1183 	to = grid_reflow_add(gd, 1);
1184 	memcpy(to, from, sizeof *to);
1185 	grid_reflow_dead(from);
1186 	return (to);
1187 }
1188 
1189 /* Join line below onto this one. */
1190 static void
1191 grid_reflow_join(struct grid *target, struct grid *gd, u_int sx, u_int yy,
1192     u_int width, int already)
1193 {
1194 	struct grid_line	*gl, *from = NULL;
1195 	struct grid_cell	 gc;
1196 	u_int			 lines, left, i, to, line, want = 0;
1197 	u_int			 at;
1198 	int			 wrapped = 1;
1199 
1200 	/*
1201 	 * Add a new target line.
1202 	 */
1203 	if (!already) {
1204 		to = target->sy;
1205 		gl = grid_reflow_move(target, &gd->linedata[yy]);
1206 	} else {
1207 		to = target->sy - 1;
1208 		gl = &target->linedata[to];
1209 	}
1210 	at = gl->cellused;
1211 
1212 	/*
1213 	 * Loop until no more to consume or the target line is full.
1214 	 */
1215 	lines = 0;
1216 	for (;;) {
1217 		/*
1218 		 * If this is now the last line, there is nothing more to be
1219 		 * done.
1220 		 */
1221 		if (yy + 1 + lines == gd->hsize + gd->sy)
1222 			break;
1223 		line = yy + 1 + lines;
1224 
1225 		/* If the next line is empty, skip it. */
1226 		if (~gd->linedata[line].flags & GRID_LINE_WRAPPED)
1227 			wrapped = 0;
1228 		if (gd->linedata[line].cellused == 0) {
1229 			if (!wrapped)
1230 				break;
1231 			lines++;
1232 			continue;
1233 		}
1234 
1235 		/*
1236 		 * Is the destination line now full? Copy the first character
1237 		 * separately because we need to leave "from" set to the last
1238 		 * line if this line is full.
1239 		 */
1240 		grid_get_cell1(&gd->linedata[line], 0, &gc);
1241 		if (width + gc.data.width > sx)
1242 			break;
1243 		width += gc.data.width;
1244 		grid_set_cell(target, at, to, &gc);
1245 		at++;
1246 
1247 		/* Join as much more as possible onto the current line. */
1248 		from = &gd->linedata[line];
1249 		for (want = 1; want < from->cellused; want++) {
1250 			grid_get_cell1(from, want, &gc);
1251 			if (width + gc.data.width > sx)
1252 				break;
1253 			width += gc.data.width;
1254 
1255 			grid_set_cell(target, at, to, &gc);
1256 			at++;
1257 		}
1258 		lines++;
1259 
1260 		/*
1261 		 * If this line wasn't wrapped or we didn't consume the entire
1262 		 * line, don't try to join any further lines.
1263 		 */
1264 		if (!wrapped || want != from->cellused || width == sx)
1265 			break;
1266 	}
1267 	if (lines == 0)
1268 		return;
1269 
1270 	/*
1271 	 * If we didn't consume the entire final line, then remove what we did
1272 	 * consume. If we consumed the entire line and it wasn't wrapped,
1273 	 * remove the wrap flag from this line.
1274 	 */
1275 	left = from->cellused - want;
1276 	if (left != 0) {
1277 		grid_move_cells(gd, 0, want, yy + lines, left, 8);
1278 		from->cellsize = from->cellused = left;
1279 		lines--;
1280 	} else if (!wrapped)
1281 		gl->flags &= ~GRID_LINE_WRAPPED;
1282 
1283 	/* Remove the lines that were completely consumed. */
1284 	for (i = yy + 1; i < yy + 1 + lines; i++) {
1285 		free(gd->linedata[i].celldata);
1286 		free(gd->linedata[i].extddata);
1287 		grid_reflow_dead(&gd->linedata[i]);
1288 	}
1289 
1290 	/* Adjust scroll position. */
1291 	if (gd->hscrolled > to + lines)
1292 		gd->hscrolled -= lines;
1293 	else if (gd->hscrolled > to)
1294 		gd->hscrolled = to;
1295 }
1296 
1297 /* Split this line into several new ones */
1298 static void
1299 grid_reflow_split(struct grid *target, struct grid *gd, u_int sx, u_int yy,
1300     u_int at)
1301 {
1302 	struct grid_line	*gl = &gd->linedata[yy], *first;
1303 	struct grid_cell	 gc;
1304 	u_int			 line, lines, width, i, xx;
1305 	u_int			 used = gl->cellused;
1306 	int			 flags = gl->flags;
1307 
1308 	/* How many lines do we need to insert? We know we need at least two. */
1309 	if (~gl->flags & GRID_LINE_EXTENDED)
1310 		lines = 1 + (gl->cellused - 1) / sx;
1311 	else {
1312 		lines = 2;
1313 		width = 0;
1314 		for (i = at; i < used; i++) {
1315 			grid_get_cell1(gl, i, &gc);
1316 			if (width + gc.data.width > sx) {
1317 				lines++;
1318 				width = 0;
1319 			}
1320 			width += gc.data.width;
1321 		}
1322 	}
1323 
1324 	/* Insert new lines. */
1325 	line = target->sy + 1;
1326 	first = grid_reflow_add(target, lines);
1327 
1328 	/* Copy sections from the original line. */
1329 	width = 0;
1330 	xx = 0;
1331 	for (i = at; i < used; i++) {
1332 		grid_get_cell1(gl, i, &gc);
1333 		if (width + gc.data.width > sx) {
1334 			target->linedata[line].flags |= GRID_LINE_WRAPPED;
1335 
1336 			line++;
1337 			width = 0;
1338 			xx = 0;
1339 		}
1340 		width += gc.data.width;
1341 		grid_set_cell(target, xx, line, &gc);
1342 		xx++;
1343 	}
1344 	if (flags & GRID_LINE_WRAPPED)
1345 		target->linedata[line].flags |= GRID_LINE_WRAPPED;
1346 
1347 	/* Move the remainder of the original line. */
1348 	gl->cellsize = gl->cellused = at;
1349 	gl->flags |= GRID_LINE_WRAPPED;
1350 	memcpy(first, gl, sizeof *first);
1351 	grid_reflow_dead(gl);
1352 
1353 	/* Adjust the scroll position. */
1354 	if (yy <= gd->hscrolled)
1355 		gd->hscrolled += lines - 1;
1356 
1357 	/*
1358 	 * If the original line had the wrapped flag and there is still space
1359 	 * in the last new line, try to join with the next lines.
1360 	 */
1361 	if (width < sx && (flags & GRID_LINE_WRAPPED))
1362 		grid_reflow_join(target, gd, sx, yy, width, 1);
1363 }
1364 
1365 /* Reflow lines on grid to new width. */
1366 void
1367 grid_reflow(struct grid *gd, u_int sx)
1368 {
1369 	struct grid		*target;
1370 	struct grid_line	*gl;
1371 	struct grid_cell	 gc;
1372 	u_int			 yy, width, i, at;
1373 
1374 	/*
1375 	 * Create a destination grid. This is just used as a container for the
1376 	 * line data and may not be fully valid.
1377 	 */
1378 	target = grid_create(gd->sx, 0, 0);
1379 
1380 	/*
1381 	 * Loop over each source line.
1382 	 */
1383 	for (yy = 0; yy < gd->hsize + gd->sy; yy++) {
1384 		gl = &gd->linedata[yy];
1385 		if (gl->flags & GRID_LINE_DEAD)
1386 			continue;
1387 
1388 		/*
1389 		 * Work out the width of this line. at is the point at which
1390 		 * the available width is hit, and width is the full line
1391 		 * width.
1392 		 */
1393 		at = width = 0;
1394 		if (~gl->flags & GRID_LINE_EXTENDED) {
1395 			width = gl->cellused;
1396 			if (width > sx)
1397 				at = sx;
1398 			else
1399 				at = width;
1400 		} else {
1401 			for (i = 0; i < gl->cellused; i++) {
1402 				grid_get_cell1(gl, i, &gc);
1403 				if (at == 0 && width + gc.data.width > sx)
1404 					at = i;
1405 				width += gc.data.width;
1406 			}
1407 		}
1408 
1409 		/*
1410 		 * If the line is exactly right, just move it across
1411 		 * unchanged.
1412 		 */
1413 		if (width == sx) {
1414 			grid_reflow_move(target, gl);
1415 			continue;
1416 		}
1417 
1418 		/*
1419 		 * If the line is too big, it needs to be split, whether or not
1420 		 * it was previously wrapped.
1421 		 */
1422 		if (width > sx) {
1423 			grid_reflow_split(target, gd, sx, yy, at);
1424 			continue;
1425 		}
1426 
1427 		/*
1428 		 * If the line was previously wrapped, join as much as possible
1429 		 * of the next line.
1430 		 */
1431 		if (gl->flags & GRID_LINE_WRAPPED)
1432 			grid_reflow_join(target, gd, sx, yy, width, 0);
1433 		else
1434 			grid_reflow_move(target, gl);
1435 	}
1436 
1437 	/*
1438 	 * Replace the old grid with the new.
1439 	 */
1440 	if (target->sy < gd->sy)
1441 		grid_reflow_add(target, gd->sy - target->sy);
1442 	gd->hsize = target->sy - gd->sy;
1443 	if (gd->hscrolled > gd->hsize)
1444 		gd->hscrolled = gd->hsize;
1445 	free(gd->linedata);
1446 	gd->linedata = target->linedata;
1447 	free(target);
1448 }
1449 
1450 /* Convert to position based on wrapped lines. */
1451 void
1452 grid_wrap_position(struct grid *gd, u_int px, u_int py, u_int *wx, u_int *wy)
1453 {
1454 	u_int	ax = 0, ay = 0, yy;
1455 
1456 	for (yy = 0; yy < py; yy++) {
1457 		if (gd->linedata[yy].flags & GRID_LINE_WRAPPED)
1458 			ax += gd->linedata[yy].cellused;
1459 		else {
1460 			ax = 0;
1461 			ay++;
1462 		}
1463 	}
1464 	if (px >= gd->linedata[yy].cellused)
1465 		ax = UINT_MAX;
1466 	else
1467 		ax += px;
1468 	*wx = ax;
1469 	*wy = ay;
1470 }
1471 
1472 /* Convert position based on wrapped lines back. */
1473 void
1474 grid_unwrap_position(struct grid *gd, u_int *px, u_int *py, u_int wx, u_int wy)
1475 {
1476 	u_int	yy, ay = 0;
1477 
1478 	for (yy = 0; yy < gd->hsize + gd->sy - 1; yy++) {
1479 		if (ay == wy)
1480 			break;
1481 		if (~gd->linedata[yy].flags & GRID_LINE_WRAPPED)
1482 			ay++;
1483 	}
1484 
1485 	/*
1486 	 * yy is now 0 on the unwrapped line which contains wx. Walk forwards
1487 	 * until we find the end or the line now containing wx.
1488 	 */
1489 	if (wx == UINT_MAX) {
1490 		while (gd->linedata[yy].flags & GRID_LINE_WRAPPED)
1491 			yy++;
1492 		wx = gd->linedata[yy].cellused;
1493 	} else {
1494 		while (gd->linedata[yy].flags & GRID_LINE_WRAPPED) {
1495 			if (wx < gd->linedata[yy].cellused)
1496 				break;
1497 			wx -= gd->linedata[yy].cellused;
1498 			yy++;
1499 		}
1500 	}
1501 	*px = wx;
1502 	*py = yy;
1503 }
1504 
1505 /* Get length of line. */
1506 u_int
1507 grid_line_length(struct grid *gd, u_int py)
1508 {
1509 	struct grid_cell	gc;
1510 	u_int			px;
1511 
1512 	px = grid_get_line(gd, py)->cellsize;
1513 	if (px > gd->sx)
1514 		px = gd->sx;
1515 	while (px > 0) {
1516 		grid_get_cell(gd, px - 1, py, &gc);
1517 		if ((gc.flags & GRID_FLAG_PADDING) ||
1518 		    gc.data.size != 1 ||
1519 		    *gc.data.data != ' ')
1520 			break;
1521 		px--;
1522 	}
1523 	return (px);
1524 }
1525