iOS: punctuation after a word fixes its typo, as space does

X (Erick): "If I add punctuation after a typo autocorrect does not fix the typo."
Only space ran autocorrect, so "teh," or "recieve." kept the typo. Now a mark
that closes a word (, . ! ? ; : ) and ") runs the same correction as space,
from the 123 page or a 123 slide, and goes in after the fix ("the,"), as the
system keyboard does. One backspace right after takes back the mark and the fix
("teh"), the same as after a space, and the kept word isn't corrected again.
A period never corrects a common abbreviation (approx., etc., dept.) and a
swiped word is never corrected (it is a reading, not a typo).

Verified: new FullKeyboardEngineTests (testPunctuationAfterATypoFixesItFirst,
testPunctuationNeverChangesASwipedWord) pass on an iOS 27.2 simulator. Autocorrect
benchmark (Spatial autocorrect on): a new 300-sentence punctuation set goes from
12.40% to 7.10% WER and 96 to 177 sentences exactly right; the held-out sets are
unchanged (EN 5.94%, ES 8.61% WER; 79 and 23 correct words broken).
This commit is contained in:
Ryan Vogel
2026-11-20 23:45:43 -05:00
parent d65f5f76f0
commit fb6200dfea
3 changed files with 109 additions and 4 deletions
@@ -1243,6 +1243,56 @@ final class FullKeyboardEngineTests: XCTestCase {
XCTAssertEqual(field.text, "hi ther")
}
/// Types a mark from the 123 page; the next space goes back to the letters.
private func punctuate(_ mark: String) {
if engine.layout.layer == .letters { tap(.layerSwitch(.numbers)) }
tap(.character(mark))
now += 0.5
}
/// X (Erick): "If I add punctuation after a typo autocorrect does not fix the typo." A
/// mark that closes a word fixes it as space does and goes in after the fix, as on Apple's
/// keyboard; backspace right after takes both back, as after a space.
func testPunctuationAfterATypoFixesItFirst() {
for mark in [",", ".", "!", "?", ";", ":", ")", "\""] {
target = FixtureTextTarget()
target.autocapitalizationType = UITextAutocapitalizationType.none
engine = FullKeyboardEngine(target: target, autocorrect: AutocorrectEngine(learnedWords: LearnedWordsStore(defaults: defaults)))
engine.width = 393
engine.clock = { [unowned self] in self.now }
engine.configureForField()
type("see teh")
punctuate(mark)
XCTAssertEqual(target.text, "see the" + mark, mark)
type(" ok")
XCTAssertEqual(target.text, "see the\(mark) ok", mark)
}
type(" recieve")
punctuate(".")
XCTAssertTrue(target.text.hasSuffix(" receive."))
tap(.delete)
XCTAssertTrue(target.text.hasSuffix(" recieve"), "one backspace takes back the mark and the fix")
punctuate(".")
XCTAssertTrue(target.text.hasSuffix(" recieve."), "the word you kept stays")
type(" approx")
punctuate(".")
XCTAssertTrue(target.text.hasSuffix(" approx."), "an abbreviation's period")
type(" a")
punctuate(",")
XCTAssertTrue(target.text.hasSuffix(" a,"))
}
func testPunctuationNeverChangesASwipedWord() throws {
let (field, plane) = try swipeKeyboard()
plane.engine.autocorrect.loadLexiconEntries([("hello", "Hello, friend")])
swipe("hello", on: plane)
tap(.layerSwitch(.numbers), on: plane)
tap(.character(","), on: plane)
XCTAssertEqual(field.text, "hello,", "a swiped word is a reading, not a typo")
}
func testDeleteSwipeWordsMatchOptionDelete() {
XCTAssertNil(DeleteWordSwipe.wordLength(before: ""))
XCTAssertEqual(DeleteWordSwipe.wordLength(before: "Hello, world. "), 7)
@@ -1125,6 +1125,14 @@ final class AutocorrectEngine {
"shell": "she'll",
]
/// Words a period after them makes an abbreviation ("approx.", "etc."): a period never
/// corrects them.
static let abbreviations: Set<String> = [
"approx", "appt", "apt", "assn", "asst", "ave", "blvd", "cf", "co", "corp", "dept", "dr",
"eg", "est", "etc", "fig", "govt", "ie", "inc", "jr", "lb", "lbs", "ltd", "misc", "mr",
"mrs", "ms", "mt", "no", "nr", "oz", "pp", "prof", "pt", "rd", "sr", "st", "vol", "vs", "wk", "yr",
]
/// Common chat & engineering shorthand that cautious autocorrect never rewrites.
static let shorthandAllowlist: Set<String> = [
"ok", "okay", "ty", "thx", "pls", "plz", "tmrw", "tbh", "idk", "imo", "imho",
@@ -752,8 +752,10 @@ final class FullKeyboardEngine {
// a slide: nothing, and back too. Off the keys: nothing, and the page stays.
if let returnLayer = touch.returnLayer {
if let under = slideTarget(for: touch, at: point), let character = under.character {
autocorrect.clearPendingUndo()
insert(character, source: "slide")
if !correctWord(endingWith: character) {
autocorrect.clearPendingUndo()
insert(character, source: "slide")
}
layerState.switchTo(returnLayer)
rebuildLayout(cause: "layer_slide")
refreshAutoCapitalization()
@@ -925,11 +927,56 @@ final class FullKeyboardEngine {
if layerState.layer == .letters {
shift.didType()
}
autocorrect.clearPendingUndo()
insert(text, source: "key", at: point)
if !correctWord(endingWith: text) {
autocorrect.clearPendingUndo()
insert(text, source: "key", at: point)
}
logState("typed")
}
/// Punctuation that closes a word, as Apple's keyboard treats it: , . ! ? ; : ) and ".
static let wordEnders: Set<Character> = [",", ".", "!", "?", ";", ":", ")", "\""]
/// Punctuation right after a word corrects it as space does ("teh," becomes "the,"), and
/// goes in after the fix. Backspace right after takes back both, as after a space ("teh").
/// False when there is nothing to fix: the caller types the mark as usual.
private func correctWord(endingWith text: String) -> Bool {
guard text.count == 1, let mark = text.first, Self.wordEnders.contains(mark), swipedWord == nil else { return false }
let before = target.documentContextBeforeInput
guard let last = before?.last, last.isLetter, let token = AutocorrectEngine.currentToken(in: before) else { return false }
// "approx." and "etc." are abbreviations, not typos.
if mark == ".", AutocorrectEngine.abbreviations.contains(token.lowercased()) { return false }
learning?.didFinish(word: token)
syncLearning()
autocorrect.decoderTaps = currentTokenTaps
guard let (original, replacement) = autocorrect.replacementOnSpace(
beforeInput: before,
field: field,
autocorrectionType: target.autocorrectionType
) else { return false }
for _ in 0..<original.count {
target.deleteBackward()
}
let inserted = replacement + text
tokenTaps.removeAll()
typingLog?.edit("autocorrect", [
TypingLogField("from", .string(original)),
TypingLogField("to", .string(replacement)),
TypingLogField("deleted", .string(original)),
TypingLogField("inserted", .string(inserted)),
TypingLogField("ending", .string(text)),
])
target.insertText(inserted)
autocorrect.recordAppliedCorrection(original: original, insertedText: inserted)
learning?.record(.autocorrected, typed: original, final: replacement)
swipedWord = nil
lastSpaceAt = nil
layerState.didInsert(text)
rebuildLayoutIfNeeded()
didEdit()
return true
}
/// The taps of the word being typed when every letter came from a key, else nil.
private var currentTokenTaps: [CGPoint]? {
let taps = tokenTaps.compactMap { $0 }