Sources/OrgIndex/Snippet.swift
56 lines · 3076 bytes
1import Foundation
2
3/// A short passage around the first word a search matched, on one line, with the matched words
4/// marked: what a search result shows under its title.
5public struct Snippet: Sendable, Hashable {
6 public let text: String
7 /// The matched words, as UTF-16 ranges of `text`.
8 public let matches: [Range<Int>]
9
10 public init(text: String, matches: [Range<Int>]) {
11 self.text = text
12 self.matches = matches
13 }
14
15 /// The passage of `text` around the first word starting with one of `prefixes`, compared
16 /// without case or diacritics as the full-text index compares them; nil when none does.
17 public init?(text: String, prefixes: [String], width: Int = 160) {
18 let folded = prefixes.map(Self.fold).filter { !$0.isEmpty }
19 let line = text.split(whereSeparator: \.isWhitespace).joined(separator: " ") as NSString
20 guard !folded.isEmpty, line.length > 0 else { return nil }
21 var words: [(range: NSRange, matches: Bool)] = []
22 let pattern = try! NSRegularExpression(pattern: "[\\p{L}\\p{N}]+")
23 for match in pattern.matches(in: line as String, range: NSRange(location: 0, length: line.length)) {
24 let word = Self.fold(line.substring(with: match.range))
25 words.append((match.range, folded.contains { word.hasPrefix($0) }))
26 }
27 guard let first = words.first(where: \.matches) else { return nil }
28 // Start a few words before the match, at a word's start; end at the last whole word.
29 var start = max(0, first.range.location - 50)
30 if start > 0 { start = words.first { $0.range.location >= start }?.range.location ?? first.range.location }
31 var end = min(line.length, start + width)
32 if end < line.length { end = words.last { NSMaxRange($0.range) <= end }.map { NSMaxRange($0.range) } ?? end }
33 let lead = start > 0 ? "…" : ""
34 self.text = lead + line.substring(with: NSRange(location: start, length: end - start)) + (end < line.length ? "…" : "")
35 let shift = lead.utf16.count - start
36 matches = words.filter { $0.matches && $0.range.location >= start && NSMaxRange($0.range) <= end }
37 .map { ($0.range.location + shift)..<(NSMaxRange($0.range) + shift) }
38 }
39
40 static func fold(_ word: String) -> String {
41 word.folding(options: [.caseInsensitive, .diacriticInsensitive], locale: nil)
42 }
43
44 /// `text` with the matched words strongly emphasized, for a SwiftUI `Text`.
45 public var attributed: AttributedString {
46 var result = AttributedString(text)
47 let utf16 = text.utf16
48 for match in matches {
49 let lower = String.Index(utf16.index(utf16.startIndex, offsetBy: match.lowerBound), within: text)
50 let upper = String.Index(utf16.index(utf16.startIndex, offsetBy: match.upperBound), within: text)
51 guard let lower, let upper, let range = Range(lower..<upper, in: result) else { continue }
52 result[range].inlinePresentationIntent = .stronglyEmphasized
53 }
54 return result
55 }
56}