Repository Public
1// =============================================================================2// SP BOUCHER | SOFTWARE & RESEARCH3// ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4// =============================================================================5//6// PROJECT METADATA7// -----------------------------------------------------------------------------8// Project : SP Search iOS9// File : Core/Sources/SPSearchKit/Highlighter.swift10// Description : Query-term highlighting, insensitive to case and11// diacritics, anchored at word starts.12// Module : SPSearchKit13// Repository : https://git.spboucher.ai/sp-search-ios14// Project Website : https://search.spboucher.ai15// Created : 2026-12-0116// Last Modified : 2026-12-0117//18// =============================================================================19// AUTHOR & PROFESSIONAL AFFILIATION20// =============================================================================21//22// Author : Simon-Pierre Boucher23// Position : Professor of Finance24// Institution : Université du Québec en Outaouais (UQO)25// Department : Département des sciences administratives26// Organization : SP Boucher27//28// Website : https://spboucher.ai29// Git : https://git.spboucher.ai30//31// =============================================================================32// OFFICIAL CONTACT DIRECTORY33// =============================================================================34//35// General : info@spboucher.ai36// Professional : contact@spboucher.ai37// Direct : simon@spboucher.ai38// Research : research@spboucher.ai39// Development : dev@spboucher.ai40// Support : support@spboucher.ai41// Security/Admin : admin@spboucher.ai42// Notifications : notifications@spboucher.ai43//44// Preferred Contact: support@spboucher.ai45//46// =============================================================================47// COPYRIGHT & INTELLECTUAL PROPERTY48// =============================================================================49//50// Copyright (c) 202651// Simon-Pierre Boucher52//53// All rights reserved where applicable.54//55// This file is governed by the applicable project license,56// copyright notices, institutional agreements and relevant law.57//58// Unless expressly authorized by the applicable license or59// rights holder, copying, redistribution, sublicensing,60// publication and commercial exploitation are not permitted.61//62// Existing third-party rights and notices remain unaffected.63//64// =============================================================================65// CONFIDENTIALITY & SECURITY66// =============================================================================67//68// Classification : Public69// Distribution : Public repository; use is governed by the project license70// Security Contact : admin@spboucher.ai71//72// Access to this source does not independently grant permission73// to redistribute or disclose confidential materials.74//75// Do not embed credentials, private keys, access tokens,76// certificates or confidential personal information.77//78// =============================================================================79// LICENSE & MAINTENANCE80// =============================================================================81//82// License : None specified (no license file in this repository)83// Maintainer : Simon-Pierre Boucher84// Technical Contact: dev@spboucher.ai85//86// =============================================================================87// END OF SP BOUCHER SOURCE HEADER88// =============================================================================8990import Foundation9192public enum Highlighter {93 /// Comparison form: no case, no diacritics, typographic apostrophes straightened.94 public static func fold(_ s: String) -> String {95 s.folding(options: [.caseInsensitive, .diacriticInsensitive, .widthInsensitive], locale: nil)96 .replacingOccurrences(of: "’", with: "'")97 }9899 /// Sorted, non-overlapping ranges of `text` where a term begins a word. "universite" marks "Université".100 public static func ranges(in text: String, terms: [String]) -> [Range<String.Index>] {101 guard !text.isEmpty else { return [] }102 var found: [Range<String.Index>] = []103 let options: String.CompareOptions = [.caseInsensitive, .diacriticInsensitive, .widthInsensitive]104 for raw in terms {105 let term = raw.replacingOccurrences(of: "’", with: "'")106 guard !term.isEmpty else { continue }107 for needle in Set([term, term.replacingOccurrences(of: "'", with: "’")]) {108 var from = text.startIndex109 while from < text.endIndex, let r = text.range(of: needle, options: options, range: from..<text.endIndex, locale: nil) {110 if r.isEmpty { break }111 if startsWord(text, at: r.lowerBound) { found.append(r) }112 from = text.index(after: r.lowerBound)113 }114 }115 }116 guard !found.isEmpty else { return [] }117 found.sort { $0.lowerBound < $1.lowerBound }118 var merged: [Range<String.Index>] = [found[0]]119 for r in found.dropFirst() {120 if let last = merged.last, r.lowerBound <= last.upperBound {121 merged[merged.count - 1] = last.lowerBound..<max(last.upperBound, r.upperBound)122 } else {123 merged.append(r)124 }125 }126 return merged127 }128129 private static func startsWord(_ text: String, at i: String.Index) -> Bool {130 guard i > text.startIndex else { return true }131 let before = text[text.index(before: i)]132 return !(before.isLetter || before.isNumber)133 }134135 /// The text with marked ranges flagged `stronglyEmphasized`; the app gives them their colour and weight.136 public static func attributed(_ text: String, terms: [String]) -> AttributedString {137 var a = AttributedString(text)138 for r in ranges(in: text, terms: terms) {139 if let lo = AttributedString.Index(r.lowerBound, within: a), let hi = AttributedString.Index(r.upperBound, within: a) {140 a[lo..<hi].inlinePresentationIntent = .stronglyEmphasized141 }142 }143 return a144 }145146 /// Server marks: `[start, end)` counted in Unicode code points of `text` (V2 `highlights`). Offsets beyond the text147 /// are clamped, empty or reversed intervals dropped, and a bound that falls inside a grapheme cluster (a flag, an148 /// emoji with a modifier, a letter with a combining accent) is moved outward so the whole character is marked.149 /// Result: sorted, non-overlapping ranges.150 public static func ranges(in text: String, codePoints: [Range<Int>]) -> [Range<String.Index>] {151 guard !text.isEmpty, !codePoints.isEmpty else { return [] }152 let scalars = text.unicodeScalars153 let count = scalars.count154 var found: [Range<String.Index>] = []155 for r in codePoints.sorted(by: { $0.lowerBound < $1.lowerBound }) {156 let lo = max(0, r.lowerBound), hi = min(count, r.upperBound)157 guard lo < hi else { continue }158 let a = scalars.index(scalars.startIndex, offsetBy: lo)159 let b = scalars.index(a, offsetBy: hi - lo)160 // Outward to character boundaries.161 let start = text.rangeOfComposedCharacterSequence(at: a).lowerBound162 let end = b == text.endIndex ? b : (text.rangeOfComposedCharacterSequence(at: b).lowerBound == b ? b : text.rangeOfComposedCharacterSequence(at: b).upperBound)163 guard start < end else { continue }164 if let last = found.last, start <= last.upperBound {165 found[found.count - 1] = last.lowerBound..<max(last.upperBound, end)166 } else {167 found.append(start..<end)168 }169 }170 return found171 }172173 /// The text with the server's marks flagged `stronglyEmphasized`.174 public static func attributed(_ text: String, codePoints: [Range<Int>]) -> AttributedString {175 var a = AttributedString(text)176 for r in ranges(in: text, codePoints: codePoints) {177 if let lo = AttributedString.Index(r.lowerBound, within: a), let hi = AttributedString.Index(r.upperBound, within: a) {178 a[lo..<hi].inlinePresentationIntent = .stronglyEmphasized179 }180 }181 return a182 }183}184