Create a TextSource
-derived class:
public class TextBuilder : TextSource
{
public Line CurrentLine { get; private set; }
public TextBuilder(FastColoredTextBox t) : base(t)
{
AppendLine();
}
public void Append(string text, StyleIndex style = StyleIndex.None)
{
for (int i = 0; i < text.Length; i++)
{
char c = text[i];
if (c == '\r' && i < text.Length - 1 && text[i + 1] == '\n') continue;
if (c == '\r' || c == '\n') { AppendLine(); continue; }
CurrentLine.Add(new Char(c, style));
}
}
public void AppendLine(string text, StyleIndex style = StyleIndex.None)
{
Append(text, style);
AppendLine();
}
public void AppendLine()
{
CurrentLine = CreateLine();
lines.Add(CurrentLine);
}
public override void Initialized()
{
// Solution similar to CustomTextSourceSample.cs (not more than necessary)
// (an alternative is OnTextChanged(0, lines.Count - 1) which invokes TextChanged but there may be side effects)
if (CurrentTB.WordWrap)
{
OnRecalcWordWrap(new TextChangedEventArgs(0, lines.Count - 1));
}
CurrentTB.Invalidate();
}
}
Add this virtual method to the TextSource
class:
/// <summary>
/// Called when CurrentTB has initialized this text source.
/// </summary>
public virtual void Initialized()
{
}
In the FCTB class, add this line to the InitTextSource
method:
while (LineInfos.Count < ts.Count)
LineInfos.Add(new LineInfo(-1));
ts.Initialized(); // Add this line
Change the Char
constructor for convenience:
public Char(char c, StyleIndex s = StyleIndex.None)
{
this.c = c;
style = s;
}
Use as follows:
var b = new TextBuilder(fctb);
b.Styles[0] = new MarkerStyle(Brushes.LightBlue);
b.Append("text", StyleIndex.Style0);
fctb.TextSource = b;
If you want to do it without recompiling FCTB you can just create the TextBuilder
class minus virtual method etc. and call b.OnTextChanged(0, b.Count - 1)
after assigning TextSource
.