import Foundation import HelderCore /// The role painted over `fragment` (its `occurrence`-th appearance), or nil when the /// fragment is missing or split over tokens of different roles. func role( _ fragment: String, in text: String, _ language: Language?, occurrence: Int = 0, symbols: Set = [] ) -> TokenRole? { let source = text as NSString var searchFrom = 0 var range = NSRange(location: NSNotFound, length: 0) for _ in 0...occurrence { range = source.range(of: fragment, range: NSRange(location: searchFrom, length: source.length - searchFrom)) guard range.location != NSNotFound else { return nil } searchFrom = range.location + max(range.length, 1) } let tokens = SyntaxHighlighter.tokens(for: text, language: language, knownSymbols: symbols) let covering = tokens.filter { $0.location < range.location + range.length && $0.location + $0.length > range.location } guard let first = covering.first, covering.allSatisfy({ $0.role == first.role }) else { return nil } return first.role } /// The non-plain runs of a text as `text:role` strings, for compact whole-line expectations. func paintedRuns(_ text: String, _ language: Language?) -> [String] { let source = text as NSString return SyntaxHighlighter.tokens(for: text, language: language) .filter { $0.role != .plain } .map { "\(source.substring(with: NSRange(location: $0.location, length: $0.length))):\($0.role.rawValue)" } }