#define _GNU_SOURCE
#include <glib.h>
#include <math.h>
#include <stdlib.h>
#include <string.h>
#include <xkbcommon/xkbcommon.h>
#include "c8ui-private.h"
#include "text-private.h"

/* Multi-line text: one Pango layout of the whole text, kept until the text
 * or the width changes, and drawn a line at a time so only what shows is
 * drawn. */

#define FRAME_PAD_X 8
#define FRAME_PAD_Y 6
#define FRAME_BORDER 2
#define BLINK_MS 530
#define MULTI_CLICK_SLOP 4

/* One step to undo: the text at pos was old and became new */
enum edit_kind {
	EDIT_OTHER,
	EDIT_TYPE,
	EDIT_BACKSPACE,
	EDIT_DELETE,
};

/* Rich text is cut into runs, each in one format. Every format is kept
 * once in the view's fmts (0 is the plain one) and runs point at them */
struct fmt {
	char *family;
	double size; // points, 0: the view's
	uint32_t color;
	bool has_color;
	bool bold, italic, underline, strike;
};

struct run {
	size_t len;
	int fmt;
};

struct runs {
	struct run *items;
	int count, cap;
};

struct edit {
	size_t pos;
	char *old, *new;
	size_t cursor, anchor; // before it
	enum edit_kind kind;
	int group; // edits made as one step share it
	/* Rich: the runs before a group's first edit, and after its last
	 * (kept on that one when it's undone, for redoing) */
	struct runs before, after;
	bool has_before, has_after;
};

struct edits {
	struct edit *items;
	int count, cap;
};

struct paste {
	struct c8ui_widget *w; // NULL once it's gone or a newer paste came
};

struct textview {
	GString *text;
	size_t cursor, anchor;
	double want_x; // where Up and Down aim, or -1: from the caret
	double xoff; // sideways scroll when not wrapping

	bool editable, wrap, framed, accepts_tab;
	char *family, *placeholder;
	double size;

	PangoLayout *layout;
	double layout_width; // what it was made for, -1: unwrapped
	bool layout_stale;
	bool reveal_pending; // show the caret once laid out

	struct edits undo, redo;
	int group, next_group;
	int saved; // undo.count when unmodified, -1: it can't come back
	bool merge_blocked;

	bool caret_on;
	void *blink;
	struct c8ui_root *blink_root;
	int64_t last_click;
	double click_x, click_y;
	int clicks;
	size_t drag_start, drag_end; // the word or line a multi-click took

	struct paste *paste;
	c8ui_action_fn change_fn;
	void *change_data;
	c8ui_action_fn move_fn;
	void *move_data;

	bool rich;
	struct fmt *fmts;
	int nfmts;
	struct runs runs; // add up to the text's length
	int typing; // a format chosen with nothing selected,
	bool typing_set; // until the caret moves
};

/* Formats */

static void runs_push(struct runs *r, size_t len, int fmt) {
	if (len == 0) {
		return;
	}
	if (r->count > 0 && r->items[r->count - 1].fmt == fmt) {
		r->items[r->count - 1].len += len;
		return;
	}
	if (r->count == r->cap) {
		r->cap = r->cap ? r->cap * 2 : 16;
		r->items = realloc(r->items, sizeof(*r->items) * r->cap);
	}
	r->items[r->count++] = (struct run){ len, fmt };
}

static void runs_free(struct runs *r) {
	free(r->items);
	*r = (struct runs){ 0 };
}

static struct runs runs_copy(const struct runs *r) {
	struct runs c = { 0 };
	for (int i = 0; i < r->count; i++) {
		runs_push(&c, r->items[i].len, r->items[i].fmt);
	}
	return c;
}

/* Bytes a to b taken out, and len bytes of fmt put in their place */
static void runs_splice(struct runs *r, size_t a, size_t b, size_t len,
		int fmt) {
	struct runs out = { 0 };
	size_t pos = 0;
	for (int i = 0; i < r->count; i++) {
		size_t s = pos, e = pos + r->items[i].len;
		if (s < a) {
			runs_push(&out, MIN(e, a) - s, r->items[i].fmt);
		}
		pos = e;
	}
	runs_push(&out, len, fmt);
	pos = 0;
	for (int i = 0; i < r->count; i++) {
		size_t s = pos, e = pos + r->items[i].len;
		if (e > b) {
			runs_push(&out, e - MAX(s, b), r->items[i].fmt);
		}
		pos = e;
	}
	runs_free(r);
	*r = out;
}

static bool same_str(const char *a, const char *b) {
	return a == b || (a && b && strcmp(a, b) == 0);
}

static int fmt_intern(struct textview *tv, const struct fmt *f) {
	for (int i = 0; i < tv->nfmts; i++) {
		struct fmt *o = &tv->fmts[i];
		if (same_str(o->family, f->family) && o->size == f->size &&
				o->has_color == f->has_color &&
				(!f->has_color || o->color == f->color) &&
				o->bold == f->bold && o->italic == f->italic &&
				o->underline == f->underline && o->strike == f->strike) {
			return i;
		}
	}
	tv->fmts = realloc(tv->fmts, sizeof(*tv->fmts) * (tv->nfmts + 1));
	struct fmt *n = &tv->fmts[tv->nfmts];
	*n = *f;
	n->family = c8ui_dup_or_null(f->family);
	if (!n->has_color) {
		n->color = 0;
	}
	return tv->nfmts++;
}

/* fmt with the fields in mask taken from f */
static int fmt_merge(struct textview *tv, int fmt,
		const struct c8ui_text_format *f, unsigned mask) {
	struct fmt m = tv->fmts[fmt];
	if (mask & C8UI_FORMAT_FAMILY) {
		m.family = f->family && f->family[0] ? (char *)f->family : NULL;
	}
	if (mask & C8UI_FORMAT_SIZE) {
		m.size = f->size > 0 ? f->size : 0;
	}
	if (mask & C8UI_FORMAT_COLOR) {
		m.has_color = f->has_color;
		m.color = f->color & 0xffffff;
	}
	if (mask & C8UI_FORMAT_BOLD) {
		m.bold = f->bold;
	}
	if (mask & C8UI_FORMAT_ITALIC) {
		m.italic = f->italic;
	}
	if (mask & C8UI_FORMAT_UNDERLINE) {
		m.underline = f->underline;
	}
	if (mask & C8UI_FORMAT_STRIKE) {
		m.strike = f->strike;
	}
	return fmt_intern(tv, &m);
}

/* The format of the character at byte i (the last one past the end) */
static int fmt_at(struct textview *tv, size_t i) {
	size_t pos = 0;
	for (int k = 0; k < tv->runs.count; k++) {
		pos += tv->runs.items[k].len;
		if (i < pos) {
			return tv->runs.items[k].fmt;
		}
	}
	return tv->runs.count ? tv->runs.items[tv->runs.count - 1].fmt : 0;
}

/* What text typed over bytes a to b gets */
static int fmt_for(struct textview *tv, size_t a, size_t b) {
	if (tv->typing_set && a == b) {
		return tv->typing;
	}
	return a < b || a == 0 ? fmt_at(tv, a) : fmt_at(tv, a - 1);
}

static void fmt_public(const struct fmt *f, struct c8ui_text_format *out) {
	*out = (struct c8ui_text_format){
		.family = f->family, .size = f->size, .color = f->color,
		.has_color = f->has_color, .bold = f->bold, .italic = f->italic,
		.underline = f->underline, .strike = f->strike,
	};
}

/* The text as one plain run, formats forgotten */
static void runs_reset(struct textview *tv) {
	runs_free(&tv->runs);
	for (int i = 1; i < tv->nfmts; i++) {
		free(tv->fmts[i].family);
	}
	if (tv->nfmts == 0) {
		tv->fmts = calloc(1, sizeof(*tv->fmts));
	}
	tv->nfmts = 1;
	tv->typing_set = false;
	runs_push(&tv->runs, tv->text->len, 0);
}

static void add_attr(PangoAttrList *list, PangoAttribute *attr, size_t s,
		size_t e) {
	attr->start_index = (guint)s;
	attr->end_index = (guint)e;
	pango_attr_list_insert(list, attr);
}

static void apply_formats(struct textview *tv, PangoLayout *layout) {
	PangoAttrList *list = pango_attr_list_new();
	size_t pos = 0;
	for (int i = 0; i < tv->runs.count; i++) {
		struct fmt *f = &tv->fmts[tv->runs.items[i].fmt];
		size_t s = pos, e = pos + tv->runs.items[i].len;
		pos = e;
		if (f->bold) {
			add_attr(list, pango_attr_weight_new(PANGO_WEIGHT_BOLD), s, e);
		}
		if (f->italic) {
			add_attr(list, pango_attr_style_new(PANGO_STYLE_ITALIC), s, e);
		}
		if (f->underline) {
			add_attr(list, pango_attr_underline_new(PANGO_UNDERLINE_SINGLE),
				s, e);
		}
		if (f->strike) {
			add_attr(list, pango_attr_strikethrough_new(TRUE), s, e);
		}
		if (f->family) {
			add_attr(list, pango_attr_family_new(f->family), s, e);
		}
		if (f->size > 0) {
			add_attr(list, pango_attr_size_new_absolute(
				(int)(f->size * 96 / 72 * PANGO_SCALE)), s, e);
		}
		if (f->has_color) {
			add_attr(list, pango_attr_foreground_new(
				((f->color >> 16) & 0xff) * 257,
				((f->color >> 8) & 0xff) * 257,
				(f->color & 0xff) * 257), s, e);
		}
	}
	pango_layout_set_attributes(layout, list);
	pango_attr_list_unref(list);
}

/* Geometry */

static struct c8ui_font view_font(struct textview *tv) {
	struct c8ui_font f = c8ui_text_font(C8UI_TEXT_BODY);
	if (tv->size > 0) {
		f.size = tv->size;
	}
	return f;
}

static const char *view_family(struct c8ui_widget *w) {
	struct textview *tv = w->data;
	return tv->family ? tv->family : c8ui_widget_font(w);
}

static double pad_x(struct textview *tv) {
	return tv->framed ? FRAME_PAD_X : 0;
}

static double pad_y(struct textview *tv) {
	return tv->framed ? FRAME_PAD_Y : 0;
}

static PangoLayout *get_layout(struct c8ui_widget *w, double inner) {
	struct textview *tv = w->data;
	double width = tv->wrap ? (inner > 1 ? inner : 1) : -1;
	if (tv->layout && !tv->layout_stale && tv->layout_width == width) {
		return tv->layout;
	}
	if (tv->layout) {
		g_object_unref(tv->layout);
	}
	tv->layout = c8ui_text_layout(c8ui_measure_cr(), view_family(w),
		view_font(tv), tv->text->str, width > 0 ? width : 0, 0);
	/* Every line, none cut short */
	pango_layout_set_ellipsize(tv->layout, PANGO_ELLIPSIZE_NONE);
	pango_layout_set_height(tv->layout, -1);
	if (tv->rich) {
		apply_formats(tv, tv->layout);
	}
	tv->layout_width = width;
	tv->layout_stale = false;
	return tv->layout;
}

static double inner_width(struct c8ui_widget *w) {
	return w->rect.width - 2 * pad_x(w->data);
}

/* The layout for the width it has now */
static PangoLayout *layout_now(struct c8ui_widget *w) {
	return get_layout(w, inner_width(w));
}

static double text_x(struct c8ui_widget *w) {
	struct textview *tv = w->data;
	return w->rect.x + pad_x(tv) - tv->xoff;
}

static double text_y(struct c8ui_widget *w) {
	return w->rect.y + pad_y(w->data);
}

static double line_height(struct c8ui_widget *w) {
	PangoLayout *layout = layout_now(w);
	PangoLayoutIter *it = pango_layout_get_iter(layout);
	int y0, y1;
	pango_layout_iter_get_line_yrange(it, &y0, &y1);
	pango_layout_iter_free(it);
	return (double)(y1 - y0) / PANGO_SCALE;
}

static struct c8ui_rect caret_rect(struct c8ui_widget *w, size_t index) {
	PangoRectangle strong;
	pango_layout_get_cursor_pos(layout_now(w), (int)index, &strong, NULL);
	return (struct c8ui_rect){
		text_x(w) + (double)strong.x / PANGO_SCALE,
		text_y(w) + (double)strong.y / PANGO_SCALE,
		1, (double)strong.height / PANGO_SCALE,
	};
}

/* Byte index nearest to a point in root coordinates */
static size_t index_at(struct c8ui_widget *w, double x, double y) {
	struct textview *tv = w->data;
	PangoLayout *layout = layout_now(w);
	int index, trailing;
	double lx = x - text_x(w), ly = y - text_y(w);
	if (ly < 0) {
		ly = 0;
	}
	pango_layout_xy_to_index(layout, (int)(lx * PANGO_SCALE),
		(int)(ly * PANGO_SCALE), &index, &trailing);
	const char *p = tv->text->str + index;
	while (trailing-- > 0 && *p) {
		p = g_utf8_next_char(p);
	}
	return (size_t)(p - tv->text->str);
}

static void reveal_caret(struct c8ui_widget *w) {
	struct textview *tv = w->data;
	tv->reveal_pending = false;
	if (w->rect.width <= 0) {
		return;
	}
	if (!tv->wrap) {
		/* Sideways, ourselves */
		double inner = inner_width(w);
		PangoRectangle pos;
		pango_layout_get_cursor_pos(layout_now(w), (int)tv->cursor, &pos,
			NULL);
		double cx = (double)pos.x / PANGO_SCALE;
		double margin = inner > 120 ? 40 : 0;
		if (cx - tv->xoff > inner - 2) {
			tv->xoff = cx - inner + 2 + margin;
		} else if (cx < tv->xoff) {
			tv->xoff = cx - margin > 0 ? cx - margin : 0;
		}
	}
	struct c8ui_rect r = caret_rect(w, tv->cursor);
	c8ui_widget_reveal(w, &r);
}

/* Edits and undo */

static void edit_free(struct edit *e) {
	free(e->old);
	free(e->new);
	runs_free(&e->before);
	runs_free(&e->after);
}

static void edits_clear(struct edits *list) {
	for (int i = 0; i < list->count; i++) {
		edit_free(&list->items[i]);
	}
	list->count = 0;
}

static void edits_push(struct edits *list, struct edit e) {
	if (list->count == list->cap) {
		list->cap = list->cap ? list->cap * 2 : 32;
		list->items = realloc(list->items, sizeof(*list->items) * list->cap);
	}
	list->items[list->count++] = e;
}

static void blink_restart(struct c8ui_widget *w);

static void text_changed(struct c8ui_widget *w) {
	struct textview *tv = w->data;
	tv->layout_stale = true;
	tv->want_x = -1;
	tv->reveal_pending = true;
	blink_restart(w);
	c8ui_widget_queue_layout(w);
	if (tv->change_fn) {
		tv->change_fn(w, tv->change_data);
	}
}

/* Replaces bytes a to b with ins, keeping it to undo */
static void replace(struct c8ui_widget *w, size_t a, size_t b, const char *ins,
		enum edit_kind kind) {
	struct textview *tv = w->data;
	if (a == b && ins[0] == '\0') {
		return;
	}
	int fmt = tv->rich ? fmt_for(tv, a, b) : 0;
	char *old = g_strndup(tv->text->str + a, b - a);
	struct edit *last = tv->undo.count ? &tv->undo.items[tv->undo.count - 1] :
		NULL;
	bool merge = last && kind != EDIT_OTHER && last->kind == kind &&
		!tv->merge_blocked && tv->undo.count != tv->saved;
	if (merge && kind == EDIT_TYPE) {
		/* Typing runs on; a new line starts a new step */
		merge = a == b && a == last->pos + strlen(last->new) &&
			ins[0] != '\n' && !strchr(last->new, '\n');
	} else if (merge && kind == EDIT_BACKSPACE) {
		merge = ins[0] == '\0' && b == last->pos && last->new[0] == '\0';
	} else if (merge && kind == EDIT_DELETE) {
		merge = ins[0] == '\0' && a == last->pos && last->new[0] == '\0';
	}
	if (merge) {
		if (kind == EDIT_TYPE) {
			char *s = g_strconcat(last->new, ins, NULL);
			free(last->new);
			last->new = s;
		} else if (kind == EDIT_BACKSPACE) {
			char *s = g_strconcat(old, last->old, NULL);
			free(last->old);
			last->old = s;
			last->pos = a;
		} else {
			char *s = g_strconcat(last->old, old, NULL);
			free(last->old);
			last->old = s;
		}
		free(old);
	} else {
		if (tv->saved > tv->undo.count) {
			tv->saved = -1; // its future is about to be dropped
		}
		struct edit e = {
			.pos = a, .old = old, .new = strdup(ins),
			.cursor = tv->cursor, .anchor = tv->anchor,
			.kind = kind,
			.group = tv->group ? tv->group : ++tv->next_group,
		};
		/* A group's runs are kept once, before its first edit */
		if (tv->rich && (last == NULL || last->group != e.group)) {
			e.before = runs_copy(&tv->runs);
			e.has_before = true;
		}
		edits_push(&tv->undo, e);
	}
	tv->merge_blocked = false;
	edits_clear(&tv->redo);
	g_string_erase(tv->text, a, b - a);
	g_string_insert(tv->text, a, ins);
	if (tv->rich) {
		runs_splice(&tv->runs, a, b, strlen(ins), fmt);
	}
	tv->typing_set = false;
	tv->cursor = tv->anchor = a + strlen(ins);
}

static void group_begin(struct textview *tv) {
	tv->group = ++tv->next_group;
}

static void group_end(struct textview *tv) {
	tv->group = 0;
	tv->merge_blocked = true;
}

static size_t sel_start(struct textview *tv) {
	return MIN(tv->cursor, tv->anchor);
}

static size_t sel_end(struct textview *tv) {
	return MAX(tv->cursor, tv->anchor);
}

static void type(struct c8ui_widget *w, const char *ins, enum edit_kind kind) {
	struct textview *tv = w->data;
	bool sel = tv->cursor != tv->anchor;
	replace(w, sel_start(tv), sel_end(tv), ins,
		sel ? EDIT_OTHER : kind);
	if (sel) {
		tv->merge_blocked = true;
	}
	text_changed(w);
}

/* Takes one step (a group of edits) from one list, applies it backwards or
 * forwards, and puts it on the other */
static bool step(struct c8ui_widget *w, bool undo) {
	struct textview *tv = w->data;
	struct edits *from = undo ? &tv->undo : &tv->redo;
	struct edits *to = undo ? &tv->redo : &tv->undo;
	if (from->count == 0) {
		return false;
	}
	int group = from->items[from->count - 1].group;
	struct runs now = tv->rich ? runs_copy(&tv->runs) : (struct runs){ 0 };
	int first = to->count; // where the first one taken lands
	while (from->count > 0 && from->items[from->count - 1].group == group) {
		struct edit e = from->items[--from->count];
		const char *gone = undo ? e.new : e.old;
		const char *back = undo ? e.old : e.new;
		g_string_erase(tv->text, e.pos, strlen(gone));
		g_string_insert(tv->text, e.pos, back);
		if (undo) {
			tv->cursor = e.cursor;
			tv->anchor = e.anchor;
		} else {
			tv->cursor = tv->anchor = e.pos + strlen(back);
		}
		edits_push(to, e);
	}
	/* The group lands on the other list upside down, its first edit on
	 * top: the order to replay it in */
	if (tv->rich) {
		/* Undone, the runs go back to before its first edit (taken
		 * last) and what they were is kept on its last (taken first);
		 * redone, the other way round */
		struct edit *last = &to->items[to->count - 1];
		struct edit *keep = &to->items[first];
		const struct runs *back = undo ?
			(last->has_before ? &last->before : NULL) :
			(last->has_after ? &last->after : NULL);
		if (back) {
			struct runs r = runs_copy(back);
			runs_free(&tv->runs);
			tv->runs = r;
		}
		if (undo) {
			runs_free(&keep->after);
			keep->after = now;
			keep->has_after = true;
		} else {
			runs_free(&now);
		}
	}
	tv->typing_set = false;
	tv->merge_blocked = true;
	if (tv->cursor > tv->text->len) {
		tv->cursor = tv->text->len;
	}
	if (tv->anchor > tv->text->len) {
		tv->anchor = tv->text->len;
	}
	text_changed(w);
	return true;
}

/* Moving */

static size_t prev_char(struct textview *tv, size_t i) {
	return i == 0 ? 0 : (size_t)(g_utf8_prev_char(tv->text->str + i) -
		tv->text->str);
}

static size_t next_char(struct textview *tv, size_t i) {
	return i >= tv->text->len ? tv->text->len :
		(size_t)(g_utf8_next_char(tv->text->str + i) - tv->text->str);
}

static bool is_word_at(struct textview *tv, size_t i) {
	gunichar c = g_utf8_get_char(tv->text->str + i);
	return g_unichar_isalnum(c) || c == '_';
}

static size_t word_left(struct textview *tv, size_t i) {
	while (i > 0 && !is_word_at(tv, prev_char(tv, i))) {
		i = prev_char(tv, i);
	}
	while (i > 0 && is_word_at(tv, prev_char(tv, i))) {
		i = prev_char(tv, i);
	}
	return i;
}

static size_t word_right(struct textview *tv, size_t i) {
	size_t len = tv->text->len;
	while (i < len && !is_word_at(tv, i)) {
		i = next_char(tv, i);
	}
	while (i < len && is_word_at(tv, i)) {
		i = next_char(tv, i);
	}
	return i;
}

static size_t paragraph_start(struct textview *tv, size_t i) {
	while (i > 0 && tv->text->str[i - 1] != '\n') {
		i--;
	}
	return i;
}

static size_t paragraph_end(struct textview *tv, size_t i) {
	while (i < tv->text->len && tv->text->str[i] != '\n') {
		i++;
	}
	return i;
}

/* Start and end of the line as shown (wrapped) */
static void visual_line(struct c8ui_widget *w, size_t i, size_t *start,
		size_t *end) {
	PangoLayout *layout = layout_now(w);
	int line, x;
	pango_layout_index_to_line_x(layout, (int)i, 0, &line, &x);
	PangoLayoutLine *l = pango_layout_get_line_readonly(layout, line);
	*start = (size_t)l->start_index;
	*end = (size_t)(l->start_index + l->length);
	/* A wrapped line ends in the space it broke at: stop before it, or
	 * the caret would show at the start of the next */
	struct textview *tv = w->data;
	if (*end > *start && *end < tv->text->len &&
			tv->text->str[*end - 1] == ' ' &&
			line + 1 < pango_layout_get_line_count(layout)) {
		*end = prev_char(tv, *end);
	}
}

/* The index a line up or down (dir), at the x Up and Down aim for */
static size_t vertical(struct c8ui_widget *w, size_t i, double lines) {
	struct textview *tv = w->data;
	struct c8ui_rect r = caret_rect(w, i);
	if (tv->want_x < 0) {
		tv->want_x = r.x - text_x(w);
	}
	double y = r.y + r.height / 2 + lines * r.height;
	if (y < text_y(w)) {
		return 0;
	}
	int lw, lh;
	pango_layout_get_size(layout_now(w), &lw, &lh);
	if (y > text_y(w) + (double)lh / PANGO_SCALE) {
		return tv->text->len;
	}
	return index_at(w, text_x(w) + tv->want_x, y);
}

static double page_lines(struct c8ui_widget *w) {
	double h = 0;
	for (struct c8ui_widget *p = w->parent; p; p = p->parent) {
		if (p->impl->clips) {
			h = p->rect.height;
			break;
		}
	}
	if (h <= 0) {
		h = w->rect.height;
	}
	double lh = line_height(w);
	double n = lh > 0 ? floor(h / lh) - 1 : 10;
	return n < 1 ? 1 : n;
}

/* Clipboard */

static void copy(struct c8ui_widget *w) {
	struct textview *tv = w->data;
	if (tv->cursor == tv->anchor || w->root == NULL) {
		return;
	}
	char *s = g_strndup(tv->text->str + sel_start(tv),
		sel_end(tv) - sel_start(tv));
	c8ui_root_set_clipboard(w->root, s);
	g_free(s);
}

static void pasted(void *data, const char *text) {
	struct paste *p = data;
	struct c8ui_widget *w = p->w;
	free(p);
	if (w == NULL) {
		return;
	}
	struct textview *tv = w->data;
	tv->paste = NULL;
	if (text && text[0] && tv->editable) {
		/* Line ends as typed */
		GString *clean = g_string_new(NULL);
		for (const char *s = text; *s; s++) {
			if (*s == '\r') {
				if (s[1] != '\n') {
					g_string_append_c(clean, '\n');
				}
				continue;
			}
			g_string_append_c(clean, *s);
		}
		type(w, clean->str, EDIT_OTHER);
		tv->merge_blocked = true;
		g_string_free(clean, TRUE);
	}
}

static void paste(struct c8ui_widget *w) {
	struct textview *tv = w->data;
	if (w->root == NULL || w->root->impl->request_paste == NULL) {
		return;
	}
	if (tv->paste) {
		tv->paste->w = NULL;
	}
	tv->paste = calloc(1, sizeof(*tv->paste));
	tv->paste->w = w;
	c8ui_root_request_paste(w->root, pasted, tv->paste);
}

/* Caret blink */

static int blink(void *data) {
	struct c8ui_widget *w = data;
	struct textview *tv = w->data;
	tv->caret_on = !tv->caret_on;
	c8ui_widget_queue_draw(w);
	return BLINK_MS;
}

static void blink_restart(struct c8ui_widget *w) {
	struct textview *tv = w->data;
	tv->caret_on = true;
	if (tv->blink) {
		c8ui_root_timer_remove(tv->blink_root, tv->blink);
		tv->blink = NULL;
	}
	if (w->focused && w->root && tv->editable) {
		tv->blink_root = w->root;
		tv->blink = c8ui_root_timer_add(w->root, BLINK_MS, blink, w);
	}
}

/* Keys */

static void tell_moved(struct c8ui_widget *w) {
	struct textview *tv = w->data;
	tv->typing_set = false;
	if (tv->move_fn) {
		tv->move_fn(w, tv->move_data);
	}
}

static void moved(struct c8ui_widget *w) {
	blink_restart(w);
	reveal_caret(w);
	c8ui_widget_queue_draw(w);
	tell_moved(w);
}

static bool key(struct c8ui_widget *w, const struct c8ui_event *ev) {
	struct textview *tv = w->data;
	bool shift = ev->mods & C8UI_MOD_SHIFT;
	bool ctrl = ev->mods & C8UI_MOD_CTRL;
	bool other = ev->mods & (C8UI_MOD_ALT | C8UI_MOD_SUPER);
	bool sel = tv->cursor != tv->anchor;
	size_t to = tv->cursor;
	bool keep_x = false;
	if (other) {
		return false;
	}

	switch (ev->sym) {
	case XKB_KEY_Left:
		to = !shift && sel ? sel_start(tv) :
			ctrl ? word_left(tv, tv->cursor) : prev_char(tv, tv->cursor);
		break;
	case XKB_KEY_Right:
		to = !shift && sel ? sel_end(tv) :
			ctrl ? word_right(tv, tv->cursor) : next_char(tv, tv->cursor);
		break;
	case XKB_KEY_Up:
	case XKB_KEY_Down:
		if (ctrl) {
			return false; // the scroll's
		}
		to = vertical(w, tv->cursor, ev->sym == XKB_KEY_Up ? -1 : 1);
		keep_x = true;
		break;
	case XKB_KEY_Page_Up:
	case XKB_KEY_Page_Down: {
		double n = page_lines(w);
		to = vertical(w, tv->cursor, ev->sym == XKB_KEY_Page_Up ? -n : n);
		keep_x = true;
		break;
	}
	case XKB_KEY_Home:
	case XKB_KEY_End: {
		if (ctrl) {
			to = ev->sym == XKB_KEY_Home ? 0 : tv->text->len;
			break;
		}
		size_t start, end;
		visual_line(w, tv->cursor, &start, &end);
		if (ev->sym == XKB_KEY_End) {
			to = end;
			break;
		}
		/* Home goes to the indent first, then the very start */
		size_t indent = start;
		while (indent < end && (tv->text->str[indent] == ' ' ||
				tv->text->str[indent] == '\t')) {
			indent++;
		}
		to = tv->cursor == indent ? start : indent;
		break;
	}
	case XKB_KEY_BackSpace:
		if (!tv->editable) {
			return false;
		}
		if (!sel) {
			tv->anchor = ctrl ? word_left(tv, tv->cursor) :
				prev_char(tv, tv->cursor);
			if (tv->anchor == tv->cursor) {
				return true;
			}
			replace(w, tv->anchor, tv->cursor, "", EDIT_BACKSPACE);
			text_changed(w);
			return true;
		}
		type(w, "", EDIT_OTHER);
		return true;
	case XKB_KEY_Delete:
		if (!tv->editable) {
			return false;
		}
		if (!sel) {
			tv->anchor = ctrl ? word_right(tv, tv->cursor) :
				next_char(tv, tv->cursor);
			if (tv->anchor == tv->cursor) {
				return true;
			}
			replace(w, tv->cursor, tv->anchor, "", EDIT_DELETE);
			text_changed(w);
			return true;
		}
		type(w, "", EDIT_OTHER);
		return true;
	case XKB_KEY_Return:
	case XKB_KEY_KP_Enter:
		if (!tv->editable || ctrl) {
			return false;
		}
		type(w, "\n", EDIT_TYPE);
		return true;
	case XKB_KEY_Tab:
	case XKB_KEY_ISO_Left_Tab:
		if (!tv->editable || !tv->accepts_tab || ctrl || shift) {
			return false;
		}
		type(w, "\t", EDIT_TYPE);
		return true;
	default:
		if (ctrl) {
			switch (ev->base_sym) {
			case XKB_KEY_a:
				tv->anchor = 0;
				tv->cursor = tv->text->len;
				c8ui_widget_queue_draw(w);
				tell_moved(w);
				return true;
			case XKB_KEY_c:
				copy(w);
				return true;
			case XKB_KEY_x:
				copy(w);
				if (tv->editable && sel) {
					type(w, "", EDIT_OTHER);
				}
				return true;
			case XKB_KEY_v:
				if (tv->editable) {
					paste(w);
				}
				return true;
			case XKB_KEY_z:
				if (tv->editable) {
					step(w, !shift);
				}
				return true;
			case XKB_KEY_y:
				if (tv->editable) {
					step(w, false);
				}
				return true;
			}
			return false;
		}
		if (tv->editable && ev->text &&
				(unsigned char)ev->text[0] >= 0x20 && ev->text[0] != 0x7f) {
			type(w, ev->text, EDIT_TYPE);
			return true;
		}
		return false;
	}
	tv->cursor = to;
	if (!shift) {
		tv->anchor = to;
	}
	if (!keep_x) {
		tv->want_x = -1;
	}
	tv->merge_blocked = true;
	moved(w);
	return true;
}

/* Pointer */

static void select_unit(struct c8ui_widget *w, size_t i, int clicks,
		size_t *start, size_t *end) {
	struct textview *tv = w->data;
	if (clicks == 2) {
		if (i < tv->text->len && is_word_at(tv, i)) {
			*start = word_left(tv, next_char(tv, i));
			*end = word_right(tv, i);
		} else {
			*start = i;
			*end = next_char(tv, i);
		}
	} else {
		*start = paragraph_start(tv, i);
		*end = paragraph_end(tv, i);
		if (*end < tv->text->len) {
			(*end)++; // the line with its break
		}
	}
}

static void press(struct c8ui_widget *w, const struct c8ui_event *ev) {
	struct textview *tv = w->data;
	int64_t now = c8ui_now_ms();
	if (now - tv->last_click < C8UI_MULTI_CLICK_MS &&
			fabs(ev->x - tv->click_x) < MULTI_CLICK_SLOP &&
			fabs(ev->y - tv->click_y) < MULTI_CLICK_SLOP) {
		tv->clicks = tv->clicks % 3 + 1;
	} else {
		tv->clicks = 1;
	}
	tv->last_click = now;
	tv->click_x = ev->x;
	tv->click_y = ev->y;
	size_t i = index_at(w, ev->x, ev->y);
	if (tv->clicks == 1) {
		tv->cursor = i;
		if (!(ev->mods & C8UI_MOD_SHIFT)) {
			tv->anchor = i;
		}
	} else {
		select_unit(w, i, tv->clicks, &tv->drag_start, &tv->drag_end);
		tv->anchor = tv->drag_start;
		tv->cursor = tv->drag_end;
	}
	tv->want_x = -1;
	tv->merge_blocked = true;
	moved(w);
}

static void drag(struct c8ui_widget *w, const struct c8ui_event *ev) {
	struct textview *tv = w->data;
	size_t i = index_at(w, ev->x, ev->y);
	if (tv->clicks > 1) {
		/* Whole words or lines, from the one clicked */
		size_t start, end;
		select_unit(w, i, tv->clicks, &start, &end);
		if (start < tv->drag_start) {
			tv->anchor = tv->drag_end;
			tv->cursor = start;
		} else {
			tv->anchor = tv->drag_start;
			tv->cursor = MAX(end, tv->drag_end);
		}
	} else {
		tv->cursor = i;
	}
	moved(w);
}

/* Widget */

static void tv_measure(struct c8ui_widget *w, double avail, double *width,
		double *height) {
	struct textview *tv = w->data;
	double inner = avail - 2 * pad_x(tv);
	PangoLayout *layout = get_layout(w, inner);
	int lw, lh;
	pango_layout_get_size(layout, &lw, &lh);
	*width = avail;
	*height = ceil((double)lh / PANGO_SCALE) + 2 * pad_y(tv);
}

static void tv_layout(struct c8ui_widget *w) {
	struct textview *tv = w->data;
	if (tv->reveal_pending) {
		reveal_caret(w);
	}
}

/* Rectangles covering bytes a to b, a line at a time */
static void selection_path(struct c8ui_widget *w, cairo_t *cr, size_t a,
		size_t b) {
	struct textview *tv = w->data;
	PangoLayout *layout = layout_now(w);
	PangoLayoutIter *it = pango_layout_get_iter(layout);
	double x0 = text_x(w), y0 = text_y(w);
	do {
		PangoLayoutLine *line = pango_layout_iter_get_line_readonly(it);
		int top, bottom;
		pango_layout_iter_get_line_yrange(it, &top, &bottom);
		size_t ls = (size_t)line->start_index;
		size_t le = ls + (size_t)line->length;
		if (le < a || ls > b) {
			continue;
		}
		int start = (int)MAX(a, ls), end = (int)MIN(b, le);
		PangoRectangle logical;
		pango_layout_iter_get_line_extents(it, NULL, &logical);
		int *ranges, n;
		pango_layout_line_get_x_ranges(line, start, end, &ranges, &n);
		for (int i = 0; i < n; i++) {
			double rx = x0 + (double)ranges[2 * i] / PANGO_SCALE;
			double rw = (double)(ranges[2 * i + 1] - ranges[2 * i]) /
				PANGO_SCALE;
			cairo_rectangle(cr, rx, y0 + (double)top / PANGO_SCALE, rw,
				(double)(bottom - top) / PANGO_SCALE);
		}
		g_free(ranges);
		/* The line break is selected too: a sliver past the end */
		if (b > le && a <= le && tv->text->str[le] == '\n') {
			double ex = x0 + (double)(logical.x + logical.width) / PANGO_SCALE;
			cairo_rectangle(cr, ex, y0 + (double)top / PANGO_SCALE, 6,
				(double)(bottom - top) / PANGO_SCALE);
		}
	} while (pango_layout_iter_next_line(it));
	pango_layout_iter_free(it);
}

/* The lines that show inside the clip, each at its baseline */
static void draw_lines(struct c8ui_widget *w, cairo_t *cr) {
	PangoLayout *layout = layout_now(w);
	double cx0, cy0, cx1, cy1;
	cairo_clip_extents(cr, &cx0, &cy0, &cx1, &cy1);
	double x0 = text_x(w), y0 = text_y(w);
	PangoLayoutIter *it = pango_layout_get_iter(layout);
	do {
		int top, bottom;
		pango_layout_iter_get_line_yrange(it, &top, &bottom);
		double t = y0 + (double)top / PANGO_SCALE;
		double b = y0 + (double)bottom / PANGO_SCALE;
		if (b < cy0) {
			continue;
		}
		if (t > cy1) {
			break;
		}
		PangoRectangle logical;
		pango_layout_iter_get_line_extents(it, NULL, &logical);
		double baseline = (double)pango_layout_iter_get_baseline(it) /
			PANGO_SCALE;
		cairo_move_to(cr, x0 + (double)logical.x / PANGO_SCALE,
			y0 + baseline);
		pango_cairo_show_layout_line(cr,
			pango_layout_iter_get_line_readonly(it));
	} while (pango_layout_iter_next_line(it));
	pango_layout_iter_free(it);
	cairo_new_path(cr);
}

static void tv_draw(struct c8ui_widget *w, cairo_t *cr) {
	struct textview *tv = w->data;
	struct c8ui_colors c = c8ui_widget_colors(w);
	struct c8ui_rect r = w->rect;
	uint32_t fg = c.fg;
	double alpha = w->disabled ? 0.5 : 1;

	if (tv->framed) {
		/* White like an entry, darker scheme or not */
		fg = 0x000000;
		double bg_alpha = c.dark && !w->focused ? 0.8 : 1;
		cairo_set_source_rgba(cr, 1, 1, 1, w->disabled ? 0.4 : bg_alpha);
		cairo_rectangle(cr, r.x, r.y, r.width, r.height);
		cairo_fill(cr);
		if (!c.dark) {
			double a = w->focused ? 1 : w->hovered ? c.border_hover : c.border;
			cairo_set_source_rgba(cr, 0, 0, 0, a);
			cairo_set_line_width(cr, FRAME_BORDER);
			cairo_rectangle(cr, r.x + 1, r.y + 1, r.width - 2, r.height - 2);
			cairo_stroke(cr);
		}
	}

	cairo_save(cr);
	double clip_pad = tv->framed ? FRAME_BORDER : 0;
	cairo_rectangle(cr, r.x + clip_pad, r.y + clip_pad, r.width - 2 * clip_pad,
		r.height - 2 * clip_pad);
	cairo_clip(cr);

	if (tv->text->len == 0 && tv->placeholder && !w->focused) {
		c8ui_set_source(cr, fg, 0.45);
		c8ui_text_draw(cr, view_family(w), view_font(tv), tv->placeholder,
			text_x(w), text_y(w), inner_width(w), 0);
		cairo_restore(cr);
		return;
	}

	/* Unfocused, the selection stays in sight as a faint band (a match
	 * found from a find box, which keeps the focus) */
	if (tv->cursor != tv->anchor && !w->focused) {
		selection_path(w, cr, sel_start(tv), sel_end(tv));
		c8ui_set_source(cr, fg, 0.18);
		cairo_fill(cr);
	}

	c8ui_set_source(cr, fg, alpha);
	draw_lines(w, cr);

	if (tv->cursor != tv->anchor && w->focused) {
		cairo_save(cr);
		selection_path(w, cr, sel_start(tv), sel_end(tv));
		cairo_clip_preserve(cr);
		c8ui_set_source(cr, c.accent, 1);
		cairo_fill(cr);
		cairo_set_source_rgb(cr, 1, 1, 1);
		draw_lines(w, cr);
		cairo_restore(cr);
	}

	bool active = w->root && w->root->keyboard_focused;
	if (tv->editable && w->focused && active && tv->caret_on &&
			tv->cursor == tv->anchor) {
		struct c8ui_rect cr_ = caret_rect(w, tv->cursor);
		c8ui_set_source(cr, fg, 1);
		cairo_rectangle(cr, round(cr_.x), cr_.y, 1, cr_.height);
		cairo_fill(cr);
	}
	cairo_restore(cr);
}

static bool tv_event(struct c8ui_widget *w, const struct c8ui_event *ev) {
	struct textview *tv = w->data;
	switch (ev->type) {
	case C8UI_EVENT_PRESS:
		if (ev->button == C8UI_BUTTON_LEFT) {
			press(w, ev);
			return true;
		}
		return false;
	case C8UI_EVENT_MOTION:
		if (w->pressed) {
			drag(w, ev);
		}
		return true;
	case C8UI_EVENT_RELEASE:
		return true;
	case C8UI_EVENT_KEY:
		return key(w, ev);
	case C8UI_EVENT_FOCUS_IN:
	case C8UI_EVENT_FOCUS_OUT:
		tv->merge_blocked = true;
		blink_restart(w);
		c8ui_widget_queue_draw(w);
		return false;
	case C8UI_EVENT_ENTER:
	case C8UI_EVENT_LEAVE:
		if (tv->framed) {
			c8ui_widget_queue_draw(w);
		}
		return false;
	default:
		return false;
	}
}

static void tv_destroy(struct c8ui_widget *w) {
	struct textview *tv = w->data;
	if (tv->blink) {
		c8ui_root_timer_remove(tv->blink_root, tv->blink);
	}
	if (tv->paste) {
		tv->paste->w = NULL;
	}
	if (tv->layout) {
		g_object_unref(tv->layout);
	}
	edits_clear(&tv->undo);
	edits_clear(&tv->redo);
	free(tv->undo.items);
	free(tv->redo.items);
	runs_free(&tv->runs);
	for (int i = 0; i < tv->nfmts; i++) {
		free(tv->fmts[i].family);
	}
	free(tv->fmts);
	g_string_free(tv->text, TRUE);
	free(tv->family);
	free(tv->placeholder);
	free(tv);
}

static const struct c8ui_widget_impl textview_impl = {
	.name = "textview",
	.measure = tv_measure,
	.layout = tv_layout,
	.draw = tv_draw,
	.event = tv_event,
	.destroy = tv_destroy,
};

struct c8ui_widget *c8ui_textview_new(const char *text) {
	struct textview *tv = calloc(1, sizeof(*tv));
	tv->text = g_string_new(text ? text : "");
	tv->editable = tv->wrap = tv->accepts_tab = true;
	tv->want_x = -1;
	tv->layout_width = -2;
	struct c8ui_widget *w = c8ui_widget_new(&textview_impl, tv);
	w->focusable = true;
	w->fill = true;
	w->cursor = C8UI_CURSOR_TEXT;
	return w;
}

const char *c8ui_textview_get(struct c8ui_widget *w) {
	return ((struct textview *)w->data)->text->str;
}

void c8ui_textview_set(struct c8ui_widget *w, const char *text) {
	struct textview *tv = w->data;
	g_string_assign(tv->text, text ? text : "");
	tv->cursor = tv->anchor = 0;
	tv->xoff = 0;
	tv->want_x = -1;
	edits_clear(&tv->undo);
	edits_clear(&tv->redo);
	tv->saved = 0;
	if (tv->rich) {
		runs_reset(tv);
	}
	tv->layout_stale = true;
	c8ui_widget_queue_layout(w);
}

void c8ui_textview_on_change(struct c8ui_widget *w, c8ui_action_fn fn,
		void *data) {
	struct textview *tv = w->data;
	tv->change_fn = fn;
	tv->change_data = data;
}

void c8ui_textview_set_editable(struct c8ui_widget *w, bool editable) {
	struct textview *tv = w->data;
	tv->editable = editable;
	blink_restart(w);
	c8ui_widget_queue_draw(w);
}

void c8ui_textview_set_wrap(struct c8ui_widget *w, bool wrap) {
	struct textview *tv = w->data;
	tv->wrap = wrap;
	tv->xoff = 0;
	tv->layout_stale = true;
	c8ui_widget_queue_layout(w);
}

void c8ui_textview_set_font(struct c8ui_widget *w, const char *family,
		double size) {
	struct textview *tv = w->data;
	free(tv->family);
	tv->family = c8ui_dup_or_null(family);
	tv->size = size;
	tv->layout_stale = true;
	c8ui_widget_queue_layout(w);
}

void c8ui_textview_set_framed(struct c8ui_widget *w, bool framed) {
	struct textview *tv = w->data;
	tv->framed = framed;
	tv->layout_stale = true;
	c8ui_widget_queue_layout(w);
}

void c8ui_textview_set_accepts_tab(struct c8ui_widget *w, bool accepts) {
	((struct textview *)w->data)->accepts_tab = accepts;
}

void c8ui_textview_set_placeholder(struct c8ui_widget *w, const char *text) {
	struct textview *tv = w->data;
	free(tv->placeholder);
	tv->placeholder = c8ui_dup_or_null(text);
	c8ui_widget_queue_draw(w);
}

void c8ui_textview_insert(struct c8ui_widget *w, const char *text) {
	struct textview *tv = w->data;
	tv->merge_blocked = true;
	type(w, text ? text : "", EDIT_OTHER);
	tv->merge_blocked = true;
}

void c8ui_textview_get_selection(struct c8ui_widget *w, size_t *start,
		size_t *end) {
	struct textview *tv = w->data;
	*start = sel_start(tv);
	*end = sel_end(tv);
}

static size_t clamp_index(struct textview *tv, size_t i) {
	if (i > tv->text->len) {
		i = tv->text->len;
	}
	/* Not inside a character */
	while (i > 0 && i < tv->text->len &&
			((unsigned char)tv->text->str[i] & 0xc0) == 0x80) {
		i--;
	}
	return i;
}

void c8ui_textview_select(struct c8ui_widget *w, size_t start, size_t end) {
	struct textview *tv = w->data;
	tv->anchor = clamp_index(tv, start);
	tv->cursor = clamp_index(tv, end);
	tv->want_x = -1;
	tv->merge_blocked = true;
	if (tv->layout_stale || w->rect.width <= 0) {
		tv->reveal_pending = true;
		c8ui_widget_queue_layout(w);
	} else {
		reveal_caret(w);
	}
	c8ui_widget_queue_draw(w);
	tell_moved(w);
}

void c8ui_textview_get_position(struct c8ui_widget *w, int *line,
		int *column) {
	struct textview *tv = w->data;
	int l = 1;
	size_t start = 0;
	for (size_t i = 0; i < tv->cursor; i++) {
		if (tv->text->str[i] == '\n') {
			l++;
			start = i + 1;
		}
	}
	*line = l;
	*column = (int)g_utf8_pointer_to_offset(tv->text->str + start,
		tv->text->str + tv->cursor) + 1;
}

bool c8ui_textview_undo(struct c8ui_widget *w) {
	return step(w, true);
}

bool c8ui_textview_redo(struct c8ui_widget *w) {
	return step(w, false);
}

bool c8ui_textview_is_modified(struct c8ui_widget *w) {
	struct textview *tv = w->data;
	return tv->saved != tv->undo.count;
}

void c8ui_textview_set_unmodified(struct c8ui_widget *w) {
	struct textview *tv = w->data;
	tv->saved = tv->undo.count;
	tv->merge_blocked = true;
}

/* Where a match of needle at i ends, or 0 if there is none */
static size_t match_at(const char *s, size_t i, const char *needle,
		bool match_case) {
	if (match_case) {
		size_t n = strlen(needle);
		return strncmp(s + i, needle, n) == 0 ? i + n : 0;
	}
	const char *p = s + i, *q = needle;
	while (*q) {
		if (*p == '\0' || g_unichar_tolower(g_utf8_get_char(p)) !=
				g_unichar_tolower(g_utf8_get_char(q))) {
			return 0;
		}
		p = g_utf8_next_char(p);
		q = g_utf8_next_char(q);
	}
	return (size_t)(p - s);
}

bool c8ui_textview_find(struct c8ui_widget *w, const char *needle,
		bool backwards, bool match_case) {
	struct textview *tv = w->data;
	if (needle == NULL || needle[0] == '\0') {
		return false;
	}
	const char *s = tv->text->str;
	size_t len = tv->text->len;
	size_t from = backwards ? sel_start(tv) : sel_end(tv);
	/* Round once: from the selection to the end, then the start back to
	 * it (backwards the other way) */
	for (size_t n = 0; n <= len; n++) {
		size_t i;
		if (backwards) {
			i = (from + len + 1 - 1 - n) % (len + 1);
		} else {
			i = (from + n) % (len + 1);
		}
		if (i > 0 && i < len && ((unsigned char)s[i] & 0xc0) == 0x80) {
			continue;
		}
		size_t end = match_at(s, i, needle, match_case);
		if (end) {
			c8ui_textview_select(w, i, end);
			return true;
		}
	}
	return false;
}

int c8ui_textview_replace_all(struct c8ui_widget *w, const char *needle,
		const char *replacement, bool match_case) {
	struct textview *tv = w->data;
	if (needle == NULL || needle[0] == '\0') {
		return 0;
	}
	if (replacement == NULL) {
		replacement = "";
	}
	int count = 0;
	group_begin(tv);
	size_t i = 0;
	while (i < tv->text->len) {
		size_t end = match_at(tv->text->str, i, needle, match_case);
		if (end == 0) {
			i = next_char(tv, i);
			continue;
		}
		replace(w, i, end, replacement, EDIT_OTHER);
		i += strlen(replacement);
		count++;
	}
	group_end(tv);
	if (count > 0) {
		text_changed(w);
	}
	return count;
}

void c8ui_textview_on_move(struct c8ui_widget *w, c8ui_action_fn fn,
		void *data) {
	struct textview *tv = w->data;
	tv->move_fn = fn;
	tv->move_data = data;
}

void c8ui_textview_set_rich(struct c8ui_widget *w, bool rich) {
	struct textview *tv = w->data;
	tv->rich = rich;
	edits_clear(&tv->undo);
	edits_clear(&tv->redo);
	tv->saved = 0;
	runs_reset(tv);
	if (!rich) {
		runs_free(&tv->runs);
	}
	tv->layout_stale = true;
	c8ui_widget_queue_layout(w);
}

bool c8ui_textview_is_rich(struct c8ui_widget *w) {
	return ((struct textview *)w->data)->rich;
}

void c8ui_textview_append(struct c8ui_widget *w, const char *text,
		const struct c8ui_text_format *format) {
	struct textview *tv = w->data;
	if (text == NULL || text[0] == '\0') {
		return;
	}
	if (tv->rich) {
		int fmt = format ? fmt_merge(tv, 0, format, ~0u) : 0;
		runs_push(&tv->runs, strlen(text), fmt);
	}
	g_string_append(tv->text, text);
	edits_clear(&tv->undo);
	edits_clear(&tv->redo);
	tv->saved = 0;
	tv->layout_stale = true;
	c8ui_widget_queue_layout(w);
}

void c8ui_textview_get_format(struct c8ui_widget *w,
		struct c8ui_text_format *format) {
	struct textview *tv = w->data;
	static const struct fmt plain = { 0 };
	fmt_public(tv->rich ? &tv->fmts[fmt_for(tv, sel_start(tv),
		sel_end(tv))] : &plain, format);
}

void c8ui_textview_format(struct c8ui_widget *w,
		const struct c8ui_text_format *format, unsigned mask) {
	struct textview *tv = w->data;
	if (!tv->rich) {
		return;
	}
	size_t a = sel_start(tv), b = sel_end(tv);
	if (a == b) {
		tv->typing = fmt_merge(tv, fmt_for(tv, a, b), format, mask);
		tv->typing_set = true;
		return;
	}
	/* One step to undo with the text the same: only the runs change */
	if (tv->saved > tv->undo.count) {
		tv->saved = -1;
	}
	char *same = g_strndup(tv->text->str + a, b - a);
	edits_push(&tv->undo, (struct edit){
		.pos = a, .old = same, .new = strdup(same),
		.cursor = tv->cursor, .anchor = tv->anchor, .kind = EDIT_OTHER,
		.group = ++tv->next_group,
		.before = runs_copy(&tv->runs), .has_before = true,
	});
	edits_clear(&tv->redo);
	tv->merge_blocked = true;
	struct runs out = { 0 };
	size_t pos = 0;
	for (int i = 0; i < tv->runs.count; i++) {
		struct run r = tv->runs.items[i];
		size_t s = pos, e = pos + r.len;
		pos = e;
		if (s < a) {
			runs_push(&out, MIN(e, a) - s, r.fmt);
		}
		size_t ms = MAX(s, a), me = MIN(e, b);
		if (ms < me) {
			runs_push(&out, me - ms, fmt_merge(tv, r.fmt, format, mask));
		}
		if (e > b) {
			runs_push(&out, e - MAX(s, b), r.fmt);
		}
	}
	runs_free(&tv->runs);
	tv->runs = out;
	/* The selection stays, so not text_changed (which reveals the caret
	 * and restarts the blink): only laid out again and told */
	tv->layout_stale = true;
	c8ui_widget_queue_layout(w);
	if (tv->change_fn) {
		tv->change_fn(w, tv->change_data);
	}
}

void c8ui_textview_get_runs(struct c8ui_widget *w, c8ui_textview_run_fn fn,
		void *data) {
	struct textview *tv = w->data;
	struct c8ui_text_format f;
	if (!tv->rich) {
		if (tv->text->len) {
			static const struct fmt plain = { 0 };
			fmt_public(&plain, &f);
			fn(tv->text->str, tv->text->len, &f, data);
		}
		return;
	}
	size_t pos = 0;
	for (int i = 0; i < tv->runs.count; i++) {
		fmt_public(&tv->fmts[tv->runs.items[i].fmt], &f);
		fn(tv->text->str + pos, tv->runs.items[i].len, &f, data);
		pos += tv->runs.items[i].len;
	}
}
