feat(desktop): built-in Han/Eng layout auto-switching, terminal/Vim support, and Unicode input

This commit is contained in:
Yun Chan 2026-10-27 10:48:07 +09:00
parent 1da04b9e46
commit a3ac44da2b
109 changed files with 8234 additions and 242 deletions

View file

@ -1,8 +1,11 @@
// packages/core — 터미널 화면에서 "지금 치고 있는 입력 줄" 을 뽑는다.
// packages/core — 터미널 화면 및 키스트로크 스트림에서 "지금 치고 있는 입력 줄" 과 Vim 모드를 뽑는다.
//
// 터미널은 화면 버퍼 전체가 입력창으로 읽힌다(상태줄·명령·출력 포함). 제안은 입력 줄만
// 접두로 써야 하므로 그 파싱을 한곳에 둔다. 순수 함수만 둔다 — 다른 core 모듈을
// import 하지 않는다 (input-intelligence 가 이 모듈을 다시 export 한다).
// 터미널은 화면 버퍼 전체가 입력창으로 읽히거나(Windows Terminal 등: 상태줄·명령·출력 포함),
// 캔버스/레거시 표면(Kitedesk, WezTerm, Alacritty, xterm.js 등: UIA 텍스트 길이 0)으로 노출된다.
// 또한 터미널 내부에서 Vim/Neovim 을 쓸 때는 화면 중간 줄을 편집하면서 하단 상태줄(-- INSERT --,
// -- NORMAL --, :wq 등)이 함께 바뀐다.
// 순수 함수와 순수 상태 머신만 둔다 — 다른 core 모듈을 import 하지 않는다
// (input-intelligence 가 이 모듈을 다시 export 한다).
/** 상자·블록·도형·기타 기호·딩뱃 — 터미널 UI/상태줄의 지문이다. */
export const NON_PROSE_GLYPH_PATTERN = /[←-⇿─-➿⬀-⯿]/u
@ -18,6 +21,25 @@ const TERMINAL_BORDER_PATTERN = /^[\s─━═┄┈╌╍╭╮╰╯┌┐└
const TERMINAL_EDGE_PATTERN = /^[\s│┃║]+|[\s│┃║]+$/gu
const TERMINAL_SCAN_LINES = 40
export type TerminalVimMode = 'insert' | 'normal' | 'command' | null
export interface TerminalActiveContext {
prefix: string
caretReliable: boolean
vimMode: TerminalVimMode
isVimScreen: boolean
}
const VIM_INSERT_LINE_PATTERN =
/(?:--\s*(?:INSERT|REPLACE|끼워넣기|바꾸기|\(insert\))\s*--|\b(?:INSERT|REPLACE)\b.*(?:\d+,\d+|\d+%|Top|Bot|All))/iu
const VIM_NORMAL_LINE_PATTERN =
/(?:--\s*(?:NORMAL|VISUAL|SELECT|비주얼|선택)(?:\s+LINE|\s+BLOCK)?\s*--|\b(?:NORMAL|VISUAL)\b.*(?:\d+,\d+|\d+%|Top|Bot|All))/iu
const VIM_RULER_LINE_PATTERN = /\s{2,}\d+,\d+(?:-\d+)?\s+(?:All|Top|Bot|\d+%)\s*$/u
const VIM_TILDE_LINE_PATTERN = /^\s*~\s*$/u
const VIM_COMMAND_LINE_PATTERN = /^:([ㄱ-ㅎㅏ-ㅣ가-힣A-Za-z0-9!%\s_.-]{1,60})$/u
const VIM_SHELL_LAUNCH_PATTERN = /^(?:sudo\s+)?(?:vim|nvim|vi|vimdiff|view|gvim|neovide)(?:\s|$)/u
const VIM_WINDOW_TITLE_PATTERN = /(?:^|[\s\-—–\\/])(?:n?vim|vi|gvim|neovide)(?:$|[\s\-—–.])/iu
/**
* 터미널 화면 텍스트에서 "지금 치고 있는 입력" 을 뽑는다.
*
@ -31,10 +53,13 @@ export function extractTerminalPromptPrefix(screen: string | null | undefined):
const lines = screen.replace(/\r/g, '').split('\n')
const start = Math.max(0, lines.length - TERMINAL_SCAN_LINES)
for (let i = lines.length - 1; i >= start; i--) {
const line = lines[i].replace(TERMINAL_EDGE_PATTERN, '')
const rawLine = lines[i]
const hasSingleTrailingSpace = !/[│┃║]\s*$/u.test(rawLine) && /\S $/u.test(rawLine)
const line = rawLine.replace(TERMINAL_EDGE_PATTERN, '')
const match = TERMINAL_PROMPT_PATTERN.exec(line)
if (!match) continue
const parts = [match[1].trimEnd()]
let lastIdx = i
for (let j = i + 1; j < lines.length; j++) {
const raw = lines[j]
if (TERMINAL_BORDER_PATTERN.test(raw)) break
@ -42,8 +67,856 @@ export function extractTerminalPromptPrefix(screen: string | null | undefined):
// 상태줄 기호(◑ ▕░ 등)가 섞인 줄은 입력이 아니다.
if (!continuation || NON_PROSE_GLYPH_PATTERN.test(continuation)) break
parts.push(continuation)
lastIdx = j
}
return parts.join(' ').replace(/\s+/gu, ' ').trimStart()
const joined = parts.join(' ').replace(/\s+/gu, ' ').trimStart()
const tailHasSpace =
lastIdx === i
? hasSingleTrailingSpace
: !/[│┃║]\s*$/u.test(lines[lastIdx]) && /\S $/u.test(lines[lastIdx])
return joined && tailHasSpace ? `${joined} ` : joined
}
return null
}
function isTerminalStatusOrNoiseLine(rawLine: string): boolean {
const line = rawLine.replace(TERMINAL_EDGE_PATTERN, '')
if (!line.trim()) return true
if (TERMINAL_BORDER_PATTERN.test(rawLine)) return true
if (NON_PROSE_GLYPH_PATTERN.test(line)) return true
if (VIM_TILDE_LINE_PATTERN.test(line)) return true
if (VIM_INSERT_LINE_PATTERN.test(line) || VIM_NORMAL_LINE_PATTERN.test(line)) return true
if (VIM_RULER_LINE_PATTERN.test(line)) return true
return false
}
function trimGridPadding(rawLine: string): string {
if (!/[│┃║]\s*$/u.test(rawLine) && /\S $/u.test(rawLine)) {
return `${rawLine.trimEnd()} `
}
return rawLine.trimEnd()
}
function stripPromptFromLine(line: string): string {
const hasSingleSpace = !/[│┃║]\s*$/u.test(line) && /\S $/u.test(line)
const cleaned = line.replace(TERMINAL_EDGE_PATTERN, '')
const match = TERMINAL_PROMPT_PATTERN.exec(cleaned)
if (match) {
const body = match[1].trimEnd()
return body && hasSingleSpace ? `${body} ` : body
}
// Vim 줄 번호 표시(" 12 dkssudgktpdy")가 앞에 있으면 걷어낸다.
const lineNumMatch = /^\s*\d+\s+(.*)$/u.exec(cleaned)
if (lineNumMatch) {
const body = lineNumMatch[1].trimEnd()
return body && hasSingleSpace ? `${body} ` : body
}
return cleaned && hasSingleSpace ? `${cleaned} ` : cleaned
}
function commonSuffixLength(a: string, b: string): number {
const max = Math.min(a.length, b.length)
let count = 0
while (count < max && a[a.length - 1 - count] === b[b.length - 1 - count]) {
count += 1
}
return count
}
/**
* 터미널 화면 스냅샷(직전/현재)에서 Vim 모드와 현재 편집 중인 활성 줄 접두를 추출한다.
*/
export function extractTerminalActiveContext(
prevScreen: string | null | undefined,
currScreen: string | null | undefined,
lastActivePrefix?: string | null,
windowTitle?: string | null,
trackerVimMode?: TerminalVimMode
): TerminalActiveContext {
if (!currScreen) {
return { prefix: '', caretReliable: false, vimMode: null, isVimScreen: false }
}
const currLines = currScreen.replace(/\r/g, '').split('\n')
const nonEmptyBottom: string[] = []
for (let i = currLines.length - 1; i >= 0 && nonEmptyBottom.length < 5; i -= 1) {
const cleaned = currLines[i].replace(TERMINAL_EDGE_PATTERN, '').trimEnd()
if (cleaned.trim().length > 0) {
nonEmptyBottom.push(cleaned)
}
}
const tildeCount = currLines.filter((line) => VIM_TILDE_LINE_PATTERN.test(line)).length
const hasInsertIndicator = nonEmptyBottom.some((line) => VIM_INSERT_LINE_PATTERN.test(line))
const hasNormalIndicator = nonEmptyBottom.some((line) => VIM_NORMAL_LINE_PATTERN.test(line))
const hasRulerIndicator = nonEmptyBottom.some((line) => VIM_RULER_LINE_PATTERN.test(line))
const titleLooksLikeVim = !!windowTitle && VIM_WINDOW_TITLE_PATTERN.test(windowTitle)
const hasVimBufferChrome =
tildeCount >= 2 || hasInsertIndicator || hasNormalIndicator || hasRulerIndicator
// 1. Vim 명령줄 모드 (:ㅈㅂ, :wq, :q! 등)
for (let i = 0; i < Math.min(2, nonEmptyBottom.length); i += 1) {
const candidate = nonEmptyBottom[i].replace(/\s+\d+,\d+.*$/u, '').trimEnd()
if (VIM_COMMAND_LINE_PATTERN.test(candidate)) {
return {
prefix: candidate,
caretReliable: true,
vimMode: 'command',
isVimScreen: true
}
}
}
// 2. 화면에 Vim 상태줄·물결표(~)·룰러가 전혀 없고 셸 프롬프트(PS ...>, $ 등)가 있으면
// 창 제목에 vim/nvim 이 남아 있더라도 일반 셸 입력 줄로 처리한다.
if (!hasVimBufferChrome) {
const promptPrefix = extractTerminalPromptPrefix(currScreen)
if (promptPrefix !== null) {
return {
prefix: promptPrefix,
caretReliable: true,
vimMode: null,
isVimScreen: false
}
}
}
const isVimScreen = hasVimBufferChrome || titleLooksLikeVim
let vimMode: TerminalVimMode = null
if (hasInsertIndicator) {
vimMode = 'insert'
} else if (hasNormalIndicator) {
vimMode = 'normal'
} else if (isVimScreen) {
vimMode = trackerVimMode === 'insert' ? 'insert' : 'normal'
}
// 3. Vim 노멀/비주얼 모드에서는 일반 텍스트 교정을 막는다.
if (vimMode === 'normal') {
return {
prefix: '',
caretReliable: false,
vimMode: 'normal',
isVimScreen: true
}
}
// 3. 직전 스냅샷과 현재 스냅샷을 줄 단위로 비교해 실제 타이핑이 일어난 내용 줄을 찾는다.
if (prevScreen && prevScreen !== currScreen) {
const prevLines = prevScreen.replace(/\r/g, '').split('\n')
const scanStart = Math.max(0, currLines.length - TERMINAL_SCAN_LINES)
for (let i = currLines.length - 1; i >= scanStart; i -= 1) {
const currRaw = currLines[i]
if (isTerminalStatusOrNoiseLine(currRaw)) continue
const prevRaw = prevLines[i] ?? ''
const currClean = trimGridPadding(currRaw)
const prevClean = trimGridPadding(prevRaw)
if (currClean === prevClean) continue
const suffixLen = commonSuffixLength(prevClean, currClean)
const editEnd = Math.max(0, currClean.length - suffixLen)
const editedSlice = editEnd > 0 ? currClean.slice(0, editEnd) : currClean
const prefix = stripPromptFromLine(editedSlice)
if (prefix.trim().length > 0) {
return {
prefix,
caretReliable: true,
vimMode,
isVimScreen
}
}
}
}
// 4. 화면이 직전 스냅샷과 같고(예: 멈춤 뒤 settle 타이머) 마지막 활성 줄이 여전히 화면에 있으면 유지한다.
if (lastActivePrefix && lastActivePrefix.trim().length > 0) {
const trimmedLast = lastActivePrefix.trimEnd()
if (currScreen.includes(trimmedLast)) {
const keepTrailingSpace = !lastActivePrefix.endsWith(' ') && currScreen.includes(`${trimmedLast} `)
return {
prefix: keepTrailingSpace ? `${trimmedLast} ` : lastActivePrefix,
caretReliable: true,
vimMode,
isVimScreen
}
}
}
// 5. 셸 프롬프트 줄 폴백
const promptPrefix = extractTerminalPromptPrefix(currScreen)
if (promptPrefix !== null) {
return {
prefix: promptPrefix,
caretReliable: true,
vimMode,
isVimScreen
}
}
// 6. Vim INSERT 모드인데 직전 화면이 없으면 가장 아래쪽 일반 내용 줄을 사용한다.
if (vimMode === 'insert') {
for (let i = currLines.length - 1; i >= 0; i -= 1) {
if (isTerminalStatusOrNoiseLine(currLines[i])) continue
const prefix = stripPromptFromLine(trimGridPadding(currLines[i]))
if (prefix.trim().length > 0) {
return {
prefix,
caretReliable: true,
vimMode: 'insert',
isVimScreen: true
}
}
}
}
return { prefix: '', caretReliable: false, vimMode, isVimScreen }
}
// ============================================================
// 두벌식 키 스트림 조합기 + 터미널/Vim 키스트로크 추적기
// ============================================================
const CHO = [
'ㄱ', 'ㄲ', 'ㄴ', 'ㄷ', 'ㄸ', 'ㄹ', 'ㅁ', 'ㅂ', 'ㅃ', 'ㅅ',
'ㅆ', 'ㅇ', 'ㅈ', 'ㅉ', 'ㅊ', 'ㅋ', 'ㅌ', 'ㅍ', 'ㅎ'
] as const
const JUNG = [
'ㅏ', 'ㅐ', 'ㅑ', 'ㅒ', 'ㅓ', 'ㅔ', 'ㅕ', 'ㅖ', 'ㅗ', 'ㅘ',
'ㅙ', 'ㅚ', 'ㅛ', 'ㅜ', 'ㅝ', 'ㅞ', 'ㅟ', 'ㅠ', 'ㅡ', 'ㅢ', 'ㅣ'
] as const
const JONG = [
'', 'ㄱ', 'ㄲ', 'ㄳ', 'ㄴ', 'ㄵ', 'ㄶ', 'ㄷ', 'ㄹ', 'ㄺ',
'ㄻ', 'ㄼ', 'ㄽ', 'ㄾ', 'ㄿ', 'ㅀ', 'ㅁ', 'ㅂ', 'ㅄ', 'ㅅ',
'ㅆ', 'ㅇ', 'ㅈ', 'ㅊ', 'ㅋ', 'ㅌ', 'ㅍ', 'ㅎ'
] as const
const KEY_TO_JAMO: Readonly<Record<string, string>> = {
q: 'ㅂ', Q: 'ㅃ', w: 'ㅈ', W: 'ㅉ', e: 'ㄷ', E: 'ㄸ', r: 'ㄱ', R: 'ㄲ', t: 'ㅅ', T: 'ㅆ',
y: 'ㅛ', u: 'ㅕ', i: 'ㅑ', o: 'ㅐ', O: 'ㅒ', p: 'ㅔ', P: 'ㅖ',
a: 'ㅁ', s: 'ㄴ', d: 'ㅇ', f: 'ㄹ', g: 'ㅎ', h: 'ㅗ', j: 'ㅓ', k: 'ㅏ', l: 'ㅣ',
z: 'ㅋ', x: 'ㅌ', c: 'ㅊ', v: 'ㅍ', b: 'ㅠ', n: 'ㅜ', m: 'ㅡ'
}
const COMPOUND_VOWEL: Readonly<Record<string, string>> = {
'ㅗㅏ': 'ㅘ', 'ㅗㅐ': 'ㅙ', 'ㅗㅣ': 'ㅚ',
'ㅜㅓ': 'ㅝ', 'ㅜㅔ': 'ㅞ', 'ㅜㅣ': 'ㅟ',
'ㅡㅣ': 'ㅢ'
}
const COMPOUND_JONG: Readonly<Record<string, string>> = {
'ㄱㅅ': 'ㄳ', 'ㄴㅈ': 'ㄵ', 'ㄴㅎ': 'ㄶ',
'ㄹㄱ': 'ㄺ', 'ㄹㅁ': 'ㄻ', 'ㄹㅂ': 'ㄼ', 'ㄹㅅ': 'ㄽ', 'ㄹㅌ': 'ㄾ', 'ㄹㅍ': 'ㄿ', 'ㄹㅎ': 'ㅀ',
'ㅂㅅ': 'ㅄ'
}
/**
* 영문 두벌식 키열을 Windows 한국어 IME 와 동일하게 조합한다.
*/
export function composeHangul2Set(keys: string): string {
const jamos: string[] = []
for (const ch of keys) {
const mapped = KEY_TO_JAMO[ch] ?? KEY_TO_JAMO[ch.toLowerCase()]
if (!mapped) {
jamos.push(ch)
} else {
jamos.push(mapped)
}
}
let out = ''
let i = 0
const isConsonant = (j: string): boolean => CHO.includes(j as (typeof CHO)[number])
const isVowel = (j: string): boolean => JUNG.includes(j as (typeof JUNG)[number])
while (i < jamos.length) {
const curr = jamos[i]
// 자음 + 모음 → 음절 시작
if (isConsonant(curr) && i + 1 < jamos.length && isVowel(jamos[i + 1])) {
const choIdx = CHO.indexOf(curr as (typeof CHO)[number])
let v = jamos[i + 1]
i += 2
if (i < jamos.length && isVowel(jamos[i]) && COMPOUND_VOWEL[v + jamos[i]]) {
v = COMPOUND_VOWEL[v + jamos[i]]
i += 1
}
const jungIdx = JUNG.indexOf(v as (typeof JUNG)[number])
let jong = ''
// 받침 확인 (다음 자음이 모음과 결합해 연음되면 받침으로 쓰지 않는다)
if (i < jamos.length && isConsonant(jamos[i])) {
const c1 = jamos[i]
const nextIsVowel = i + 1 < jamos.length && isVowel(jamos[i + 1])
if (!nextIsVowel && JONG.includes(c1 as (typeof JONG)[number])) {
jong = c1
i += 1
if (i < jamos.length && isConsonant(jamos[i])) {
const c2 = jamos[i]
const afterC2IsVowel = i + 1 < jamos.length && isVowel(jamos[i + 1])
const compound = COMPOUND_JONG[c1 + c2]
if (!afterC2IsVowel && compound) {
jong = compound
i += 1
}
}
}
}
const jongIdx = JONG.indexOf(jong as (typeof JONG)[number])
out += String.fromCharCode(0xac00 + (choIdx * 21 + jungIdx) * 28 + Math.max(0, jongIdx))
continue
}
// 단독 모음 합성 (ㅗ + ㅏ = ㅘ 등)
if (isVowel(curr) && i + 1 < jamos.length && isVowel(jamos[i + 1]) && COMPOUND_VOWEL[curr + jamos[i + 1]]) {
out += COMPOUND_VOWEL[curr + jamos[i + 1]]
i += 2
continue
}
out += curr
i += 1
}
return out
}
const SHIFTED_DIGITS = ')!@#$%^&*('
export function vkToPrintableChar(vk: number, shift: boolean): string | null {
if (vk >= 0x41 && vk <= 0x5a) {
return shift ? String.fromCharCode(vk) : String.fromCharCode(vk + 32)
}
if (vk >= 0x30 && vk <= 0x39) {
return shift ? (SHIFTED_DIGITS[vk - 0x30] ?? null) : String.fromCharCode(vk)
}
if (vk >= 0x60 && vk <= 0x69) {
return String.fromCharCode(vk - 0x30)
}
switch (vk) {
case 0xba:
return shift ? ':' : ';'
case 0xbb:
return shift ? '+' : '='
case 0xbc:
return shift ? '<' : ','
case 0xbd:
return shift ? '_' : '-'
case 0xbe:
return shift ? '>' : '.'
case 0xbf:
return shift ? '?' : '/'
case 0xc0:
return shift ? '~' : '`'
case 0xdb:
return shift ? '{' : '['
case 0xdc:
return shift ? '|' : '\\'
case 0xdd:
return shift ? '}' : ']'
case 0xde:
return shift ? '"' : "'"
default:
return null
}
}
export interface TerminalKeyInput {
hwnd: number | null
windowTitle?: string | null
vk: number | null
rawKeycode?: number
shift: boolean
ctrl: boolean
alt: boolean
meta: boolean
koreanIme?: boolean | null
now?: number
}
/**
* 터미널 및 Vim 키스트로크 추적기.
*
* UIA 가 터미널 줄 끝 공백을 잘라 버리거나(Windows Terminal), 캔버스/원격 터미널(Kitedesk,
* WezTerm, Alacritty, xterm.js 등)에서 텍스트를 전혀 돌려주지 않을 때(len=0), 그리고 Vim 의
* 노멀/입력/명령줄 모드를 오갈 때 정확한 현재 줄 접두와 조합 상태를 복원한다.
*/
export class TerminalKeystrokeTracker {
private _hwnd: number | null = null
private _committed = ''
private _composingKeys = ''
private _koreanIme = false
private _imm32Supported = false
private _lastImeToggleAt = 0
private _vimSession = false
private _vimMode: TerminalVimMode = null
private _pendingVimOperator = ''
private _afterEscape = false
private _lastKeyWasSpace = false
private _shellPromptScreen = false
private _prevScreen: string | null = null
private _lastScreenPrefix: string | null = null
private _unreplacedStart = 0
private _lastXtermValue = ''
reset(): void {
this._committed = ''
this._composingKeys = ''
this._pendingVimOperator = ''
this._afterEscape = false
this._lastKeyWasSpace = false
this._lastScreenPrefix = null
this._unreplacedStart = 0
}
onPointerOrFocusChange(hwnd?: number | null): void {
if (hwnd !== undefined && hwnd !== this._hwnd) {
this._hwnd = hwnd
this._imm32Supported = false
this._vimSession = false
this._vimMode = null
this._shellPromptScreen = false
this._prevScreen = null
this._lastXtermValue = ''
}
this.reset()
}
onKeyDown(input: TerminalKeyInput): void {
const now = input.now ?? Date.now()
if (input.hwnd !== null && input.hwnd !== this._hwnd) {
this._hwnd = input.hwnd
this._imm32Supported = false
this._vimSession = false
this._vimMode = null
this._shellPromptScreen = false
this._prevScreen = null
this._lastXtermValue = ''
this.reset()
}
if (!this._shellPromptScreen && input.windowTitle && VIM_WINDOW_TITLE_PATTERN.test(input.windowTitle)) {
this._vimSession = true
if (this._vimMode === null) this._vimMode = 'normal'
}
// 한/영 전환 키 (VK_HANGUL = 0x15, uiohook keycode = 112)
if (input.rawKeycode === 112 || input.vk === 0x15) {
this._flushComposing()
// Vim 노멀 모드(또는 Esc 직후)에서 i/a/o 를 눌러 입력 모드로 들어간 직후 한/영 키를 눌렀다면
// 앞에 찍힌 i/a/o 는 Vim 명령이므로 버퍼에서 비운다.
if (
(this._afterEscape || this._vimSession) &&
/^[hjklwbe0$dugG]*[iIaAoOsSCR]$/u.test(this._committed)
) {
this._committed = ''
this._vimSession = true
this._vimMode = 'insert'
this._afterEscape = false
}
this._koreanIme = !this._koreanIme
this._lastImeToggleAt = now
return
}
// Chromium/Electron(Agent Switchboard, VS Code 등)은 TSF IME 를 사용해 최상위 HWND 의
// ImmGetDefaultIMEWnd(IMC_GETCONVERSIONMODE)가 한글 상태에서도 항상 false(0)를 돌려준다.
// 따라서 해당 창에서 한 번이라도 true 가 관측된 경우(_imm32Supported)에만 false 로의 하향 동기화를 허용한다.
if (typeof input.koreanIme === 'boolean') {
if (input.koreanIme) {
this._imm32Supported = true
}
if ((input.koreanIme || this._imm32Supported) && now - this._lastImeToggleAt > 250) {
if (this._koreanIme && !input.koreanIme) {
this._flushComposing()
}
this._koreanIme = input.koreanIme
}
}
const { vk, shift, ctrl, alt, meta } = input
// Escape 또는 Ctrl+[ / Ctrl+C → 현재 줄 초기화 (실제 Esc/Ctrl+[ 만 _afterEscape 설정)
const isRealEscape = vk === 0x1b || (ctrl && !alt && !meta && vk === 0xdb)
const isCtrlC = ctrl && !alt && !meta && vk === 0x43
if (isRealEscape || isCtrlC) {
this.reset()
if (isRealEscape) {
this._afterEscape = true
}
if (this._vimSession) {
this._vimMode = 'normal'
}
return
}
// 기타 단축키(Ctrl/Alt/Meta 조합)는 버퍼를 비운다.
if (ctrl || alt || meta) {
this.reset()
return
}
if (vk === null) {
this._lastKeyWasSpace = false
return
}
// Enter (0x0D)
if (vk === 0x0d) {
this._lastKeyWasSpace = false
const fullLine = this.currentPrefix().trim()
if (VIM_SHELL_LAUNCH_PATTERN.test(fullLine)) {
this._vimSession = true
this._vimMode = 'normal'
} else if (this._vimMode === 'command') {
const cmd = fullLine.replace(/^:/u, '').trim()
if (/^(?:q|qa|wq|wqa|x|xa)!?$/u.test(cmd)) {
this._vimSession = false
this._vimMode = null
} else {
this._vimMode = 'normal'
}
}
this.reset()
return
}
// Tab (0x09), 화살표(0x25..0x28), Home/End/PgUp/PgDn/Delete(0x21..0x24, 0x2E)
if (vk === 0x09 || (vk >= 0x21 && vk <= 0x28) || vk === 0x2e) {
this.reset()
return
}
// Backspace (0x08)
if (vk === 0x08) {
this._lastKeyWasSpace = false
if (this._composingKeys.length > 0) {
this._composingKeys = this._composingKeys.slice(0, -1)
return
}
if (this._committed.length > 0) {
this._committed = this._committed.slice(0, -1)
this._unreplacedStart = Math.min(this._unreplacedStart, this._committed.length)
if (this._vimMode === 'command' && this._committed.length === 0) {
this._vimMode = 'normal'
}
}
return
}
// Space (0x20)
if (vk === 0x20) {
if (this._vimMode === 'normal') {
this._pendingVimOperator = ''
this._lastKeyWasSpace = false
return
}
this._flushComposing()
this._committed += ' '
this._lastKeyWasSpace = true
return
}
this._lastKeyWasSpace = false
const ch = vkToPrintableChar(vk, shift)
if (!ch) return
// Vim 노멀 모드에서의 키 처리
if (this._vimMode === 'normal') {
this._handleVimNormalChar(ch)
return
}
// 아직 vimSession 이 확정되지 않았더라도 Esc 직후나 줄 맨 앞에서 ':' 를 치면 즉시 Vim 명령줄 모드로 본다.
if (ch === ':' && (this._afterEscape || (this._committed.length === 0 && this._composingKeys.length === 0))) {
this._flushComposing()
this._vimSession = true
this._vimMode = 'command'
this._afterEscape = false
this._committed = ':'
return
}
// 알파벳 키 (A..Z)
if (vk >= 0x41 && vk <= 0x5a) {
// Esc 직후 영문 상태에서 노멀 모드 이동키(h/j/k/l 2회 이상 또는 기존 vimSession) 뒤에 i/a/o/s 를 친 경우
if (
this._afterEscape &&
!this._koreanIme &&
/^[iIaAoOsSCR]$/u.test(ch) &&
/^[hjklwbe0$dugG]*$/u.test(this._committed) &&
(this._vimSession || /[hjkl]{2,}/u.test(this._committed))
) {
this._vimSession = true
this._vimMode = 'insert'
this._afterEscape = false
this._committed = ''
this._composingKeys = ''
return
}
if (this._koreanIme) {
const normKey = /^[QWERTPO]$/u.test(ch) ? ch : ch.toLowerCase()
this._composingKeys += normKey
this._commitOverflowSyllables()
} else {
this._flushComposing()
this._committed += ch
}
return
}
// 숫자 및 문장부호: 한글 조합을 먼저 확정하고 문자를 추가한다.
this._flushComposing()
this._committed += ch
}
/**
* 프로그램(오타 교정)이 커서 앞 deleteCount 글자를 지우고 insertText 를 넣었을 때 버퍼를 동기화한다.
* 비동기 치환 도중 사용자가 추가로 친 글자(baseLength 이후)가 있으면 유실하지 않고 뒤에 보존한다.
*/
applyReplacement(deleteCount: number, insertText: string, baseLength?: number): void {
const full = this.currentPrefix()
const targetEnd =
baseLength !== undefined && baseLength >= 0 ? Math.min(baseLength, full.length) : full.length
const keepLen = Math.max(0, targetEnd - Math.max(0, deleteCount))
const typedAfterStart = full.slice(targetEnd)
this._committed = full.slice(0, keepLen) + insertText + typedAfterStart
this._composingKeys = ''
this._lastKeyWasSpace = this._committed.endsWith(' ')
this._lastScreenPrefix = this._committed
this._unreplacedStart = keepLen + insertText.length
}
currentPrefix(): string {
return this._committed + (this._composingKeys ? composeHangul2Set(this._composingKeys) : '')
}
get isComposing(): boolean {
return this._composingKeys.length > 0
}
get vimMode(): TerminalVimMode {
return this._vimMode
}
/**
* UIA 텍스트가 없는 터미널(Kitedesk, 캔버스 터미널 등)에서 현재 키스트로크 문맥을 돌려준다.
*/
getSnapshot(
hwnd: number | null,
windowTitle?: string | null
): { prefix: string; caretReliable: boolean; isComposing: boolean; vimMode: TerminalVimMode } {
if (hwnd !== null && this._hwnd !== null && hwnd !== this._hwnd) {
return { prefix: '', caretReliable: false, isComposing: false, vimMode: null }
}
if (windowTitle && VIM_WINDOW_TITLE_PATTERN.test(windowTitle)) {
this._vimSession = true
}
if (this._vimMode === 'normal') {
return { prefix: '', caretReliable: false, isComposing: false, vimMode: 'normal' }
}
const prefix = this.currentPrefix()
return {
prefix,
caretReliable: prefix.length > 0,
isComposing: this.isComposing,
vimMode: this._vimMode
}
}
/**
* UIA 화면 버퍼가 있는 터미널(Windows Terminal, pwsh, cmd 등)에서 화면 파싱과 키스트로크 버퍼를 결합한다.
*/
reconcileWithScreen(
currScreen: string | null | undefined,
windowTitle?: string | null
): { prefix: string; caretReliable: boolean; isComposing: boolean; vimMode: TerminalVimMode } {
const screenCtx = extractTerminalActiveContext(
this._prevScreen,
currScreen,
this._lastScreenPrefix,
windowTitle,
this._vimMode
)
this._prevScreen = currScreen ?? null
if (screenCtx.isVimScreen) {
this._shellPromptScreen = false
this._vimSession = true
if (screenCtx.vimMode !== null) {
if (screenCtx.vimMode === 'normal' && this._vimMode !== 'normal') {
this.reset()
}
this._vimMode = screenCtx.vimMode
}
} else if (screenCtx.prefix.length > 0) {
this._shellPromptScreen = true
this._vimSession = false
this._vimMode = null
}
if (this._vimMode === 'normal' || screenCtx.vimMode === 'normal') {
return { prefix: '', caretReliable: false, isComposing: false, vimMode: 'normal' }
}
const tracked = this.currentPrefix()
// Vim 명령줄(:ㅈㅂ 등)은 화면에 실제 ':...' 줄이 보이면 그 줄을 정본으로 삼고,
// 아직 화면에 반영되지 않은 방금 친 키가 있을 때만(tracked 가 screenCtx.prefix 로 시작할 때) tracked 를 쓴다.
if (screenCtx.vimMode === 'command' || this._vimMode === 'command') {
let cmdPrefix: string
if (screenCtx.prefix.startsWith(':')) {
cmdPrefix =
tracked.startsWith(screenCtx.prefix) && tracked.length > screenCtx.prefix.length
? tracked
: screenCtx.prefix
} else if (tracked.startsWith(':')) {
cmdPrefix = tracked
} else {
cmdPrefix = screenCtx.prefix || tracked
}
this._committed = cmdPrefix
this._composingKeys = ''
this._lastScreenPrefix = cmdPrefix
return {
prefix: cmdPrefix,
caretReliable: cmdPrefix.length > 1,
isComposing: this.isComposing,
vimMode: 'command'
}
}
// Windows Terminal 등 그리드 터미널은 줄 끝 공백을 UIA 텍스트에서 잘라 버린다.
// 방금 Space 키를 쳤다면(또는 키 버퍼 끝에 공백이 있다면) 화면 줄 끝에 공백을 복원한다.
let resolved = screenCtx.prefix
if (!resolved.trim() && tracked.length > 0) {
resolved = tracked
} else if (resolved.trim().length > 0 && !resolved.endsWith(' ') && this._lastKeyWasSpace) {
resolved = resolved.trimEnd() + ' '
}
this._lastScreenPrefix = resolved
return {
prefix: resolved,
caretReliable: resolved.trim().length > 0,
isComposing: this.isComposing,
vimMode: this._vimMode ?? screenCtx.vimMode
}
}
/**
* xterm.js(`xterm-helper-textarea`)의 `.value` 와 키스트로크 버퍼를 결합한다.
*
* xterm.js 는 Backspace·Space·영문 키를 `preventDefault()` 로 가로채 PTY 로만 보내고
* `<textarea>.value` 는 Enter/Ctrl+C 전까지 비우지 않는다. 따라서 실제 편집 문맥은
* 키스트로크 버퍼(`currentPrefix()`)를 정본으로 삼되, `.value` 에 새 한글이 들어오면
* 한글 IME 활성 신호로 삼아 아직 치환되지 않은 영문 키들을 두벌식 한글로 복원한다.
*/
reconcileWithXtermValue(
xtermValue: string | null | undefined,
hwnd: number | null,
windowTitle?: string | null
): { prefix: string; caretReliable: boolean; isComposing: boolean; vimMode: TerminalVimMode } {
const raw = xtermValue ?? ''
if (hwnd !== null && this._hwnd !== null && hwnd !== this._hwnd) {
this._hwnd = hwnd
this._imm32Supported = false
this._vimSession = false
this._vimMode = null
this._shellPromptScreen = false
this._prevScreen = null
this._lastXtermValue = raw
this.reset()
} else if (raw !== this._lastXtermValue) {
const hasNewHangul =
/[가-힣ㄱ-ㆎ]\s*$/u.test(raw) && raw.trimEnd() !== this._lastXtermValue.trimEnd()
if (hasNewHangul) {
this._koreanIme = true
const unreplacedTail = this._committed.slice(this._unreplacedStart)
if (/[A-Za-z]/u.test(unreplacedTail) && !/[가-힣ㄱ-ㆎ]/u.test(unreplacedTail)) {
const convertedTail = unreplacedTail.replace(/[A-Za-z]+/gu, (word) => {
const norm = word.replace(/[A-Z]/gu, (c) => (/^[QWERTPO]$/u.test(c) ? c : c.toLowerCase()))
return composeHangul2Set(norm)
})
this._committed = this._committed.slice(0, this._unreplacedStart) + convertedTail
} else if (
this._unreplacedStart === 0 &&
raw.startsWith(this.currentPrefix()) &&
raw.length > this.currentPrefix().length
) {
this._committed = raw
this._composingKeys = ''
}
}
this._lastXtermValue = raw
}
return this.getSnapshot(hwnd, windowTitle)
}
private _handleVimNormalChar(ch: string): void {
if (this._pendingVimOperator === 'c') {
if (ch === 'i' || ch === 'a' || ch === 'f' || ch === 'F' || ch === 't' || ch === 'T') {
this._pendingVimOperator = `c${ch}`
return
}
if (/^[wWeEbBc$0^]$/u.test(ch)) {
this._enterVimInsertMode()
return
}
this._pendingVimOperator = ''
return
}
if (this._pendingVimOperator.length === 2) {
this._enterVimInsertMode()
return
}
if (ch === 'c') {
this._pendingVimOperator = 'c'
return
}
if (/^[iIaAoOsSCR]$/u.test(ch)) {
this._enterVimInsertMode()
return
}
if (ch === ':') {
this._vimMode = 'command'
this._pendingVimOperator = ''
this._afterEscape = false
this._committed = ':'
this._composingKeys = ''
}
}
private _enterVimInsertMode(): void {
this._vimSession = true
this._vimMode = 'insert'
this._pendingVimOperator = ''
this._afterEscape = false
this._committed = ''
this._composingKeys = ''
}
private _flushComposing(): void {
if (this._composingKeys.length === 0) return
this._committed += composeHangul2Set(this._composingKeys)
this._composingKeys = ''
}
/**
* Windows 한국어 두벌식 IME 와 동일하게, 현재 조합 중인 마지막 1글자만 _composingKeys 에 남기고
* 이미 완성된 앞 글자들은 _committed 로 넘긴다.
*/
private _commitOverflowSyllables(): void {
const full = composeHangul2Set(this._composingKeys)
if (full.length < 2) return
const targetPrefix = full.slice(0, -1)
const targetLast = full.slice(-1)
for (let i = 1; i < this._composingKeys.length; i += 1) {
if (
composeHangul2Set(this._composingKeys.slice(0, i)) === targetPrefix &&
composeHangul2Set(this._composingKeys.slice(i)) === targetLast
) {
this._committed += targetPrefix
this._composingKeys = this._composingKeys.slice(i)
return
}
}
}
}