// THE app's match underline — split a result line into words and say which // ones the query touches, so a row can set a pencil under them. // // **Literal, never a pattern.** A person searching for "." or "(" is searching // for a character, and a regex built from the query would either throw or match // the whole line. That is why this compares with `range(of:)` and `.literal` // rather than compiling anything, and `.caseInsensitive` as an OPTION rather // than by lowercasing both sides. import Foundation /// One word of a result line: the characters (with the space that follows /// them, so a wrap breaks between words), and whether a pencil goes under it. /// /// The unit is the WORD, not the matched characters: a person underlines /// words, and a line that broke "escalation" in two to underline "esc" would /// wrap mid-word. A word wears the pencil when any token of the query is found /// inside it — a literal, case-insensitive comparison, for the reasons in the /// file header. public struct UnderlineWord: Equatable, Sendable, Identifiable { public let text: String public let underlined: Bool public let index: Int public var id: Int { index } public init(text: String, underlined: Bool, index: Int) { self.text = text self.underlined = underlined self.index = index } } /// Split a line into words and say which ones the query touches. public func underlineWords(_ text: String, query: String) -> [UnderlineWord] { let tokens = query .trimmingCharacters(in: .whitespacesAndNewlines) .components(separatedBy: .whitespacesAndNewlines) .filter { !$0.isEmpty } let words = text .components(separatedBy: .whitespacesAndNewlines) .filter { !$0.isEmpty } return words.enumerated().map { index, word in let last = index == words.count - 1 let touched = tokens.contains { token in word.range(of: token, options: [.caseInsensitive, .literal]) != nil } return UnderlineWord(text: last ? word : word + " ", underlined: touched, index: index) } }