import Foundation /// Splits text at paragraph, sentence, word and grapheme boundaries with script-aware limits. /// /// Joining `chunks(for:)` with `reassemble(_:)` always returns the input exactly. The chunker does /// not trim, normalise or invent separators; call `TextNormalization.normalizeInput` first. public struct Chunker: Sendable, Equatable { /// The limit for Latin, Cyrillic and Greek text. public let latinLimit: Int /// The limit for CJK, Arabic, Thai, Indic and other dense scripts. public let denseLimit: Int /// Creates a chunker. public init(latinLimit: Int = 4000, denseLimit: Int = 2000) { self.latinLimit = latinLimit self.denseLimit = denseLimit } /// The character limit that applies to `text`. public func limit(for text: String) -> Int { TextScript.isDense(text) ? denseLimit : latinLimit } /// Splits `text` into chunks of at most the script-aware limit. public func chunks(for text: String) -> [TextChunk] { guard !text.isEmpty else { return [] } let limit = max(1, limit(for: text)) var pieces: [(text: String, separator: String)] = [] for unit in paragraphUnits(text) { split(unit.text, trailing: unit.separator, limit: limit, into: &pieces) } return pack(mergingLeadingEmpty(pieces), limit: limit) } /// Reassembles chunks into the original text. public static func reassemble(_ chunks: [TextChunk]) -> String { chunks.sorted { $0.index < $1.index }.reduce(into: "") { result, chunk in result += chunk.text result += chunk.separatorAfter } } // MARK: - Splitting private func split( _ text: String, trailing: String, limit: Int, into pieces: inout [(text: String, separator: String)] ) { if text.count <= limit { pieces.append((text, trailing)) return } let sentences = sentenceUnits(text) if sentences.count > 1 { splitSubunits(sentences, trailing: trailing, limit: limit, into: &pieces) return } let words = wordUnits(text) if words.count > 1 { splitSubunits(words, trailing: trailing, limit: limit, into: &pieces) return } splitGraphemes(text, trailing: trailing, into: &pieces) } private func splitSubunits( _ units: [(text: String, separator: String)], trailing: String, limit: Int, into pieces: inout [(text: String, separator: String)] ) { for (offset, unit) in units.enumerated() { let separator = offset == units.count - 1 ? unit.separator + trailing : unit.separator split(unit.text, trailing: separator, limit: limit, into: &pieces) } } private func splitGraphemes( _ text: String, trailing: String, into pieces: inout [(text: String, separator: String)] ) { let characters = Array(text) for (offset, character) in characters.enumerated() { let separator = offset == characters.count - 1 ? trailing : "" pieces.append((String(character), separator)) } } // MARK: - Units private func paragraphUnits(_ text: String) -> [(text: String, separator: String)] { guard let regex = try? NSRegularExpression(pattern: "\\n[ \\t]*\\n(?:[ \\t]*\\n)*") else { return [(text, "")] } let nsText = text as NSString let matches = regex.matches(in: text, range: NSRange(location: 0, length: nsText.length)) guard !matches.isEmpty else { return [(text, "")] } var units: [(String, String)] = [] var cursor = 0 for match in matches { let body = nsText.substring(with: NSRange(location: cursor, length: match.range.location - cursor)) let separator = nsText.substring(with: match.range) units.append((body, separator)) cursor = match.range.location + match.range.length } let tail = nsText.substring(from: cursor) units.append((tail, "")) return units } private func sentenceUnits(_ text: String) -> [(text: String, separator: String)] { let terminators: Set = [".", "!", "?", "。", "!", "?", "…"] let closers: Set = ["\"", "'", "”", "’", ")", "]", "}"] let characters = Array(text) var units: [(String, String)] = [] var start = 0 var index = 0 while index < characters.count { guard terminators.contains(characters[index]) else { index += 1 continue } var end = index + 1 while end < characters.count, terminators.contains(characters[end]) { end += 1 } while end < characters.count, closers.contains(characters[end]) { end += 1 } guard end < characters.count, characters[end].isWhitespace else { index = end continue } var separatorEnd = end while separatorEnd < characters.count, characters[separatorEnd].isWhitespace { separatorEnd += 1 } let body = String(characters[start ..< end]) let separator = String(characters[end ..< separatorEnd]) units.append((body, separator)) start = separatorEnd index = separatorEnd } if start < characters.count { units.append((String(characters[start...]), "")) } return units.isEmpty ? [(text, "")] : units } private func wordUnits(_ text: String) -> [(text: String, separator: String)] { let characters = Array(text) var units: [(String, String)] = [] var start = 0 var index = 0 while index < characters.count { guard characters[index].isWhitespace else { index += 1 continue } let body = String(characters[start ..< index]) var end = index while end < characters.count, characters[end].isWhitespace { end += 1 } let separator = String(characters[index ..< end]) units.append((body, separator)) start = end index = end } if start < characters.count { units.append((String(characters[start...]), "")) } return units.isEmpty ? [(text, "")] : units } // MARK: - Packing /// Keeps a leading empty body's separator (for example a text starting with `\n\n` or a long /// over-limit text starting with whitespace) by attaching it to the first non-empty piece. private func mergingLeadingEmpty( _ pieces: [(text: String, separator: String)] ) -> [(text: String, separator: String)] { var result = pieces var prefix = "" while let first = result.first, first.text.isEmpty { prefix += first.separator result.removeFirst() } guard !result.isEmpty else { return prefix.isEmpty ? [] : [(prefix, "")] } var first = result[0] first.text = prefix + first.text result[0] = first return result } private func pack( _ pieces: [(text: String, separator: String)], limit: Int ) -> [TextChunk] { var chunks: [TextChunk] = [] var current = "" var trailing = "" var lastSeparator = "" var index = 0 func emit() { guard !current.isEmpty else { return } chunks.append(TextChunk(index: index, text: current, separatorAfter: trailing)) index += 1 current = "" trailing = "" lastSeparator = "" } for piece in pieces { if current.isEmpty { current = piece.text } else if current.count + lastSeparator.count + piece.text.count <= limit { current += lastSeparator + piece.text } else { emit() current = piece.text } trailing = piece.separator lastSeparator = piece.separator } emit() return chunks } }