From 7bb0fd91a7b420876afdca12488de638ce96a504 Mon Sep 17 00:00:00 2001
From: Dan Whittaker <zallist@gmail.com>
Date: Sat, 19 Oct 2024 18:06:38 +0100
Subject: [PATCH] Fix for github issue #101 Codeium was not checking for both
 \r and \n when working out what else should be appended to the end of the
 line. It now does that.

---
 CodeiumVS/SuggestionUI/StringCompare.cs    | 21 +++++++++++++++++++--
 CodeiumVS/SuggestionUI/TextViewListener.cs |  7 ++++---
 2 files changed, 23 insertions(+), 5 deletions(-)

diff --git a/CodeiumVS/SuggestionUI/StringCompare.cs b/CodeiumVS/SuggestionUI/StringCompare.cs
index 9d51b0b..7511ca2 100644
--- a/CodeiumVS/SuggestionUI/StringCompare.cs
+++ b/CodeiumVS/SuggestionUI/StringCompare.cs
@@ -75,7 +75,7 @@ public static int CheckSuggestion(String suggestion, String line, bool isTextIns
 
         int index = suggestion.IndexOf(line);
         int endPos = index + line.Length;
-        int firstLineBreak = suggestion.IndexOf('\n');
+        int firstLineBreak = IndexOfNewLine(suggestion);
 
         if (index > -1 && (firstLineBreak == -1 || endPos < firstLineBreak))
         {
@@ -88,5 +88,22 @@ public static int CheckSuggestion(String suggestion, String line, bool isTextIns
             return res.Item1 >= endPoint ? res.Item2 : -1;
         }
     }
-}
+        
+    private static readonly System.Text.RegularExpressions.Regex newLineMatcher = new System.Text.RegularExpressions.Regex(@"(?:\r\n|\n|\r)",
+        System.Text.RegularExpressions.RegexOptions.Compiled | System.Text.RegularExpressions.RegexOptions.Singleline);
+
+    /// <summary>
+    /// Returns the index of the first new line in the string, or -1 if not found
+    /// </summary>
+    /// <remarks>Checks for both \r\n and \n</remarks>
+    public static int IndexOfNewLine(string text)
+    {
+        System.Text.RegularExpressions.Match newLineMatch = newLineMatcher.Match(text);
+
+        if (newLineMatch.Success)
+            return newLineMatch.Index;
+
+        return -1;
+    }
+    }
 }
diff --git a/CodeiumVS/SuggestionUI/TextViewListener.cs b/CodeiumVS/SuggestionUI/TextViewListener.cs
index 344b057..490bf99 100644
--- a/CodeiumVS/SuggestionUI/TextViewListener.cs
+++ b/CodeiumVS/SuggestionUI/TextViewListener.cs
@@ -157,9 +157,10 @@ List<Tuple<String, String>> ParseCompletion(IList<Packets.CompletionItem> comple
             String completionText = completionItems[i].completion.text;
             if (!String.IsNullOrEmpty(end))
             {
-                int endNewline = end.IndexOf('\r');
-                endNewline = endNewline <= -1 ? end.IndexOf('\n') : endNewline;
-                endNewline = endNewline <= -1 ? end.Length : endNewline;
+                int endNewline = StringCompare.IndexOfNewLine(end);
+
+                if (endNewline <= -1)
+                    endNewline = end.Length;
 
                 completionText = completionText + end.Substring(0, endNewline);
             }