// ScratchSyntaxHighlighter.swift // Lyrebird // // Copyright (c) 2026 Joshua Parmenter / realizedsound // SPDX-License-Identifier: MIT // LyrebirdUI/LiveCompile // // Paints ``ScratchSwiftTokenizer`` token colors onto an `NSTextStorage`. Split // out of the SwiftUI `NSViewRepresentable` so the tokenizer→color→storage wiring // is unit-testable against a plain `NSTextStorage` (no window / view needed). // // macOS only. #if os(macOS) import AppKit enum ScratchSyntaxHighlighter { /// Foreground color for a token kind. `NSColor.system*` are dynamic, so they /// adapt to the editor's light/dark appearance automatically. static func color(for kind: ScratchSwiftTokenizer.Kind) -> NSColor { switch kind { case .keyword: return .systemPink case .type: return .systemPurple case .string: return .systemRed case .number: return .systemBlue case .comment: return .systemGreen } } /// Normalize `baseAttributes` (font / paragraph / label color) over the whole /// storage — so a paste or font change can't leave stray styling — then /// overlay per-token foreground colors. Attribute-only: the string is not /// changed, so the caller's selection is preserved. static func apply(to storage: NSTextStorage, baseAttributes: [NSAttributedString.Key: Any]) { let full: NSRange = NSRange(location: 0, length: storage.length) storage.beginEditing() storage.setAttributes(baseAttributes, range: full) for token: ScratchSwiftTokenizer.Token in ScratchSwiftTokenizer.tokens(in: storage.string) { // Ranges come from the same string, but guard against any bounds // drift before touching the storage. let end: Int = token.range.location + token.range.length if token.range.location >= 0, end <= storage.length { storage.addAttribute(.foregroundColor, value: color(for: token.kind), range: token.range) } } storage.endEditing() } } #endif