Repository Public
1// =============================================================================2// SP BOUCHER | SOFTWARE & RESEARCH3// ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4// =============================================================================5//6// PROJECT METADATA7// -----------------------------------------------------------------------------8// Project : SP Keyboard9// File : Shared/Sources/KeyboardCore/TextAnalysis.swift10// Description : Pure functions over the text around the cursor: current11// word, previous words, sentence starts, word boundaries for12// deletion, and the pacing of continuous delete.13// Module : KeyboardCore14// Repository : https://git.spboucher.ai/sp-keyboard15// 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 TextAnalysis {93 /// Characters that belong to a word being typed (letters, digits, and in-word apostrophes / hyphens).94 public static func isWordCharacter(_ character: Character) -> Bool {95 character.isLetter || character.isNumber || character == "'" || character == "’" || character == "-" || character == "_"96 }9798 /// The partial word immediately before the cursor ("" after a space or punctuation).99 public static func currentWord(in before: String?) -> String {100 guard let before, !before.isEmpty else { return "" }101 var start = before.endIndex102 while start > before.startIndex {103 let previous = before.index(before: start)104 guard isWordCharacter(before[previous]) else { break }105 start = previous106 }107 var word = before[start...]108 // A leading apostrophe or hyphen is punctuation, not part of the word.109 while let first = word.first, !(first.isLetter || first.isNumber) { word = word.dropFirst() }110 return String(word)111 }112113 /// Up to `limit` complete words before the current one, nearest last. Stops at a sentence boundary.114 public static func previousWords(in before: String?, limit: Int = 2) -> [String] {115 guard let before, !before.isEmpty else { return [] }116 let current = currentWord(in: before)117 var rest = before.dropLast(current.count)118 var words: [String] = []119 while words.count < limit {120 while let last = rest.last, last == " " || last == "\u{00A0}" { rest = rest.dropLast() }121 guard let last = rest.last, isWordCharacter(last) else { break }122 var word = ""123 while let character = rest.last, isWordCharacter(character) {124 word.insert(character, at: word.startIndex)125 rest = rest.dropLast()126 }127 words.insert(word, at: 0)128 }129 return words130 }131132 static let sentenceEnders: Set<Character> = [".", "!", "?", "…"]133134 /// True when the next typed letter starts a sentence.135 public static func isSentenceStart(_ before: String?) -> Bool {136 guard let before, !before.isEmpty else { return true }137 guard let last = before.last, last.isWhitespace else { return false }138 if last.isNewline { return true }139 let trimmed = before.reversed().drop(while: { $0.isWhitespace })140 guard var significant = trimmed.first else { return true }141 // Closing quotes and brackets after the period still end the sentence.142 var remaining = trimmed.dropFirst()143 while ["\"", "”", "»", ")", "’", "'"].contains(significant) || significant.isWhitespace, let next = remaining.first {144 significant = next145 remaining = remaining.dropFirst()146 }147 return sentenceEnders.contains(significant)148 }149150 public static func isWordStart(_ before: String?) -> Bool {151 guard let last = before?.last else { return true }152 return last.isWhitespace153 }154155 /// Number of characters a "delete word" removes: trailing spaces, then the word (or one run of punctuation).156 public static func wordDeletionCount(in before: String?) -> Int {157 guard let before, !before.isEmpty else { return 0 }158 var count = 0159 var rest = Substring(before)160 while let last = rest.last, last == " " {161 rest = rest.dropLast()162 count += 1163 }164 guard let last = rest.last else { return count }165 if last.isNewline { return count == 0 ? 1 : count }166 if isWordCharacter(last) {167 while let character = rest.last, isWordCharacter(character) {168 rest = rest.dropLast()169 count += 1170 }171 } else {172 count += 1173 }174 return count175 }176177 /// Tokens the engine must never autocorrect or capitalise on its own.178 public static func looksLikeMachineToken(_ word: String) -> Bool {179 guard !word.isEmpty else { return false }180 if word.contains("@") || word.contains("://") || word.contains("_") { return true }181 if word.contains(where: \.isNumber) { return true }182 if word.contains(".") && !word.hasSuffix(".") { return true }183 return false184 }185}186187/// Pacing of the continuous delete: characters first, then whole words, with a bounded top speed.188public enum DeleteAcceleration {189 public enum Granularity: Equatable, Sendable { case character, word }190191 public static let initialDelay = 0.42192 public static let wordThreshold = 22193 public static let minimumInterval = 0.045194195 /// Delay before repeat number `n` (0-based) fires.196 public static func interval(forRepeat n: Int) -> Double {197 if n >= wordThreshold { return 0.16 }198 let ramp = 0.11 - Double(n) * 0.004199 return max(minimumInterval, ramp)200 }201202 public static func granularity(forRepeat n: Int) -> Granularity {203 n >= wordThreshold ? .word : .character204 }205}206