-
Notifications
You must be signed in to change notification settings - Fork 28
Basic Text Retrieval and Modification
At its most basic level ScintillaNET is a text editor. The following recipes demonstrate basic text I/O.
The Text
property is the obvious choice if you want to get a string that represents all the text currently in a Scintilla control. Internally the Scintilla control will copy the entire contents of the document into a new string. Depending on the amount of text in the editor, this could be an expensive operation. Scintilla is designed to work efficiently with large amounts of text, but using the Text
property to retrieve only a substring negates that.
Instead, it's usually best to identify the range of text you're interested in (through search, selection, or some other means) and use the GetTextRange
method to copy only what you need into a string:
// Get the whole document
var wholeDoc = scintilla.Text;
// Get the first 256 characters of the document
var text = scintilla.GetTextRange(0, Math.Min(256, scintilla.TextLength));
Console.WriteLine(text);
// Sometimes it's nice to read the lines of a file to an array/list for processing
var myListOfItems = new List<string>();
foreach (var item in scintilla.Lines)
myListOfItems.Add(item.Text);
// or...
List<string> myListOfItems = scintilla.Lines.Select(x => x.Text).ToList();
Modifications usually come in the form of insert, append, and delete operations. As was discussed above, using the Text
property to make a small change in the document contents is highly inefficient. Instead try one of the following options:
scintilla.Text = "Hello";
scintilla.AppendText(" World"); // 'Hello' -> 'Hello World'
scintilla.DeleteRange(0, 5); // 'Hello World' -> ' World'
scintilla.InsertText(0, "Goodbye"); // ' World' -> 'Goodbye World'
// Remove line from Scintilla
scintilla.TargetStart = scintilla.Lines[0].Position;
scintilla.TargetEnd = scintilla.Lines[0].EndPosition;
scintilla.ReplaceTarget(string.Empty);
NOTE: It may help to think of a Scintilla control as a StringBuilder
.