feat(input): expand Araso Han/Eng contractions, acronyms, typo recovery, and fast cursor-tail replacement

This commit is contained in:
Yun Chan 2026-10-28 10:41:26 +09:00
parent 51bf664302
commit f403111256
80 changed files with 1449 additions and 458 deletions

View file

@ -838,11 +838,11 @@ export class TerminalKeystrokeTracker {
this._committed = this._committed.slice(0, this._unreplacedStart) + convertedTail
} else if (
this._unreplacedStart === 0 &&
raw.startsWith(this.currentPrefix()) &&
raw.length > this.currentPrefix().length
this._lastXtermValue === '' &&
this._committed.length === 0 &&
this._composingKeys.length === 0
) {
this._committed = raw
this._composingKeys = ''
}
}
this._lastXtermValue = raw

View file

@ -15,8 +15,12 @@ import {
CORE_KOREAN_WORDS,
KOREAN_COUNTER_KEYS,
PARTICLE_KEYS,
finalSoundOfAcronym,
finalSoundOfHangul,
isUrlOrPathRun,
lingersAfterKoreanShift,
normalizeLingeringShift,
particleAgrees,
splitMixedWord
} from './araso-layout'
@ -432,7 +436,7 @@ const COMMON_ENGLISH_WORDS: ReadonlySet<string> = new Set(
'wait walk wall watch water weapon wear weight west whatever ' +
'whether white whole wide wife wind window wish within without ' +
'woman wonder word worker worry write writer wrong yard ' +
'yeah young yourself ' +
'yeah young yourself myself himself herself ourselves themselves yourselves ' +
'button menu view mode state value error warning info debug output input process thread local cloud ' +
' column filter sort count average limit delay timeout retry cancel accept reject ignore clear reset ' +
'load copy paste undo redo select focus blur click press enter shift ctrl alt tab esc backspace delete ' +
@ -536,6 +540,8 @@ export interface LayoutDetectOptions {
afterEnglishWord?: boolean
/** 바로 뒤 토큰이 영문(또는 한글 자판으로 친 영문)인가 */
nextIsEnglish?: boolean
/** 토큰 바로 뒤에 공백·문장부호 등 단어 경계가 이미 확정되었는가 (예: "ㅑ " → "I ") */
hasWordBoundaryAfter?: boolean
/** 슬래시 쌍(ska/du)·약어 조사(L.A.fh)처럼 1음절 변환을 폭넓게 허용할 문맥인가 */
allowSingleSyllable?: boolean
/** 개인 어휘(소문자 영단어 → 빈도) */
@ -727,6 +733,228 @@ function findAdjacentTransposedEnglishWord(latin: string): string | null {
return null
}
const QWERTY_ADJACENT: Readonly<Record<string, string>> = {
q: 'wa',
w: 'qeasd',
e: 'wsdr',
r: 'edft',
t: 'rfgy',
y: 'tghu',
u: 'yhji',
i: 'ujko',
o: 'iklp',
p: 'ol',
a: 'qwsxz',
s: 'qweadzx',
d: 'wersfxc',
f: 'ertdgcv',
g: 'rtyfhvb',
h: 'tyugjbn',
j: 'yuihknm',
k: 'uiojlm',
l: 'opk',
z: 'asx',
x: 'zsdc',
c: 'xdfv',
v: 'cfgb',
b: 'vghn',
n: 'bhjm',
m: 'njk'
}
function isQwertyAdjacent(a: string, b: string): boolean {
const la = a.toLowerCase()
const lb = b.toLowerCase()
return Boolean(QWERTY_ADJACENT[la]?.includes(lb))
}
const ENGLISH_CONTRACTIONS: Readonly<Record<string, string>> = {
"can't": "can't",
"cann't": "can't",
"don't": "don't",
"donn't": "don't",
"doesn't": "doesn't",
"didn't": "didn't",
"won't": "won't",
"isn't": "isn't",
"aren't": "aren't",
"wasn't": "wasn't",
"weren't": "weren't",
"haven't": "haven't",
"hasn't": "hasn't",
"hadn't": "hadn't",
"couldn't": "couldn't",
"wouldn't": "wouldn't",
"shouldn't": "shouldn't",
"mustn't": "mustn't",
"mightn't": "mightn't",
"i'm": "I'm",
"i've": "I've",
"i'll": "I'll",
"i'd": "I'd",
"you're": "you're",
"you've": "you've",
"you'll": "you'll",
"you'd": "you'd",
"he's": "he's",
"he'll": "he'll",
"he'd": "he'd",
"she's": "she's",
"she'll": "she'll",
"she'd": "she'd",
"it's": "it's",
"it'll": "it'll",
"we're": "we're",
"we've": "we've",
"we'll": "we'll",
"we'd": "we'd",
"they're": "they're",
"they've": "they've",
"they'll": "they'll",
"they'd": "they'd",
"that's": "that's",
"that'll": "that'll",
"what's": "what's",
"where's": "where's",
"when's": "when's",
"who's": "who's",
"why's": "why's",
"how's": "how's",
"let's": "let's",
"there's": "there's",
"here's": "here's"
}
function resolveContraction(candidate: string): string | null {
const lower = candidate.toLowerCase()
const contraction = ENGLISH_CONTRACTIONS[lower]
if (!contraction) return null
return /^[iI]'|^I'/u.test(contraction) ? contraction : matchCase(candidate, contraction)
}
function resolveExactOrKnownEnglish(candidate: string): string | null {
const contraction = resolveContraction(candidate)
if (contraction) return contraction
if (/^[A-Za-z]+$/u.test(candidate) && isCommonEnglishWord(candidate)) return candidate
const known = fixKnownMisspelling(candidate)
if (known) return known
return null
}
/**
* 낱자가 섞인 두벌식 영타(정상 한국어 어절일 수 없음)에서
* 중복 타건·빠진 쌍자음·1타 오타(인접 키/누락/추가)를 복원한다.
*/
function findFuzzyEnglishForLooseJamo(latin: string): string | null {
if (latin.length < 3) return null
// 1) 3번 이상 반복된 글자를 2글자/1글자로 축약하거나, 연속 2글자 구간을 하나씩 줄여 본다
// 예: ㅊ무ㅜ'ㅅ(cann't) → can't, ㅊ무ㅜㅅ(cannt) → can't, ㅗ디ㅣㅐㅐ(helloo) → hello, ㅗ디ㅔㅔ(helpp) → help
const collapsedTriple = latin.replace(/([A-Za-z])\1{2,}/gu, '$1$1')
if (collapsedTriple !== latin) {
const resolved = resolveExactOrKnownEnglish(collapsedTriple)
if (resolved) return resolved
}
const collapsedAll = latin.replace(/([A-Za-z])\1+/gu, '$1')
if (collapsedAll !== latin && collapsedAll.length >= 3) {
const resolved = resolveExactOrKnownEnglish(collapsedAll)
if (resolved) return resolved
}
const doubleRunRegex = /([A-Za-z])\1+/gu
for (let match = doubleRunRegex.exec(latin); match !== null; match = doubleRunRegex.exec(latin)) {
const singleCollapsed =
latin.slice(0, match.index) + match[1] + latin.slice(match.index + match[0].length)
if (singleCollapsed.length >= 3) {
const resolved =
resolveExactOrKnownEnglish(singleCollapsed) ??
(/^[A-Za-z]+$/u.test(singleCollapsed) ? findAdjacentTransposedEnglishWord(singleCollapsed) : null)
if (resolved) return resolved
}
}
if (!/^[A-Za-z]+$/u.test(latin)) return null
const lower = latin.toLowerCase()
// 2) 영어에서 자주 겹쳐 쓰는 글자(l, s, r, t, n, m, p, c, f, g, d, b, o, e)가 1글자만 눌린 경우
// 예: ㅗ디ㅐ(helo) → hello, ㅔㅐ냐ㅠㅣㄷ(posible) → possible, ㄴㅐ교(sory) → sorry, 재교(wory) → worry
if (lower.length >= 4) {
for (let i = 1; i < lower.length; i += 1) {
const ch = lower[i]
if (!/[lsrtnmpcfgdboe]/u.test(ch)) continue
const doubled = `${lower.slice(0, i)}${ch}${lower.slice(i)}`
if (COMMON_ENGLISH_WORDS.has(doubled)) {
return matchCase(latin, doubled)
}
}
}
// 3) 끝에 글자가 빠졌거나 5글자 이상에서 1글자가 빠진 경우 (ㅔㅐㄴ냐ㅠㅣ[possibl] → possible, ㅡㅁ가애주[markdow] → markdown)
if (lower.length >= 5) {
for (const tail of ['e', 'n', 'd', 'r', 't', 'l', 'y']) {
const extended = `${lower}${tail}`
if (COMMON_ENGLISH_WORDS.has(extended)) {
return matchCase(latin, extended)
}
}
const insertionMatches: string[] = []
for (const candidate of COMMON_ENGLISH_WORDS) {
if (candidate.length !== lower.length + 1 || candidate[0] !== lower[0]) continue
if (editDistance(Array.from(lower), Array.from(candidate)) === 1) {
insertionMatches.push(candidate)
if (insertionMatches.length > 1) break
}
}
if (insertionMatches.length === 1) {
return matchCase(latin, insertionMatches[0])
}
}
// 4) 5글자 이상에서 이웃 키가 1글자 더 끼어든 경우 (재ㅜㅇㄷㄱㅅ[wondert] → wonder, ㅗ디ㅣㅐㅔ[hellop] → hello)
if (lower.length >= 5) {
for (let i = lower.length - 1; i >= 1; i -= 1) {
const removed = lower[i]
const prev = lower[i - 1]
const next = lower[i + 1] ?? ''
if (!isQwertyAdjacent(removed, prev) && (!next || !isQwertyAdjacent(removed, next))) continue
const shortened = `${lower.slice(0, i)}${lower.slice(i + 1)}`
if (COMMON_ENGLISH_WORDS.has(shortened)) {
return matchCase(latin, shortened)
}
}
}
// 5) 4글자 이상에서 1글자 치환 오타 (세갸ㅜㅎ[tpring] → spring, ㅗ디ㅣㅔ[hellp] → hello, 재기f[worlf] → world)
if (lower.length >= 4) {
const adjacentSubMatches: string[] = []
const anySubMatches: string[] = []
for (const candidate of COMMON_ENGLISH_WORDS) {
if (candidate.length !== lower.length) continue
let diffIndex = -1
let diffs = 0
for (let i = 0; i < lower.length; i += 1) {
if (lower[i] !== candidate[i]) {
diffs += 1
diffIndex = i
if (diffs > 1) break
}
}
if (diffs !== 1 || diffIndex < 0) continue
anySubMatches.push(candidate)
if (isQwertyAdjacent(lower[diffIndex], candidate[diffIndex])) {
adjacentSubMatches.push(candidate)
}
}
if (adjacentSubMatches.length === 1) {
return matchCase(latin, adjacentSubMatches[0])
}
if (lower.length >= 5 && anySubMatches.length === 1) {
return matchCase(latin, anySubMatches[0])
}
}
return null
}
/**
* 두벌식 자판에서 조합되지 않고 낱자가 그대로 남는 2글자 영단어 (한글 단어·초성 줄임말이 될 수 없음).
* 예: "ㅑㄹ ㅑ 쇼ㅔㄷ hello 소두 ㅑㅅ 초뭏ㄷㄴ ㅑㅜ 10 ㄴㄷ채ㅜㅇㄴ" → "if I type hello then it changes in 10 seconds"
@ -761,7 +989,8 @@ const LOOSE_JAMO_TWO_LETTER_ENGLISH: Readonly<Record<string, string>> = {
ㅔㅊ: 'PC',
ㅅㅍ: 'TV',
ㅑㅇ: 'ID',
ㅑㅔ: 'IP'
ㅑㅔ: 'IP',
ㅑㅡ: "I'm"
}
/**
@ -802,7 +1031,43 @@ const VIM_EX_COMMANDS: ReadonlySet<string> = new Set([
*/
const STANDALONE_SYLLABLE_ENGLISH: Readonly<Record<string, string>> = {
재깅: 'world',
쟈소: 'with'
쟈소: 'with',
소됴: 'they',
갸홋: 'right',
녀초: 'such',
생묘: 'today',
낵교: 'sorry',
잭교: 'worry',
쟈노: 'wish',
래쳔: 'focus',
랙댜후: 'foreign',
디드둣: 'element',
내챠미: 'social',
소대교: 'theory',
며쇄갸쇼: 'authority',
랴흠: 'figma',
님차: 'slack',
네둥: 'spend',
초먁: 'chair',
댜홋: 'eight',
랴딩: 'field',
랴그: 'firm',
랴노: 'fish',
래그: 'form',
햐기: 'girl',
해미: 'goal',
갸초: 'rich',
갸나: 'risk',
개차: 'rock',
노맏: 'shake',
냐후: 'sign',
샛미: 'total',
셔구: 'turn',
츠맏: 'cmake',
녀애: 'sudo',
먁: 'air',
앳: 'dot',
므: 'am'
}
/**
@ -817,7 +1082,28 @@ const CONTEXTUAL_SYLLABLE_ENGLISH: Readonly<Record<string, string>> = {
쟈소: 'with',
소드: 'them',
소무: 'than',
미내: 'also'
미내: 'also',
애주: 'down',
새주: 'town',
챠쇼: 'city',
챔초: 'coach',
쳐기: 'curl'
}
/**
* 영문 어절 바로 뒤(또는 영문 문맥 안)에서 한글 자판으로 찍힌 1음절 영문 기능어 (새 → to, 애 → do, 무 → an, 뭉 → and, 랙 → for 등).
* 예: "I want 새 애 this" → "I want to do this", "into english 새 애" → "into english to do"
*/
const ENGLISH_CLAUSE_SINGLE_SYLLABLE: Readonly<Record<string, string>> = {
새: 'to',
애: 'do',
무: 'an',
뭉: 'and',
랙: 'for',
좨: 'who',
양: 'did',
햇: 'got',
둥: 'end'
}
const SURROUNDED_SINGLE_SYLLABLE_ENGLISH: Readonly<Record<string, string>> = {
@ -925,9 +1211,41 @@ const COMMON_TECH_ACRONYMS: ReadonlySet<string> = new Set([
'eks',
'rds',
'pc',
'tv'
'tv',
'cms',
'crm',
'erp',
'sns',
'rls',
'vad',
'pwa',
'spa',
'msa',
'ssr',
'csr',
'eu',
'tm',
'rn',
'tl'
])
/**
* 두벌식 한글 상태에서 Shift를 눌러 영문 대문자 약어를 쳤을 때 완성형 음절로 조합되지만,
* 한국어에서는 단독 1음절 명사로 쓰이지 않는 어간 (뒤에 조사나 한국어 명사가 붙으면 즉시 약어로 복원).
* 예: "츤를" → "CMS를", "먀를" → "AI를", "틔을" → "XML을", "뗘를" → "EU를", "넴를" → "SPA를", "젳를" → "VPC를"
*/
const NON_KOREAN_NOUN_ACRONYM_STEMS: Readonly<Record<string, string>> = {
츤: 'CMS',
먀: 'AI',
틔: 'XML',
뗘: 'EU',
뎌: 'EU',
넴: 'SPA',
섐: 'SPA',
젳: 'VPC',
춗: 'CORS'
}
/**
* 한글 자판 상태로 친 영단어(또는 영단어+한국어 조사)인가 → 고칠 문자열을 돌려준다.
*
@ -942,14 +1260,16 @@ export function detectHangulTypedLatin(
context: { hangul: number; latin: number },
options: LayoutDetectOptions = {}
): string | null {
// 0. 앞부분이 이미 영문으로 변환된 뒤 한글 자판으로 남은 글자(낱자 포함)를 이어 친 경우 (hellㅐ → hello, githuㅠ → github, some샤ㅡㄷ → sometime)
const latinThenJamoMatch = word.match(/^([A-Za-z]+)([가-힣ㄱ-ㆎ]*[ㄱ-ㆎ][가-힣ㄱ-ㆎ]*)$/u)
// 0. 앞부분이 이미 영문으로 변환된 뒤 한글 자판으로 남은 글자(낱자 포함)를 이어 친 경우 (hellㅐ → hello, githuㅠ → github, some샤ㅡㄷ → sometime, can'ㅅ → can't)
const latinThenJamoMatch = word.match(/^([A-Za-z']+)([가-힣ㄱ-ㆎ]*[ㄱ-ㆎ][가-힣ㄱ-ㆎ]*)$/u)
if (latinThenJamoMatch) {
const [, engPrefix, jamoSuffix] = latinThenJamoMatch
const suffixLatin = hangulToLatin(jamoSuffix)
const combinedLatin = engPrefix + suffixLatin
if (/^[A-Za-z]+$/u.test(combinedLatin) && isCommonEnglishWord(combinedLatin)) {
return combinedLatin
const combinedLatin = (engPrefix + suffixLatin).replace(/’/gu, "'")
const resolvedCombined =
resolveExactOrKnownEnglish(combinedLatin) ?? findFuzzyEnglishForLooseJamo(combinedLatin)
if (resolvedCombined) {
return resolvedCombined
}
if (
/^[A-Za-z]+$/u.test(suffixLatin) &&
@ -974,9 +1294,9 @@ export function detectHangulTypedLatin(
return null
}
if (!HANGUL_ANY.test(word) || !/^[가-힣ㄱ-ㆎ]+$/u.test(word)) return null
if (!HANGUL_ANY.test(word) || !/^[가-힣ㄱ-ㆎ'’]+$/u.test(word)) return null
// 0b. 낱자로 풀린 2글자 영단어 (ㅑㄹ → if, ㅑㅅ → it, ㅑㅜ → in, ㅑㄴ → is, ㅐㄹ → of, ㅐㅜ → on 등)
// 0b. 낱자로 풀린 2글자 영단어 (ㅑㄹ → if, ㅑㅅ → it, ㅑㅜ → in, ㅑㄴ → is, ㅐㄹ → of, ㅐㅜ → on, ㅑㅡ → I'm 등)
const twoLetter = LOOSE_JAMO_TWO_LETTER_ENGLISH[word]
if (twoLetter) return twoLetter
@ -984,16 +1304,35 @@ export function detectHangulTypedLatin(
const standaloneSyllable = STANDALONE_SYLLABLE_ENGLISH[word]
if (standaloneSyllable) return standaloneSyllable
// 0c. 영문 문맥 안의 단독 모음 'ㅑ' → 'I' (예: "ㅑㄹ ㅑ 쇼ㅔㄷ" → "if I type")
if (word === 'ㅑ' && (options.afterEnglishWord || options.nextIsEnglish || context.latin >= 2)) {
// 0c. 단독 모음 'ㅑ' → 'I' (공백 등 단어 경계가 확정되었거나 영문 문맥일 때), 양쪽 영문 사이 단독 자음 'ㅁ' → 'a'
// 한국어 감탄사 '야'는 초성 'ㅇ'이 포함된 완성형 음절('야')이며, 홀로 떨어진 호환 모음 'ㅑ'(i 키 단독)는 한국어 단어가 될 수 없다.
// 아직 치는 중일 때(if=ㅑㄹ, in=ㅑㅜ, it=ㅑㅅ 등)만 기다리고, 뒤에 공백이 왔거나 영문 문맥이면 즉시 'I'로 복원한다.
if (
word === 'ㅑ' &&
(options.hasWordBoundaryAfter || options.afterEnglishWord || options.nextIsEnglish || context.latin >= 1)
) {
return 'I'
}
if (word === 'ㅁ' && options.afterEnglishWord && options.nextIsEnglish) {
return 'a'
}
if (word === '츤' && options.hasWordBoundaryAfter) {
return 'CMS'
}
// 0d. 영문 문맥 안의 기능어 음절 (소두 → then, 조두 → when, 양쪽이 영문일 때의 새 → to / 무 → an / 므 → am)
// 0d. 영문 문맥 안의 기능어 음절 (소두 → then, 조두 → when, 새 → to, 애 → do, 무 → an, 내 → so, 해 → go)
const contextualMulti = CONTEXTUAL_SYLLABLE_ENGLISH[word]
if (contextualMulti && (options.afterEnglishWord || options.nextIsEnglish || context.latin >= 3)) {
return contextualMulti
}
const clauseSingle = ENGLISH_CLAUSE_SINGLE_SYLLABLE[word]
if (
clauseSingle &&
((options.afterEnglishWord && (options.hasWordBoundaryAfter || options.nextIsEnglish || context.latin >= 3)) ||
(options.nextIsEnglish && context.latin >= 4 && context.latin > context.hangul * 2))
) {
return clauseSingle
}
const surroundedSingle = SURROUNDED_SINGLE_SYLLABLE_ENGLISH[word]
if (surroundedSingle && options.afterEnglishWord && options.nextIsEnglish) {
return surroundedSingle
@ -1017,20 +1356,39 @@ export function detectHangulTypedLatin(
// 핵심 한국어 어휘는 절대 영어로 바꾸지 않는다.
if (CORE_KOREAN_WORDS.has(word)) return null
const latin = hangulToLatin(word)
if (!/^[A-Za-z]+$/u.test(latin) || latin.length < 3) return null
const latin = hangulToLatin(word).replace(/’/gu, "'")
if (!/^[A-Za-z']+$/u.test(latin) || latin.length < 3) return null
// 아포스트로피가 들어간 두벌식 영문 축약형 (ㅊ무'ㅅ → can't, ㅊ무ㅜ'ㅅ → can't, 애ㅜ'ㅅ → don't, ㅑ'ㅡ → I'm, ㅑㅅ'ㄴ → it's, ㅊ무'ㅅ는 → can't는)
if (latin.includes("'")) {
const directContraction = resolveContraction(latin) ?? findFuzzyEnglishForLooseJamo(latin)
if (directContraction) return directContraction
const contractionWithTail = word.match(/^([가-힣ㄱ-ㆎ]+'’?[가-힣ㄱ-ㆎ]+?)([가-힣]+)$/u)
if (contractionWithTail) {
const [, cStem, korSuffix] = contractionWithTail
const suffixKeys = hangulToLatin(korSuffix)
if (PARTICLE_KEYS.has(suffixKeys)) {
const stemLatin = hangulToLatin(cStem).replace(/’/gu, "'")
const resolvedStem = resolveContraction(stemLatin) ?? findFuzzyEnglishForLooseJamo(stemLatin)
if (resolvedStem) return `${resolvedStem}${korSuffix}`
}
}
return null
}
const hasLooseJamo = /[ㄱ-ㆎ]/u.test(word)
const chars = Array.from(word)
const hasRareSyllable = chars.some((char) => HANGUL_SYLLABLE.test(char) && !isCommonHangulSyllable(char))
const allCommonSyllables = !hasLooseJamo && chars.every((char) => isCommonHangulSyllable(char))
// 1. 낱자가 섞여 있고(정상 한국어 어절일 수 없음) 되돌린 결과가 흔한 영단어 또는 기술 약어면 문맥 무관 즉시 복원 (ㅗ디ㅣㅐ → hello, 쇼ㅔㄷ → type, 초뭏ㄷㄴ → changes, ㄴㄷ채ㅜㅇㄴ → seconds, ㅖㅇㄹ → PDF)
// 1. 낱자가 섞여 있고(정상 한국어 어절일 수 없음) 되돌린 결과가 흔한 영단어·오타 사전 영단어 또는 기술 약어면 문맥 무관 즉시 복원 (ㅗ디ㅣㅐ → hello, 쇼ㅔㄷ → type, 초뭏ㄷㄴ → changes, ㄴㄷ채ㅜㅇㄴ → seconds, ㅖㅇㄹ → PDF, ㅊ무ㅅ → can't)
if (hasLooseJamo) {
if (COMMON_TECH_ACRONYMS.has(latin.toLowerCase()) && /[A-Z]/u.test(latin)) {
return latin.toUpperCase()
}
if (isCommonEnglishWord(latin)) return latin
const knownEnglishFix = fixKnownMisspelling(latin)
if (knownEnglishFix) return knownEnglishFix
if (COMMON_TECH_ACRONYMS.has(latin.toLowerCase()) && latin.length >= 3) {
return latin.toLowerCase()
}
@ -1075,10 +1433,23 @@ export function detectHangulTypedLatin(
if (stemLatin.length >= 3 && isCommonEnglishWord(stemLatin)) {
return `${stemLatin}${korSuffix}`
}
const transposedStem = findAdjacentTransposedEnglishWord(stemLatin)
const transposedStem =
findAdjacentTransposedEnglishWord(stemLatin) ?? findFuzzyEnglishForLooseJamo(stemLatin)
if (transposedStem) {
return `${transposedStem}${korSuffix}`
}
// Araso 일반 규칙: 2~4자 미조합 호환 자모(ㅏㅅㅌ, ㅎㅅㅌ, ㅠㅅㄴ, ㅐㅅㅅ, ㄷㅅㄹ, ㅜㄹㅅ, ㅊㄷㅐ, ㅔㅡ 등) 뒤에
// 바로 한국어 조사가 오고 약어 끝소리 받침 호응이 맞으면 사전 등록 여부와 무관하게 대문자 약어+조사로 복원한다.
if (
isParticleSuffix &&
/^[ㄱ-ㆎ]{2,4}$/u.test(jamoPrefix) &&
!/^[ㅋㅎㅠㅜㅇ]+$/u.test(jamoPrefix) &&
stemLatin.length >= 2 &&
stemLatin.length <= 4 &&
particleAgrees(korSuffix, finalSoundOfAcronym(stemLatin)) !== false
) {
return `${stemLatin.toUpperCase()}${korSuffix}`
}
}
}
@ -1097,6 +1468,68 @@ export function detectHangulTypedLatin(
const tailConv = latinToHangul(tail)
if (tailConv.complete) return `${transposedStem}${tailConv.text}`
}
// 2.5. 낱자가 섞여 있어 한국어 단어일 수 없는 토큰의 영문 1타 오타 복원 (ㅗ디ㅐ → hello, ㅔㅐㄴ냐ㅠㅣ → possible, 세갸ㅜㅎ → spring, ㅊ무ㅜㅅ → can't)
const fuzzyEnglish = findFuzzyEnglishForLooseJamo(latin)
if (fuzzyEnglish) return fuzzyEnglish
}
// 2b. 낱자 없이 완성형 음절로 조합된 영문 약어/단어 + 한국어 조사 (Araso 받침 호응 및 비상용 명사 어간 판별)
// 예: "츤를" → "CMS를", "먀를" → "AI를", "틔을" → "XML을", "뗘를" → "EU를", "눈를" → "SNS를", "운를" → "DNS를", "긴를" → "RLS를", "쓰은" → "TM은", "꾸은" → "RN은"
if (!hasLooseJamo && chars.length >= 2) {
for (let splitIdx = 1; splitIdx < chars.length; splitIdx += 1) {
const stem = chars.slice(0, splitIdx).join('')
const korSuffix = chars.slice(splitIdx).join('')
const suffixKeys = hangulToLatin(korSuffix)
if (!PARTICLE_KEYS.has(suffixKeys)) continue
if (CORE_KOREAN_WORDS.has(word)) continue
const directAcronym = NON_KOREAN_NOUN_ACRONYM_STEMS[stem]
if (directAcronym) {
return `${directAcronym}${korSuffix}`
}
const standaloneStem = STANDALONE_SYLLABLE_ENGLISH[stem]
if (standaloneStem) {
return `${standaloneStem}${korSuffix}`
}
const stemLatin = hangulToLatin(stem)
const lowerStemLatin = stemLatin.toLowerCase()
const stemHasRareSyllable = Array.from(stem).some((ch) => !isCommonHangulSyllable(ch))
const korFinal = finalSoundOfHangul(stem)
const korAgrees = korFinal !== null ? particleAgrees(korSuffix, korFinal) : null
const acronymAgrees = particleAgrees(korSuffix, finalSoundOfAcronym(stemLatin))
// Araso 일반 받침 호응 판별:
// 한글 어간의 받침과 조사가 문법적으로 충돌하는데(korAgrees === false: 예 '츤'+'를', '눈'+'를', '운'+'를', '긴'+'를',
// '쓰'+'은', '꾸'+'은', '띠'+'이', '꺼'+'을', '씨'+'은'), 영문 약어 알파벳 끝소리 발음과는 호응하면(acronymAgrees === true)
// 사전 등록 여부와 무관하게 대문자 약어+조사로 복원한다.
if (
korAgrees === false &&
stemLatin.length >= 2 &&
stemLatin.length <= 4 &&
((/[A-Z]/u.test(stemLatin) && stemLatin.length === 2 && korFinal === 'vowel') ||
(acronymAgrees === true &&
(COMMON_TECH_ACRONYMS.has(lowerStemLatin) ||
/[A-Z]/u.test(stemLatin) ||
stemHasRareSyllable ||
(stem.length === 1 &&
stemLatin.length === 3 &&
(korSuffix === '를' || korSuffix === '가' || korSuffix === '와')))))
) {
return `${stemLatin.toUpperCase()}${korSuffix}`
}
if (COMMON_TECH_ACRONYMS.has(lowerStemLatin) && stemHasRareSyllable) {
return `${stemLatin.toUpperCase()}${korSuffix}`
}
if (stemHasRareSyllable && stemLatin.length >= 3 && isCommonEnglishWord(stemLatin)) {
return `${stemLatin}${korSuffix}`
}
}
}
// 3. 비상용 음절(솓 → the 등)이면서 흔한 영단어면 복원
@ -1165,9 +1598,11 @@ const ENGLISH_MISSPELLINGS: Readonly<Record<string, string>> = {
neccessary: 'necessary', necesary: 'necessary', noticable: 'noticeable', occassion: 'occasion',
persue: 'pursue', posession: 'possession', publically: 'publicly', realy: 'really', recomend: 'recommend',
refered: 'referred', relevent: 'relevant', succesful: 'successful', successfull: 'successful',
suprise: 'surprise', truely: 'truly', withold: 'withhold', dont: "don't", doesnt: "doesn't", didnt: "didn't",
isnt: "isn't", wasnt: "wasn't", werent: "weren't", havent: "haven't", hasnt: "hasn't", couldnt: "couldn't",
wouldnt: "wouldn't", shouldnt: "shouldn't", arent: "aren't", thats: "that's", whats: "what's",
suprise: 'surprise', truely: 'truly', withold: 'withhold', cant: "can't", cannt: "can't", "cann't": "can't",
dont: "don't", donnt: "don't", "donn't": "don't", doesnt: "doesn't", didnt: "didn't", wont: "won't",
isnt: "isn't", wasnt: "wasn't", werent: "weren't", havent: "haven't", hasnt: "hasn't", hadnt: "hadn't",
couldnt: "couldn't", wouldnt: "wouldn't", shouldnt: "shouldn't", arent: "aren't", thats: "that's", whats: "what's",
hes: "he's", shes: "she's", lets: "let's",
im: "I'm", ive: "I've", youre: "you're", theyre: "they're", thanx: 'thanks', pls: 'please', plz: 'please',
wiht: 'with', woudl: 'would', coudl: 'could', shoudl: 'should', jsut: 'just', konw: 'know', nwo: 'now',
waht: 'what', whcih: 'which', thsi: 'this', tihs: 'this', alos: 'also', aslo: 'also', abotu: 'about',
@ -1268,12 +1703,30 @@ function isIgnored(word: string, ignored: readonly string[] | undefined): boolea
}
function looksLikeEnglishOrHangulTypedEnglish(tokenText: string): boolean {
if (/^[A-Za-z]{2,}$/u.test(tokenText) && isCommonEnglishWord(tokenText)) return true
if (/^[A-Za-z']{2,}$/u.test(tokenText) && (isCommonEnglishWord(tokenText) || resolveContraction(tokenText) !== null)) {
return true
}
if (LOOSE_JAMO_TWO_LETTER_ENGLISH[tokenText]) return true
if (STANDALONE_SYLLABLE_ENGLISH[tokenText] || CONTEXTUAL_SYLLABLE_ENGLISH[tokenText]) return true
if (
STANDALONE_SYLLABLE_ENGLISH[tokenText] ||
CONTEXTUAL_SYLLABLE_ENGLISH[tokenText] ||
ENGLISH_CLAUSE_SINGLE_SYLLABLE[tokenText]
) {
return true
}
if (/[ㄱ-ㆎ]/u.test(tokenText)) {
const latin = hangulToLatin(tokenText)
if (/^[A-Za-z]{3,}$/u.test(latin) && isCommonEnglishWord(latin)) return true
const latin = hangulToLatin(tokenText).replace(/’/gu, "'")
if (latin.includes("'") && (resolveContraction(latin) !== null || findFuzzyEnglishForLooseJamo(latin) !== null)) {
return true
}
if (
/^[A-Za-z]{3,}$/u.test(latin) &&
(isCommonEnglishWord(latin) ||
fixKnownMisspelling(latin) !== null ||
findFuzzyEnglishForLooseJamo(latin) !== null)
) {
return true
}
}
return false
}
@ -1372,6 +1825,7 @@ export function detectTypos(prefix: string, options: TypoDetectOptions = {}): Ty
afterKoreanWord,
afterEnglishWord,
nextIsEnglish,
hasWordBoundaryAfter: /[ \t.,!?;:]/u.test(after),
vocabulary: options.vocabulary
})
@ -1423,7 +1877,56 @@ export function detectTypos(prefix: string, options: TypoDetectOptions = {}): Ty
}
afterKoreanWord = HANGUL_SYLLABLE.test(token.text)
afterEnglishWord = /^[A-Za-z]+$/u.test(token.text)
afterEnglishWord = /^[A-Za-z']+$/u.test(token.text)
// 영단어 바로 뒤에 실수로 눌린 짝 없는 여는 대괄호 제거 (예: p 옆 키 오타인 "help[ " → "help ")
if (
!options.terminalMode &&
after === '[' &&
(token.start === 0 || /\s/u.test(before)) &&
/\s/u.test(prefix[token.end + 1] ?? '') &&
/^[A-Za-z]{3,}$/u.test(token.text) &&
isCommonEnglishWord(token.text) &&
!prefix.slice(token.end + 1).includes(']')
) {
out.push({
start: token.start,
end: token.end + 1,
from: `${token.text}[`,
to: token.text,
source: 'layout'
})
continue
}
// 공백으로 잘못 띄어 쓴 영어 재귀대명사 결합 (예: "my self " → "myself ")
if (
!options.terminalMode &&
/^(?:self|selves)$/iu.test(token.text) &&
index > 0 &&
(/[ \t.,!?;:]/u.test(after) || !options.layoutOnly)
) {
const prevToken = tokens[index - 1]
if (
prevToken &&
prevToken.end + 1 === token.start &&
prefix[prevToken.end] === ' ' &&
!out.some((existing) => existing.end > prevToken.start)
) {
const mergedReflexive = `${prevToken.text}${token.text}`
if (/^(?:myself|yourself|himself|herself|ourselves|themselves|yourselves)$/iu.test(mergedReflexive)) {
out.push({
start: prevToken.start,
end: token.end,
from: `${prevToken.text} ${token.text}`,
to: mergedReflexive,
source: 'layout'
})
continue
}
}
}
if (options.layoutOnly) continue
if (looksTechnical(prefix, token)) continue
@ -1468,9 +1971,14 @@ export function detectJamoNoise(prefix: string, options: { ignoredWords?: readon
if (isIgnored(token.text, options.ignoredWords)) return
const chars = Array.from(token.text)
if (chars.length === 1 && COMPAT_JAMO.test(chars[0])) {
// 글 첫 단어인 "ㅇ"(응)·"ㄱ"(고) 는 대답이다 — 앞에 한글 단어가 있을 때만 잡음으로 본다.
// 글 첫 단어인 "ㅇ"(응)·"ㄱ"(고) 는 대답이다 — 앞에 온전한 단어가 있을 때만 잡음으로 본다.
const previous = tokens[index - 1]
if (!previous || !HANGUL_SYLLABLE.test(previous.text) || EMOTIVE_JAMO.has(chars[0])) return
if (!previous || EMOTIVE_JAMO.has(chars[0])) return
const prevIsKorean = HANGUL_SYLLABLE.test(previous.text)
const prevIsEnglish = /^[A-Za-z']/u.test(previous.text) || /[ㄱ-ㆎ]/u.test(previous.text)
if (!prevIsKorean && !prevIsEnglish) return
// 영문 뒤의 'ㅑ'(I), 'ㅁ'(a), 'ㅇ' 은 잡음 삭제 대상에서 제외한다.
if (!prevIsKorean && (chars[0] === 'ㅑ' || chars[0] === 'ㅁ' || chars[0] === 'ㅇ')) return
// 뒤 공백과 함께 지운다 — 앞 공백을 지우면 끝에 남은 낱자("있고 ㅇ")가 "있고" 가 되어, 모델이 끝난
// 단어에 글자를 붙이려 하거나 곧바로 턴을 닫았다(실측 2026-10-17: 교정이 붙은 첫 후보 4번 모두 빈 출력).
const end = /[ \t]/u.test(prefix[token.end] ?? '') ? token.end + 1 : token.end
@ -1495,17 +2003,101 @@ export function detectJamoNoise(prefix: string, options: { ignoredWords?: readon
return out
}
function isIntentionalJamoToken(word: string): boolean {
if (/^[ㅋㅎㅠㅜㅇ]+$/u.test(word)) return true
if (word === 'ㅇㅋ' || word === 'ㄱㅅ' || word === 'ㅊㅋ' || word === 'ㅅㄱ') return true
if (/^[가-힣]+[ㅋㅎㅠㅜ]+$/u.test(word)) return true
return false
}
/**
* 모델에 오타 검사를 맡길 만큼 수상한 구간인가 — 낱자가 섞인 한글 단어, 드문 음절, 결정적 탐지 결과.
* 모델에 오타 검사를 맡길 만큼 수상한 구간인가 — 낱자가 섞인 한글/한영 오타 단어, 드문 음절, 미등록 소문자 영단어.
*
* 제안 창에 교정을 함께 내놓을 때 멈출 때마다 모델 검사(0.5초)를 하면 제안이 그만큼 늦는다.
* 수상한 흔적이 있을 때만 묻는다.
* 수상한 흔적이 있을 때만 즉시 묻는다.
*/
export function hasSuspiciousTypo(region: string): boolean {
if (detectJamoNoise(region).length > 0) return true
return tokenizeWords(region).some((token) =>
Array.from(token.text).some((char) => HANGUL_SYLLABLE.test(char) && !isCommonHangulSyllable(char))
)
return tokenizeWords(region).some((token) => {
const word = token.text
if (/[ㄱ-ㆎ]/u.test(word) && !isIntentionalJamoToken(word)) return true
if (Array.from(word).some((char) => HANGUL_SYLLABLE.test(char) && !isCommonHangulSyllable(char))) {
return true
}
if (
/^[a-z]{4,}$/u.test(word) &&
!isCommonEnglishWord(word) &&
!COMMON_TECH_ACRONYMS.has(word)
) {
return true
}
return false
})
}
/**
* 로컬 LLM(Gemma)이 두벌식 한/영 자판 오타와 철자 오타가 결합된 어절을 정확히 알아보도록
* 수상한 어절의 두벌식 영문/한글 변환 힌트 줄을 만든다.
*/
export function buildModelTypoHints(sentence: string): string[] {
const hints: string[] = []
const seen = new Set<string>()
for (const token of tokenizeWords(sentence)) {
const word = token.text
if (seen.has(word) || isIntentionalJamoToken(word)) continue
if (HANGUL_ANY.test(word) && /^[가-힣ㄱ-ㆎ]+$/u.test(word) && !CORE_KOREAN_WORDS.has(word)) {
const hasLooseJamo = /[ㄱ-ㆎ]/u.test(word)
const hasRareSyllable = Array.from(word).some(
(ch) => HANGUL_SYLLABLE.test(ch) && !isCommonHangulSyllable(ch)
)
const jamoPrefixAndHangulTail = word.match(/^([가-힣ㄱ-ㆎ]*[ㄱ-ㆎ][가-힣ㄱ-ㆎ]*?)([가-힣]+)$/u)
if (jamoPrefixAndHangulTail) {
const [, jamoPrefix, korSuffix] = jamoPrefixAndHangulTail
const stemLatin = hangulToLatin(jamoPrefix)
const suffixKeys = hangulToLatin(korSuffix)
if (/^[A-Za-z]{2,}$/u.test(stemLatin) && PARTICLE_KEYS.has(suffixKeys)) {
seen.add(word)
hints.push(`- "${word}" (영문 자판 키 입력값: "${stemLatin}${korSuffix}")`)
if (hints.length >= 6) break
continue
}
}
const fullLatin = hangulToLatin(word)
if (
/^[A-Za-z]{3,}$/u.test(fullLatin) &&
(hasLooseJamo || hasRareSyllable || isCommonEnglishWord(fullLatin))
) {
let particleHint = ''
for (let i = fullLatin.length - 2; i >= 3; i -= 1) {
const stem = fullLatin.slice(0, i)
const tail = fullLatin.slice(i)
if (PARTICLE_KEYS.has(tail)) {
const tailKor = latinToHangul(tail)
if (tailKor.complete) {
particleHint = ` 또는 "${stem}${tailKor.text}"`
break
}
}
}
seen.add(word)
hints.push(`- "${word}" (영문 자판 키 입력값: "${fullLatin}"${particleHint})`)
if (hints.length >= 6) break
}
continue
}
if (/^[A-Za-z]{4,}$/u.test(word) && !isCommonEnglishWord(word) && !COMMON_TECH_ACRONYMS.has(word.toLowerCase())) {
const conv = latinToHangul(word)
const hangulCount = Array.from(conv.text).filter((ch) => HANGUL_SYLLABLE.test(ch)).length
if (hangulCount >= 2) {
seen.add(word)
hints.push(`- "${word}" (한글 자판 조합값: "${conv.text}")`)
if (hints.length >= 6) break
}
}
}
return hints
}
/**
@ -1557,23 +2149,86 @@ export function isPlausibleTypoFix(from: string, to: string): boolean {
if (/\s/u.test(from) || /\s/u.test(to)) return false
if (/\d/u.test(from) || /\d/u.test(to)) return false
if (from.toLowerCase() === to.toLowerCase()) return false
const fromHasHangulOrJamo = HANGUL_ANY.test(from)
const fromPureLatin = /^[A-Za-z']+$/u.test(from)
const toPureLatin = /^[A-Za-z']+$/u.test(to)
// 1) 한→영 (또는 한+조사 → 영+조사) 자판 오타 + 철자 오타 복합 교정
// 예: ㅗ디ㅐ(helo) → hello, ㅡㅁ가둥(markend) → markdown, 네갸ㅜㅎ에서 → spring에서, ㅊ무ㅜ'ㅅ → can't
const toEngKorMatch = /^([A-Za-z']{2,})([가-힣]*)$/u.exec(to)
if (fromHasHangulOrJamo && toEngKorMatch) {
const [, toEng, toKorSuffix] = toEngKorMatch
if (toEng.length < 3) return false
const fromStem =
toKorSuffix && from.endsWith(toKorSuffix) ? from.slice(0, from.length - toKorSuffix.length) : from
if (!fromStem || CORE_KOREAN_WORDS.has(fromStem)) return false
const fromLatin = hangulToLatin(fromStem).replace(/’/gu, "'").toLowerCase()
const targetLatin = (
toKorSuffix && !from.endsWith(toKorSuffix) ? `${toEng}${hangulToLatin(toKorSuffix)}` : toEng
).toLowerCase()
if (!/^[a-z']+$/u.test(fromLatin)) return false
const keyDist = editDistance(Array.from(fromLatin), Array.from(targetLatin))
const hasLooseJamo = /[ㄱ-ㆎ]/u.test(fromStem)
const hasRareSyllable = Array.from(fromStem).some(
(ch) => HANGUL_SYLLABLE.test(ch) && !isCommonHangulSyllable(ch)
)
if (hasLooseJamo || hasRareSyllable) {
if (Math.abs(fromLatin.length - targetLatin.length) > 2) return false
const sharesPrefix3 = fromLatin.length >= 4 && fromLatin.slice(0, 3) === targetLatin.slice(0, 3)
const maxDist = sharesPrefix3
? Math.max(2, Math.ceil(targetLatin.length * 0.5))
: targetLatin.length >= 7 && fromLatin.slice(0, 2) === targetLatin.slice(0, 2)
? 3
: 2
return keyDist <= maxDist
}
return toEng.length >= 4 && keyDist === 0
}
// 2) 영→한 자판 오타 + 철자 오타 복합 교정 (예: dkssudgktpd → 안녕하세요)
if (fromPureLatin && /^[가-힣]{2,}$/u.test(to)) {
const toLatin = hangulToLatin(to).toLowerCase()
const fromLower = from.toLowerCase()
if (Math.abs(fromLower.length - toLatin.length) > 2) return false
const keyDist = editDistance(Array.from(fromLower), Array.from(toLatin))
return keyDist <= 2
}
const fromHangul = HANGUL_SYLLABLE.test(from)
const toHangul = HANGUL_SYLLABLE.test(to)
if (fromHangul !== toHangul) return false
// 낱자 수가 크게 달라지면 오타 수정이 아니라 단어 교체다.
if (Math.abs(Array.from(from).length - Array.from(to).length) > 1) return false
// 3) 한글 → 한글 철자·자모 오타 교정
const distance = spellingDistance(from, to)
if (fromHangul) {
if (/[ㄱ-ㆎ]/u.test(to)) return false
const fromChars = Array.from(from)
const toChars = Array.from(to)
const fromHasLooseJamo = /[ㄱ-ㆎ]/u.test(from)
if (fromHasLooseJamo) {
if (toChars.length < 2) return false
const fromJamo = decomposeHangul(from)
const toJamo = decomposeHangul(to)
if (Math.abs(fromJamo.length - toJamo.length) > 2) return false
return distance <= Math.min(3, Math.max(1, Math.ceil(fromJamo.length * 0.25)))
}
// 낱자 수가 크게 달라지면 오타 수정이 아니라 단어 교체다.
if (Math.abs(fromChars.length - toChars.length) > 1) return false
// 1음절 어절(넘·젤·걍)과 짧은 어절이 길어지는 것은 오타가 아니라 줄임말 풀기다 (실측: gemma 가
// "넘 => 너무" 를 오타로 냈다). 긴 어절에서 빠진 음절을 채우는 것만 허용한다.
const fromSyllables = Array.from(from).length
const fromSyllables = fromChars.length
if (fromSyllables < 2) return false
if (Array.from(to).length > fromSyllables && fromSyllables <= 3) return false
if (toChars.length > fromSyllables && fromSyllables <= 3) return false
const jamoLength = decomposeHangul(from).length
return distance <= Math.min(3, Math.max(1, Math.ceil(jamoLength * 0.25)))
}
// 4) 영문 → 영문 철자 오타 교정
if (!fromPureLatin || !toPureLatin) return false
if (Math.abs(Array.from(from).length - Array.from(to).length) > 1) return false
if (from.length < 3) return false
return distance <= (from.length >= 7 ? 2 : 1)
return distance <= (from.length >= 6 ? 2 : 1)
}
/**
@ -1593,9 +2248,17 @@ export function validateModelCorrections(
const out: TypoCorrection[] = []
const reversed = [...tokens].reverse()
for (const pair of pairs) {
// 모델은 어절 대신 어간만 돌려주기도 한다("회으에서" 를 "회으 => 회의" 로) — 그때는 어절 안의
// 그 부분만 바꾼 어절 전체로 다시 판단한다. 어절 앞부분이 맞는 것을 먼저 고른다.
const whole = reversed.find((candidate) => candidate.text === pair.from)
// 모델은 어절 대신 어간만 돌려주거나("회으에서" 를 "회으 => 회의" 로),
// [한영 자판 변환 참고] 에 적힌 자판 키값("ㅗ디ㅐ" 의 "helo => hello")을 from 으로 돌려주기도 한다.
const whole =
reversed.find((candidate) => candidate.text === pair.from) ??
reversed.find(
(candidate) =>
HANGUL_ANY.test(candidate.text) && hangulToLatin(candidate.text).toLowerCase() === pair.from.toLowerCase()
) ??
reversed.find(
(candidate) => /^[A-Za-z]+$/u.test(candidate.text) && latinToHangul(candidate.text).text === pair.from
)
const partial =
whole || Array.from(pair.from).length < 2
? undefined