# Copyright (c) 2026 Krzysztof Rudnicki. MIT licence. """How far one typed word is from another, and which command a typo meant. ``difflib`` was the obvious candidate and it is the wrong one. Its ratio is built out of matching blocks, which is exactly what a transposition destroys: "!cta" against "!cat" scores 0.75, but "!cta" against "!kot" scores 0.50. No single cutoff both catches the first and rejects the second on principle rather than by luck. Optimal string alignment counts a swap as one edit, which is what somebody who typed the letters in the wrong order actually did. Both sides are expected to be folded already -- see ``signal_bot.folding``. Comparing a folded trigger against an unfolded word would measure the alphabet somebody's keyboard was in rather than how badly they mistyped. """ from __future__ import annotations from typing import TYPE_CHECKING, Final if TYPE_CHECKING: from collections.abc import Iterable # A short word has no room to be wrong twice, and five characters is still # short. Measured against the shipped aliases.json: at a boundary of four, # two edits put four pairs of *different* commands within reach of each # other -- !pies/!popes, !days/!cats, !dzis/!dni and !mnie/!dni, every one # of them exactly five characters long. Moving the boundary to five removes # all four and costs nothing, because every real typo this feature was # written for (!cta, !kto, !gekno, !papiesz, !stat, !rok2, !korna) is one # edit away, not two. test_no_two_commands_are_within_reach_of_each_other # fails if a future alias reopens the gap. SHORT: Final = 5 SHORT_BUDGET: Final = 1 LONG_BUDGET: Final = 2 # A candidate this short is not a suggestion, it is a magnet. "!ja" is three # characters, so at a budget of one edit it sits within reach of roughly # forty of the 676 two-letter words somebody could type: !aa, !ba, !ca, !da # and so on all "meant" !ja, and so did !jak and !nie. Refusing to offer # anything shorter costs exactly one real command its typo correction -- # measured against the live aliases.json, !ja is the only trigger the rule # excludes -- and buys silence for all forty. MIN_CANDIDATE: Final = 4 def distance(one: str, other: str) -> int: """Optimal string alignment distance between two words. Damerau-Levenshtein restricted to adjacent transpositions: insertion, deletion and substitution each cost one, and swapping two neighbouring characters costs one rather than the two a plain Levenshtein charges. Args: one: The first word. other: The second word. Returns: The number of edits that turn one into the other. """ rows, columns = len(one), len(other) grid = [[0] * (columns + 1) for _ in range(rows + 1)] for row in range(rows + 1): grid[row][0] = row for column in range(columns + 1): grid[0][column] = column for row in range(1, rows + 1): for column in range(1, columns + 1): cost = 0 if one[row - 1] == other[column - 1] else 1 best = min( grid[row - 1][column] + 1, grid[row][column - 1] + 1, grid[row - 1][column - 1] + cost, ) # The transposition arm. Guarded on both indices because it # reaches two cells back in each direction, and the first row # and column of the grid are the base case rather than real # comparisons. if ( row > 1 and column > 1 and one[row - 1] == other[column - 2] and one[row - 2] == other[column - 1] ): best = min(best, grid[row - 2][column - 2] + 1) grid[row][column] = best return grid[rows][columns] def budget(length: int) -> int: """How many edits a word of this length may be wrong by.""" return SHORT_BUDGET if length <= SHORT else LONG_BUDGET def nearest(token: str, candidates: Iterable[str]) -> str | None: """The candidate a token most likely meant, or None if none is close. Ties are broken by distance, then by length, then alphabetically. That ordering is not cosmetic: without it the suggestion would depend on the iteration order of the registry, and the same typo would get different answers on different runs. Args: token: The folded word somebody typed, including its "!". candidates: Every folded trigger it could plausibly have meant. Anything shorter than MIN_CANDIDATE is never offered. Returns: The closest candidate within budget, or None. """ ranked = sorted( (distance(token, one), len(one), one) for one in candidates if len(one) >= MIN_CANDIDATE ) if not ranked or ranked[0][0] > budget(len(token)): return None return ranked[0][2]