restores Helder in all its glory
This commit is contained in:
@@ -0,0 +1,174 @@
|
||||
import AppKit
|
||||
import HelderCore
|
||||
|
||||
/// One file's text as the editor holds it: its own storage, undo history, line index and tokens,
|
||||
/// so switching files swaps storages instead of re-reading and re-colouring the file.
|
||||
@MainActor
|
||||
final class CodeDocument: NSObject, NSTextStorageDelegate {
|
||||
let id: String
|
||||
let storage = NSTextStorage()
|
||||
let undoManager = UndoManager()
|
||||
var revision = -1
|
||||
var language: Language?
|
||||
var tabSize = 4
|
||||
private(set) var scale: CGFloat = 1
|
||||
private(set) var lineIndex = LineIndex("")
|
||||
var selection = NSRange(location: 0, length: 0)
|
||||
var scrollOrigin = NSPoint.zero
|
||||
|
||||
private(set) var tokens: [Token] = []
|
||||
private var tokenTextLength = 0
|
||||
private var knownSymbols: Set<String> = []
|
||||
/// Which symbol list the colours were computed with.
|
||||
private(set) var symbolsVersion = -1
|
||||
private var generation = 0
|
||||
/// What changed since the last paint, in current text coordinates.
|
||||
private var dirty: NSRange?
|
||||
/// Suppresses the edit bookkeeping while the document replaces its own text.
|
||||
private var isLoading = false
|
||||
|
||||
init(id: String) {
|
||||
self.id = id
|
||||
super.init()
|
||||
storage.delegate = self
|
||||
}
|
||||
|
||||
var length: Int { storage.length }
|
||||
|
||||
/// Replaces the whole text from outside (load, reload); the undo history no longer applies.
|
||||
func load(_ text: String, revision: Int, tabSize: Int) {
|
||||
self.revision = revision
|
||||
self.tabSize = tabSize
|
||||
isLoading = true
|
||||
storage.setAttributedString(NSAttributedString(string: text, attributes: EditorFonts.baseAttributes(tabSize: tabSize, scale: scale)))
|
||||
isLoading = false
|
||||
lineIndex = LineIndex(text)
|
||||
undoManager.removeAllActions()
|
||||
tokens = []
|
||||
tokenTextLength = storage.length
|
||||
dirty = nil
|
||||
selection = NSRange(location: min(selection.location, storage.length), length: 0)
|
||||
}
|
||||
|
||||
func setTabSize(_ size: Int) {
|
||||
guard size != tabSize else { return }
|
||||
tabSize = size
|
||||
restyle()
|
||||
}
|
||||
|
||||
/// View → Zoom: the font and row height change in place, keeping the text and its undo history.
|
||||
func setScale(_ next: CGFloat) {
|
||||
guard next != scale else { return }
|
||||
scale = next
|
||||
restyle()
|
||||
}
|
||||
|
||||
private func restyle() {
|
||||
let font = EditorFonts.code(scale: scale)
|
||||
let whole = NSRange(location: 0, length: storage.length)
|
||||
storage.beginEditing()
|
||||
storage.addAttribute(.font, value: font, range: whole)
|
||||
storage.addAttribute(.paragraphStyle, value: EditorFonts.paragraphStyle(tabSize: tabSize, font: font, scale: scale), range: whole)
|
||||
storage.endEditing()
|
||||
}
|
||||
|
||||
nonisolated func textStorage(_ textStorage: NSTextStorage, didProcessEditing editedMask: NSTextStorageEditActions,
|
||||
range editedRange: NSRange, changeInLength delta: Int) {
|
||||
guard editedMask.contains(.editedCharacters) else { return }
|
||||
MainActor.assumeIsolated {
|
||||
guard !isLoading else { return }
|
||||
let inserted = (textStorage.string as NSString).substring(with: editedRange)
|
||||
lineIndex.applyEdit(editedRange: editedRange, delta: delta, inserted: inserted)
|
||||
markDirty(editedRange, delta: delta)
|
||||
}
|
||||
}
|
||||
|
||||
private func markDirty(_ range: NSRange, delta: Int) {
|
||||
guard let previous = dirty else {
|
||||
dirty = range
|
||||
return
|
||||
}
|
||||
let shiftedEnd = NSMaxRange(previous) >= range.location ? NSMaxRange(previous) + delta : NSMaxRange(previous)
|
||||
let start = min(previous.location, range.location)
|
||||
let end = max(shiftedEnd, NSMaxRange(range))
|
||||
dirty = NSRange(location: start, length: max(0, end - start))
|
||||
}
|
||||
|
||||
// MARK: Highlighting
|
||||
|
||||
/// Colours the whole text off the main thread; the plain text shows at once, colours follow.
|
||||
func highlightAll(symbols: Set<String>, version: Int) {
|
||||
knownSymbols = symbols
|
||||
symbolsVersion = version
|
||||
dirty = nil
|
||||
run(full: true, delay: nil)
|
||||
}
|
||||
|
||||
/// After a keystroke: waits for a pause, re-tokenises, repaints only what changed.
|
||||
func highlightEdits() {
|
||||
run(full: false, delay: .milliseconds(40))
|
||||
}
|
||||
|
||||
private func run(full: Bool, delay: Duration?) {
|
||||
generation += 1
|
||||
let mine = generation
|
||||
guard let language else {
|
||||
if full { paint(NSRange(location: 0, length: storage.length), with: []) }
|
||||
return
|
||||
}
|
||||
Task { @MainActor [weak self] in
|
||||
if let delay { try? await Task.sleep(for: delay) }
|
||||
guard let self, mine == self.generation else { return }
|
||||
let text = self.storage.string
|
||||
let symbols = self.knownSymbols
|
||||
let tokens = await Task.detached(priority: .userInitiated) {
|
||||
SyntaxHighlighter.tokens(for: text, language: language, knownSymbols: symbols)
|
||||
}.value
|
||||
guard mine == self.generation, (text as NSString).length == self.storage.length else { return }
|
||||
let length = self.storage.length
|
||||
let range: NSRange
|
||||
if full || self.tokens.isEmpty {
|
||||
range = NSRange(location: 0, length: length)
|
||||
} else {
|
||||
let edited = self.dirty ?? NSRange(location: 0, length: 0)
|
||||
range = HighlightDiff.repaintRange(old: self.tokens, new: tokens, edited: edited,
|
||||
delta: length - self.tokenTextLength, newLength: length)
|
||||
}
|
||||
self.tokens = tokens
|
||||
self.tokenTextLength = length
|
||||
self.dirty = nil
|
||||
self.paint(range, with: tokens)
|
||||
}
|
||||
}
|
||||
|
||||
private func paint(_ range: NSRange, with tokens: [Token]) {
|
||||
guard range.length > 0 else { return }
|
||||
storage.beginEditing()
|
||||
storage.addAttribute(.foregroundColor, value: EditorColors.syntax(.plain), range: range)
|
||||
var index = firstToken(endingAfter: range.location, in: tokens)
|
||||
let end = NSMaxRange(range)
|
||||
while index < tokens.count, tokens[index].location < end {
|
||||
let token = tokens[index]
|
||||
index += 1
|
||||
guard token.role != .plain else { continue }
|
||||
let hit = NSIntersectionRange(range, NSRange(location: token.location, length: token.length))
|
||||
if hit.length > 0 { storage.addAttribute(.foregroundColor, value: EditorColors.syntax(token.role), range: hit) }
|
||||
}
|
||||
storage.endEditing()
|
||||
}
|
||||
|
||||
private func firstToken(endingAfter location: Int, in tokens: [Token]) -> Int {
|
||||
var low = 0
|
||||
var high = tokens.count
|
||||
while low < high {
|
||||
let mid = (low + high) / 2
|
||||
if tokens[mid].location + tokens[mid].length <= location { low = mid + 1 } else { high = mid }
|
||||
}
|
||||
return low
|
||||
}
|
||||
|
||||
/// Ranges of the ⌘-clickable class names, for the underline while ⌘ is held.
|
||||
var symbolRanges: [NSRange] {
|
||||
tokens.filter { $0.role == .symbol }.map { NSRange(location: $0.location, length: $0.length) }
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user