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