r/swift • u/Ok-Welder-8005 • 9h ago
Project Building incremental Swift syntax highlighting and symbol navigation with TextKit 2
I’ve been working on a native code editor for iPhone and iPad, and one of the more interesting problems has been making Swift files comfortable to read and edit without reprocessing the entire document after every keystroke.
The editor uses UIKit and TextKit 2, with a custom NSTextContentStorage implementation managing the source text and attributed rendering.
For syntax highlighting, I use a Swift TextMate grammar and store the parsed output in a token tree. The initial document load parses the complete file, while interactive edits are handled incrementally.
After an edit, the editor:
- Invalidates the affected syntax range.
- Continues parsing from the nearest valid state.
- Propagates highlighting changes in bounded chunks.
- Applies attributes only to ranges that need rendering.
- Cancels stale work when another edit changes the document revision.
Keeping a syntax revision number turned out to be important. Background parsing may finish after the user has already changed the document again, so each result is checked against the current revision before it can update the editor.
The other feature shown in the screenshot is Swift symbol navigation.
Instead of using SourceKit, the current implementation builds a lightweight outline from the scopes emitted by the TextMate grammar. It identifies declarations such as:
classstructenumprotocolextensionfunc- Initializers and subscripts
The symbols are arranged into a hierarchy using their scope depth and indentation. Selecting a symbol jumps directly to its line in the editor.
This approach is intentionally syntax-based rather than semantic. It works well for navigating a single source file, but it does not understand types, overload resolution, cross-file references, or compiler diagnostics.
That trade-off has been useful on iPhone and iPad: the outline remains lightweight and provides a quick way to move around long Swift files without trying to reproduce Xcode.
I’m considering where to take it next. Possible additions include stored properties, MARK sections, protocol conformances, and improved handling of nested declarations.
For a lightweight mobile Swift editor, which symbols would you expect to see in the outline?

