Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
@@ -1,20 +1,7 @@
//
// CTTypesetter+SuggestLineBreak.swift
// TableProTextEngine
//
// Created by Khan Winter on 4/24/25.
//

import AppKit

extension CTTypesetter {
/// Suggest a line break for the given line break strategy.
/// - Parameters:
/// - typesetter: The typesetter to use.
/// - strategy: The strategy that determines a valid line break.
/// - startingOffset: Where to start breaking.
/// - constrainingWidth: The available space for the line.
/// - Returns: An offset relative to the entire string indicating where to break.
// Returns an offset into the whole string, not a length.
func suggestLineBreak(
using string: NSAttributedString,
strategy: LineBreakStrategy,
Expand All @@ -37,20 +24,12 @@ extension CTTypesetter {
}
}

/// Suggest a line break for the character break strategy.
/// - Parameters:
/// - typesetter: The typesetter to use.
/// - startingOffset: Where to start breaking.
/// - constrainingWidth: The available space for the line.
/// - Returns: An offset relative to the entire string indicating where to break.
private func suggestLineBreakForCharacter(
string: NSAttributedString,
startingOffset: Int,
constrainingWidth: CGFloat
) -> Int {
var breakIndex: Int
// Check if we need to skip to an attachment

breakIndex = startingOffset + CTTypesetterSuggestClusterBreak(self, startingOffset, constrainingWidth)
guard breakIndex < string.length else {
return breakIndex
Expand All @@ -64,12 +43,6 @@ extension CTTypesetter {
return breakIndex
}

/// Suggest a line break for the word break strategy.
/// - Parameters:
/// - typesetter: The typesetter to use.
/// - startingOffset: Where to start breaking.
/// - constrainingWidth: The available space for the line.
/// - Returns: An offset relative to the entire string indicating where to break.
private func suggestLineBreakForWord(
string: NSAttributedString,
subrange: NSRange,
Expand All @@ -79,11 +52,12 @@ extension CTTypesetter {
if breakIndex >= subrange.max {
return breakIndex
}
if checkIfLineBreakOnCRLF(breakIndex, for: string) {
let text = string.string as NSString
if LineBreakCharacters.isCRLF(endingAt: breakIndex, in: text) {
return breakIndex + 1
}

let hangingEnd = endOfHangingSpaces(from: breakIndex, before: subrange.max, in: string)
let hangingEnd = endOfHangingSpaces(from: breakIndex, before: subrange.max, in: text)
if hangingEnd > breakIndex {
return hangingEnd
}
Expand All @@ -101,7 +75,7 @@ extension CTTypesetter {
// breaks after the nearest punctuation rather than mid-word.
var index = breakIndex - 1
while breakIndex - index < 100 && index > subrange.location {
if ensureCharacterCanBreakLine(at: index, for: string) {
if LineBreakCharacters.canBreakLine(at: index, in: text) {
return index + 1
}
index -= 1
Expand All @@ -110,9 +84,8 @@ extension CTTypesetter {
return breakIndex
}

/// Spaces and tabs past the edge stay on the line they follow instead of opening the next one.
private func endOfHangingSpaces(from index: Int, before end: Int, in string: NSAttributedString) -> Int {
let text = string.string as NSString
// Spaces and tabs past the edge stay on the line they follow instead of opening the next one.
private func endOfHangingSpaces(from index: Int, before end: Int, in text: NSString) -> Int {
var hangingEnd = index
while hangingEnd < end {
let character = text.character(at: hangingEnd)
Expand All @@ -121,26 +94,28 @@ extension CTTypesetter {
}
return hangingEnd
}
}

/// Ensures the character at the given index can break a line.
/// - Parameter index: The index to check at.
/// - Returns: True, if the character is a whitespace or punctuation character.
private func ensureCharacterCanBreakLine(at index: Int, for string: NSAttributedString) -> Bool {
let subrange = (string.string as NSString).rangeOfComposedCharacterSequence(at: index)
let set = CharacterSet(charactersIn: (string.string as NSString).substring(with: subrange))
return set.isSubset(of: .whitespacesAndNewlines) || set.isSubset(of: .punctuationCharacters)
}
enum LineBreakCharacters {
private static let whitespace = CharacterSet.whitespacesAndNewlines
private static let punctuation = CharacterSet.punctuationCharacters

/// Check if the break index is on a CRLF (`\r\n`) character, indicating a valid break position.
/// - Parameter breakIndex: The index to check in the string.
/// - Returns: True, if the break index lies after the `\n` character in a `\r\n` sequence.
private func checkIfLineBreakOnCRLF(_ breakIndex: Int, for string: NSAttributedString) -> Bool {
guard breakIndex - 1 > 0 && breakIndex + 1 <= string.length else {
// True when the composed sequence at `index` is all whitespace or all punctuation. A unit that is a whole
// scalar in neither set already rules its sequence out, so a letter or digit costs no substring.
static func canBreakLine(at index: Int, in text: NSString) -> Bool {
let unit = text.character(at: index)
if !UTF16.isLeadSurrogate(unit), !UTF16.isTrailSurrogate(unit), let scalar = Unicode.Scalar(unit),
!whitespace.contains(scalar), !punctuation.contains(scalar) {
return false
}
let substringRange = NSRange(location: breakIndex - 1, length: 2)
let substring = string.attributedSubstring(from: substringRange).string
let scalars = text.substring(with: text.rangeOfComposedCharacterSequence(at: index)).unicodeScalars
return scalars.allSatisfy { whitespace.contains($0) } || scalars.allSatisfy { punctuation.contains($0) }
}

return substring == LineEnding.carriageReturnLineFeed.rawValue
static func isCRLF(endingAt breakIndex: Int, in text: NSString) -> Bool {
guard breakIndex - 1 > 0 && breakIndex + 1 <= text.length else {
return false
}
return text.character(at: breakIndex - 1) == 0x0D && text.character(at: breakIndex) == 0x0A
}
}
Original file line number Diff line number Diff line change
@@ -1,8 +1,3 @@
//
// TypesetterWordBreakTests.swift
// TableProTextEngineTests
//

import AppKit
import Foundation
@testable import TableProTextEngine
Expand All @@ -15,7 +10,7 @@ struct TypesetterWordBreakTests {
.font: NSFont.monospacedSystemFont(ofSize: 12, weight: .regular)
]

/// The text of each wrapped fragment when a line is `columns` characters wide.
// The text of each wrapped fragment when a line is `columns` characters wide.
private func fragments(_ text: String, columns: Int) -> [String] {
let characterWidth = ("x" as NSString).size(withAttributes: Self.attributes).width
let length = (text as NSString).length
Expand Down Expand Up @@ -83,4 +78,99 @@ struct TypesetterWordBreakTests {
#expect(wrapped.joined() == text)
#expect((wrapped.first?.count ?? 0) > "日本語。".count)
}

@Test("A run with no punctuation in reach breaks at the edge")
func unbreakableRunBreaksAtTheEdge() {
let run = String(repeating: "a", count: 300)
#expect(fragments(run, columns: 120).map { $0.count } == [120, 120, 60])
}

@Test("Punctuation 99 characters back from the edge is in reach, 100 back is not")
func punctuationSearchReachesBack99Characters() {
func run(underscoreAt offset: Int) -> String {
var characters = Array(repeating: "a", count: 300)
characters[offset] = "_"
return characters.joined()
}

#expect(fragments(run(underscoreAt: 21), columns: 120).first?.count == 22)
#expect(fragments(run(underscoreAt: 20), columns: 120).first?.count == 120)
}

// The search walks back from the edge to one past the fragment's start, which here is the low surrogate.
@Test("Supplementary punctuation whose low surrogate is the last offset searched still breaks after it")
func supplementaryPunctuationAtTheSearchsEnd() {
let text = "\u{1E95E}" + String(repeating: "a", count: 200)
#expect(fragments(text, columns: 30).first == "\u{1E95E}")
}

@Test("The break test answers what the composed-sequence rule answers, at every offset of 2,000 strings")
func breakTestMatchesTheComposedSequenceRule() {
var generator = SplitMix64(seed: 0x5EED_1E55)
var mismatches: [String] = []
for _ in 0..<2_000 {
let text = Self.generatedText(using: &generator)
let reference = NSAttributedString(string: text as String)
for index in 0..<text.length
where LineBreakCharacters.canBreakLine(at: index, in: text) != Self.referenceCanBreak(at: index, for: reference) {
mismatches.append("break at \(index) of \((text as String).debugDescription)")
}
for index in 0...text.length
where LineBreakCharacters.isCRLF(endingAt: index, in: text) != Self.referenceIsCRLF(index, for: reference) {
mismatches.append("CRLF at \(index) of \((text as String).debugDescription)")
}
}
#expect(mismatches.isEmpty, "\(mismatches.prefix(5))")
}

// The helpers as they were before the break test stopped building character sets.
private static func referenceCanBreak(at index: Int, for string: NSAttributedString) -> Bool {
let subrange = (string.string as NSString).rangeOfComposedCharacterSequence(at: index)
let set = CharacterSet(charactersIn: (string.string as NSString).substring(with: subrange))
return set.isSubset(of: .whitespacesAndNewlines) || set.isSubset(of: .punctuationCharacters)
}

private static func referenceIsCRLF(_ breakIndex: Int, for string: NSAttributedString) -> Bool {
guard breakIndex - 1 > 0 && breakIndex + 1 <= string.length else {
return false
}
return string.attributedSubstring(from: NSRange(location: breakIndex - 1, length: 2)).string == "\r\n"
}

private static let pieces: [[unichar]] = {
let strings = [
"a", "Z", "x9", "0", "_", ".", ",", "-", "(", ")", "\"", "'", "/", ":", ";", "!", "?", "#", "%", "&", "*", "@",
"[", "]", "{", "}", "\\", "$", "+", "<", "=", ">", "^", "`", "|", "~",
" ", "\t", "\n", "\r", "\r\n", "\u{00A0}", "\u{3000}", "\u{200B}", "\u{2028}", "\u{0085}",
".\u{0301}", ",\u{20DD}", "_\u{0308}", " \u{0301}", "\u{0301}", "\u{0600}1", "\u{0600}.",
"😀", "👩‍💻", "👍🏽", "🇻🇳", "1\u{FE0F}\u{20E3}", "日本", "。", "、", "「", "」", "ー", "\u{1100}\u{1161}",
"\u{10100}", "\u{1039F}", "\u{1E95E}", "\u{12470}", "\u{1D400}", "\u{20000}",
]
return strings.map { Array($0.utf16) } + [[0xD800], [0xDC00], [0xDBFF, 0x41], [0x2E, 0xDC00]]
}()

private static func generatedText(using generator: inout SplitMix64) -> NSString {
var units: [unichar] = []
let count = Int.random(in: 1...24, using: &generator)
for _ in 0..<count {
units += pieces.randomElement(using: &generator) ?? []
}
return NSString(characters: units, length: units.count)
}
}

private struct SplitMix64: RandomNumberGenerator {
private var state: UInt64

init(seed: UInt64) {
state = seed
}

mutating func next() -> UInt64 {
state &+= 0x9E37_79B9_7F4A_7C15
var value = state
value = (value ^ (value >> 30)) &* 0xBF58_476D_1CE4_E5B9
value = (value ^ (value >> 27)) &* 0x94D0_49BB_1331_11EB
return value ^ (value >> 31)
}
}
Loading
Loading