Skip to content

Commit 254b601

Browse files
author
Kapil Borle
committed
Add alternative apply edit method
This method uses the logic used in editor services to apply an edit.
1 parent 470416d commit 254b601

1 file changed

Lines changed: 54 additions & 0 deletions

File tree

Engine/EditableText.cs

Lines changed: 54 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,5 @@
11
using System;
2+
using System.Collections.Generic;
23
using System.Linq;
34
using System.Management.Automation.Language;
45
using System.Text;
@@ -37,6 +38,59 @@ public EditableText ApplyEdit(TextEdit textEdit)
3738
return new EditableText(stringBuilder.ToString());
3839
}
3940

41+
// TODO replace apply edit with an optimized version of this.
42+
public EditableText ApplyEdit1(TextEdit textEdit)
43+
{
44+
ValidateTextEdit(textEdit);
45+
46+
// Break up the change lines
47+
var changeLines = textEdit.Lines;
48+
var Lines = new List<String>(this.Lines);
49+
50+
// Get the first fragment of the first line
51+
string firstLineFragment =
52+
Lines[textEdit.StartLineNumber - 1]
53+
.Substring(0, textEdit.StartColumnNumber - 1);
54+
55+
// Get the last fragment of the last line
56+
string endLine = Lines[textEdit.EndLineNumber - 1];
57+
string lastLineFragment =
58+
endLine.Substring(
59+
textEdit.EndColumnNumber - 1,
60+
Lines[textEdit.EndLineNumber - 1].Length - textEdit.EndColumnNumber + 1);
61+
62+
// Remove the old lines
63+
for (int i = 0; i <= textEdit.EndLineNumber - textEdit.StartLineNumber; i++)
64+
{
65+
Lines.RemoveAt(textEdit.StartLineNumber - 1);
66+
}
67+
68+
// Build and insert the new lines
69+
int currentLineNumber = textEdit.StartLineNumber;
70+
for (int changeIndex = 0; changeIndex < changeLines.Length; changeIndex++)
71+
{
72+
// Since we split the lines above using \n, make sure to
73+
// trim the ending \r's off as well.
74+
string finalLine = changeLines[changeIndex].TrimEnd('\r');
75+
76+
// Should we add first or last line fragments?
77+
if (changeIndex == 0)
78+
{
79+
// Append the first line fragment
80+
finalLine = firstLineFragment + finalLine;
81+
}
82+
if (changeIndex == changeLines.Length - 1)
83+
{
84+
// Append the last line fragment
85+
finalLine = finalLine + lastLineFragment;
86+
}
87+
88+
Lines.Insert(currentLineNumber - 1, finalLine);
89+
currentLineNumber++;
90+
}
91+
92+
return new EditableText(String.Join(NewLine, Lines));
93+
}
4094
// TODO Add a method that takes multiple edits, checks if they are unique and applies them.
4195

4296
public override string ToString()

0 commit comments

Comments
 (0)