From 5c84cf7e90211fa12eab08590c79a3d64daedbe9 Mon Sep 17 00:00:00 2001 From: Chris Waldon Date: Mon, 14 Nov 2022 09:53:10 -0500 Subject: [PATCH] widget: do not allow invalid utf8 in editor This commit replaces invalid UTF8 codepoints with the replacement character when they are inserted into the editor. This ensures that the editor never moves the editing gap to an invalid location and reads its contents. Signed-off-by: Chris Waldon --- widget/buffer.go | 6 ++++++ 1 file changed, 6 insertions(+) diff --git a/widget/buffer.go b/widget/buffer.go index 40e02a86..48ed72ed 100644 --- a/widget/buffer.go +++ b/widget/buffer.go @@ -6,6 +6,8 @@ import ( "io" "strings" "unicode/utf8" + + "golang.org/x/text/runes" ) // editBuffer implements a gap buffer for text editing. @@ -162,6 +164,10 @@ func (e *editBuffer) String() string { } func (e *editBuffer) prepend(caret int, s string) { + if !utf8.ValidString(s) { + s = runes.ReplaceIllFormed().String(s) + } + e.moveGap(caret, len(s)) copy(e.text[caret:], s) e.gapstart += len(s)