From e275ba4fc994474155fbafe8b87a6d3b477456ba Mon Sep 17 00:00:00 2001
From: Bram Moolenaar <Bram@vim.org>
Date: Wed, 6 Oct 2021 13:41:07 +0100
Subject: [PATCH] patch 8.2.3484: crash when going through spell suggestions

Problem:    Crash when going through spell suggestions.
Solution:   Limit the text length for finding suggestions to the original
length.  Do not update buffers when exiting. (closes #8965)
---
 src/spellsuggest.c              |  5 +++++
 src/testdir/test_spell_utf8.vim | 16 ++++++++++++++++
 src/ui.c                        |  3 ++-
 3 files changed, 23 insertions(+), 1 deletion(-)

diff --git a/src/spellsuggest.c b/src/spellsuggest.c
index 0171a5b..0f833f5 100644
--- a/src/spellsuggest.c
+++ b/src/spellsuggest.c
@@ -1169,6 +1169,11 @@ suggest_try_change(suginfo_T *su)
     p = su->su_badptr + su->su_badlen;
     (void)spell_casefold(p, (int)STRLEN(p), fword + n, MAXWLEN - n);
 
+    // Make sure the resulting text is not longer than the original text.
+    n = (int)STRLEN(su->su_badptr);
+    if (n < MAXWLEN)
+	fword[n] = NUL;
+
     for (lpi = 0; lpi < curwin->w_s->b_langp.ga_len; ++lpi)
     {
 	lp = LANGP_ENTRY(curwin->w_s->b_langp, lpi);
diff --git a/src/testdir/test_spell_utf8.vim b/src/testdir/test_spell_utf8.vim
index 1f561e4..79dc3e4 100644
--- a/src/testdir/test_spell_utf8.vim
+++ b/src/testdir/test_spell_utf8.vim
@@ -765,4 +765,20 @@ func Test_spellfile_value()
   set spellfile=Xdir/Xtest.utf-8.add,Xtest_other.add
 endfunc
 
+func Test_no_crash_with_weird_text()
+  new
+  let lines =<< trim END
+      r<sfile>
+      
+
+
+      
+  END
+  call setline(1, lines)
+  exe "%norm \<C-v>ez=>\<C-v>wzG"
+
+  bwipe!
+endfunc
+
+
 " vim: shiftwidth=2 sts=2 expandtab
diff --git a/src/ui.c b/src/ui.c
index 7ec1e56..8d6f681 100644
--- a/src/ui.c
+++ b/src/ui.c
@@ -868,7 +868,8 @@ clip_lose_selection(Clipboard_T *cbd)
 					    || get_real_state() == SELECTMODE)
 		&& (cbd == &clip_star ?
 				clip_isautosel_star() : clip_isautosel_plus())
-		&& HL_ATTR(HLF_V) != HL_ATTR(HLF_VNC))
+		&& HL_ATTR(HLF_V) != HL_ATTR(HLF_VNC)
+		&& !exiting)
 	{
 	    update_curbuf(INVERTED_ALL);
 	    setcursor();
-- 
1.8.3.1

