From 0b52f9863e42fac772a3c906c6b353a7a7dfadca Mon Sep 17 00:00:00 2001
From: Sandy McFadden <sandy.mcfadden@automattic.com>
Date: Thu, 15 Apr 2021 07:37:33 -0300
Subject: [PATCH 1/2] Ensure selected search index isn't larger then the number
 of search matches.

---
 lib/note-content-editor.tsx | 11 +++++++++++
 1 file changed, 11 insertions(+)

diff --git a/lib/note-content-editor.tsx b/lib/note-content-editor.tsx
index c271e93a7..541055ec3 100644
--- a/lib/note-content-editor.tsx
+++ b/lib/note-content-editor.tsx
@@ -374,6 +374,17 @@ class NoteContentEditor extends Component<Props> {
       this.setDecorators();
     }
 
+    // If content is changed so that the selected search index is greater then the number of matches
+    // then select the last match instead
+    if (
+      this.editor &&
+      this.state.editor === 'full' &&
+      (this.props.selectedSearchMatchIndex ?? 0) > this.matchesInNote.length - 1
+    ) {
+      this.setSearchSelection(this.matchesInNote.length - 1);
+      this.props.storeSearchSelection(this.matchesInNote.length - 1);
+    }
+
     if (
       this.editor &&
       this.state.editor === 'full' &&

From 264db378bd10b55a9c3d427cef2530a777d3c7ab Mon Sep 17 00:00:00 2001
From: Sandy McFadden <sandy.mcfadden@automattic.com>
Date: Thu, 15 Apr 2021 07:54:58 -0300
Subject: [PATCH 2/2] Ensure index we set is not less then 0

---
 lib/note-content-editor.tsx | 5 +++--
 1 file changed, 3 insertions(+), 2 deletions(-)

diff --git a/lib/note-content-editor.tsx b/lib/note-content-editor.tsx
index 541055ec3..886e2b6a7 100644
--- a/lib/note-content-editor.tsx
+++ b/lib/note-content-editor.tsx
@@ -381,8 +381,9 @@ class NoteContentEditor extends Component<Props> {
       this.state.editor === 'full' &&
       (this.props.selectedSearchMatchIndex ?? 0) > this.matchesInNote.length - 1
     ) {
-      this.setSearchSelection(this.matchesInNote.length - 1);
-      this.props.storeSearchSelection(this.matchesInNote.length - 1);
+      const newIndex = Math.max(this.matchesInNote.length - 1, 0);
+      this.setSearchSelection(newIndex);
+      this.props.storeSearchSelection(newIndex);
     }
 
     if (