Capstone A: the document
A text editor is the smallest application that has all the problems: a document that can be changed, a file that has to be saved, a window title that says whether the changes are safe, a search that has to find the next occurrence, and a list of the files the user opened last. This capstone builds it in three lessons. The first is the document, and the document has no window in it.
The document
The class owns the text, the path and the dirty flag, and it asks a store for the bytes. The store is an interface because the tests of the next lesson do not touch a disk:
internal interface INotesStore
{
string Load(string path);
void Save(string path, string text);
}
internal sealed class NoteDocument
{
private readonly INotesStore _store;
public NoteDocument(INotesStore store) => _store = store;
public string Text { get; private set; } = string.Empty;
public string? FilePath { get; private set; }
public bool IsDirty { get; private set; }
public string Title => FilePath is null ? "Untitled" : Path.GetFileName(FilePath);
public void New()
{
Text = string.Empty;
FilePath = null;
IsDirty = false;
}
public void SetText(string text)
{
if (text == Text)
{
return;
}
Text = text;
IsDirty = true;
}
public void Open(string path)
{
Text = _store.Load(path);
FilePath = path;
IsDirty = false;
}
public void Save(string? path = null)
{
var target = path ?? FilePath
?? throw new InvalidOperationException("The document has no path yet.");
_store.Save(target, Text);
FilePath = target;
IsDirty = false;
}
}
The store is two methods, and the real implementation is two lines over File.ReadAllText and File.WriteAllText. What the interface buys is the test that does not write a file, and the place to add a check for a file that is too large. The document never reads a path itself, so it does not have to know whether the text came from a disk, a network share or a string in a test.
The dirty flag
IsDirty is true from the first change until the next successful save or open. It is the flag that decides whether closing the window asks a question, and the title bar is its visible form: todo.txt * means there are unsaved changes.
The setter is the only place that can set it, and it returns early when the text did not change. That early return matters more than it looks: a TextBox raises TextChanged for changes the user did not make, such as a programmatic assignment of the same text, and a dirty flag that goes true on every event makes the close prompt useless. The property has a private setter, so nothing outside the document can clear it by accident.
Save with no argument uses the current path and throws when there is none. That exception is deliberate: a save of a new document has to ask the user first, and the presenter is the layer that asks. The document is a model and does not open a dialog.
Find and replace
Find is string.IndexOf with a start position and a comparison, plus a clamp of the start to the document: a caret position after an edit can be one past the end. It returns -1 when there is no match, which is the value IndexOf already uses, so the caller does not translate an index.
ReplaceAll is the loop that the naive version gets wrong. It walks the text with an index, appends the part before each match and the replacement, and never rescans the replacement: a replacement that contains the needle would otherwise loop forever or replace its own output. It counts the matches, and it sets the flag only when there was at least one.
Both use StringComparison.OrdinalIgnoreCase. That is a decision, and the right one for a note editor: a case-insensitive search finds Ada for ada, and the culture does not change what matches. A code editor with a case-sensitive option would pass the comparison in, not read a setting from inside the document.
Recent files
The recent list is a small rule with a surprising number of edges: the newest path comes first, an existing path moves to the front instead of appearing twice, the comparison ignores case on Windows, and the list has a limit. The class below is the whole of it:
internal sealed class RecentFiles
{
private readonly List<string> _paths = new();
public IReadOnlyList<string> Paths => _paths;
public int Capacity { get; } = 5;
public void Add(string path)
{
_paths.RemoveAll(existing => string.Equals(existing, path, StringComparison.OrdinalIgnoreCase));
_paths.Insert(0, path);
if (_paths.Count > Capacity)
{
_paths.RemoveAt(_paths.Count - 1);
}
}
}
The real application saves the list in the settings file of lesson 043 or in the JSON store of the third capstone, and it drops a path that no longer exists when the menu is built. Neither is the document's job, and both are testable with the same class.
The document in a program that runs
The whole core, with an in-memory store, driven through the states a user produces. It was built and run in the container:
using System;
using System.Collections.Generic;
using System.IO;
Console.WriteLine("a note document and its recent files");
var store = new MemoryStore();
var document = new NoteDocument(store);
Console.WriteLine($"start: {document.Title}, dirty {document.IsDirty}");
document.SetText("First line\nSecond line");
Console.WriteLine($"after typing: dirty {document.IsDirty}");
document.Save("/notes/todo.txt");
Console.WriteLine($"after save: dirty {document.IsDirty}, title {document.Title}, stored {store.Count} file(s)");
Console.WriteLine($"find 'second' from 0: {document.Find("second", 0)}");
Console.WriteLine($"find 'third' from 0: {document.Find("third", 0)}");
var replaced = document.ReplaceAll("line", "row");
Console.WriteLine($"replaced {replaced}, dirty {document.IsDirty}");
Console.WriteLine($"text: {document.Text.Replace("\n", " | ")}");
var recent = new RecentFiles();
foreach (var path in new[] { "/a.txt", "/b.txt", "/a.txt", "/c.txt" })
{
recent.Add(path);
}
Console.WriteLine($"recent: {string.Join(", ", recent.Paths)}");
document.New();
Console.WriteLine($"new: {document.Title}, dirty {document.IsDirty}, text '{document.Text}'");
internal interface INotesStore
{
string Load(string path);
void Save(string path, string text);
}
internal sealed class MemoryStore : INotesStore
{
private readonly Dictionary<string, string> _files = new();
public int Count => _files.Count;
public string Load(string path) => _files[path];
public void Save(string path, string text) => _files[path] = text;
}
internal sealed class NoteDocument
{
private readonly INotesStore _store;
public NoteDocument(INotesStore store) => _store = store;
public string Text { get; private set; } = string.Empty;
public string? FilePath { get; private set; }
public bool IsDirty { get; private set; }
public string Title => FilePath is null ? "Untitled" : Path.GetFileName(FilePath);
public void New()
{
Text = string.Empty;
FilePath = null;
IsDirty = false;
}
public void SetText(string text)
{
if (text == Text)
{
return;
}
Text = text;
IsDirty = true;
}
public void Open(string path)
{
Text = _store.Load(path);
FilePath = path;
IsDirty = false;
}
public void Save(string? path = null)
{
var target = path ?? FilePath
?? throw new InvalidOperationException("The document has no path yet.");
_store.Save(target, Text);
FilePath = target;
IsDirty = false;
}
public int Find(string needle, int start)
{
if (needle.Length == 0)
{
return -1;
}
var from = Math.Clamp(start, 0, Text.Length);
return Text.IndexOf(needle, from, StringComparison.OrdinalIgnoreCase);
}
public int ReplaceAll(string needle, string replacement)
{
if (needle.Length == 0)
{
return 0;
}
var count = 0;
var index = 0;
var result = new System.Text.StringBuilder();
while (true)
{
var hit = Text.IndexOf(needle, index, StringComparison.OrdinalIgnoreCase);
if (hit < 0)
{
result.Append(Text, index, Text.Length - index);
break;
}
result.Append(Text, index, hit - index);
result.Append(replacement);
index = hit + needle.Length;
count++;
}
if (count > 0)
{
Text = result.ToString();
IsDirty = true;
}
return count;
}
}
internal sealed class RecentFiles
{
private readonly List<string> _paths = new();
public IReadOnlyList<string> Paths => _paths;
public int Capacity { get; } = 5;
public void Add(string path)
{
_paths.RemoveAll(existing => string.Equals(existing, path, StringComparison.OrdinalIgnoreCase));
_paths.Insert(0, path);
if (_paths.Count > Capacity)
{
_paths.RemoveAt(_paths.Count - 1);
}
}
}
dotnet run
a note document and its recent files
start: Untitled, dirty False
after typing: dirty True
after save: dirty False, title todo.txt, stored 1 file(s)
find 'second' from 0: 11
find 'third' from 0: -1
replaced 2, dirty True
text: First row | Second row
recent: /c.txt, /a.txt, /b.txt
new: Untitled, dirty False, text ''
The output is the real run, and every line is a state the form of the next lesson shows. The title changed with the save, the dirty flag went true on the first edit and false on the save, the find found second at 11 and did not find third, the replacement made two changes and marked the document dirty, and the recent list put /a.txt in front of /b.txt the second time it was added.
Exercises
- Add a FindNext that continues from the end of the last match and wraps to the start; extend the run with a case that wraps.
- Add a LineCount and a WordCount to the document and print them before and after the replacement.
- Make RecentFiles drop a path that starts with a drive letter on Linux and explain why the rule belongs in the view.
Questions
A new set of questions in a new order every time. Choose one answer for each, then check.
-
What does the document own?
Answer
The text, the path and the dirty flag
The store is behind an interface, and the form is a separate class.
-
Why does SetText return early when the text is equal?
Answer
A programmatic assignment of the same text must not mark the document dirty
The close prompt depends on the flag meaning a real change.
-
What does Save with no argument do for a new document?
Answer
Throws, because there is no path yet
The presenter is the layer that asks for a path.
-
What position did Find report for second?
Answer
11
The newline is at 10, so Second starts at 11.
-
Why does ReplaceAll build a new string instead of calling Replace?
Answer
It needs the count, and it must not rescan the replacement
The loop counts matches and appends past each one.
-
What comparison do Find and ReplaceAll use?
Answer
OrdinalIgnoreCase
A note editor finds Ada for ada and does not depend on the culture.
-
What happens when an existing path is added to RecentFiles again?
Answer
It moves to the front and appears once
RemoveAll then Insert is the move-to-front rule.
-
What was the recent list after the four additions?
Answer
/c.txt, /a.txt, /b.txt
The run prints the newest first, without a duplicate.
-
Why is the store an interface?
Answer
A test can use an in-memory store and no disk
The run of this page uses MemoryStore.
-
What did New leave in the document?
Answer
An empty text, no path and a clean flag
The run printed Untitled, dirty False, text empty.
Every listing on this page was built with the .NET SDK 10.0.303 for net10.0-windows against the targeting pack Microsoft.WindowsDesktop.App.Ref 10.0.15 from the offline feed, in a Docker container on Alpine Linux 3.24.3 (x86_64). The programs were built, not run on Linux: WinForms needs Windows. The logic that draws nothing was also run headless on the same machine, and its output is the run output printed below each of those programs.
Article author: Arthur Isaev