Debian Codegraph @

pkg/twwidth/ea.go

raw
1 /*
2 Package twwidth provides intelligent East Asian width detection.
3
4 In 2025/2026, most modern terminal emulators (VSCode, Windows Terminal, iTerm2,
5 Alacritty) and modern monospace fonts (Hack, Fira Code, Cascadia Code) treat
6 box-drawing characters as Single Width, regardless of the underlying OS Locale.
7
8 Detection Logic (in order of priority):
9 - RUNEWIDTH_EASTASIAN environment variable (explicit user override)
10 - Force Legacy Mode (programmatic override for backward compatibility)
11 - Modern environment detection (VSCode, Windows Terminal, etc. -> Narrow)
12 - Locale-based detection (CJK locales in traditional terminals -> Wide)
13
14 This prioritization ensures that:
15 - Users can always override behavior using RUNEWIDTH_EASTASIAN
16 - Modern development environments work correctly by default
17 - Traditional CJK terminals maintain compatibility via locale checks
18
19 Examples:
20
21 // Force narrow borders (for Hack font in zh_CN)
22 RUNEWIDTH_EASTASIAN=0 go run .
23
24 // Force wide borders (for legacy CJK terminals)
25 RUNEWIDTH_EASTASIAN=1 go run .
26 */
27 package twwidth
28
29 import (
30 "os"
31 "runtime"
32 "strings"
33 "sync"
34 )
35
36 // Environment Variable Constants
37 const (
38 EnvLCAll = "LC_ALL"
39 EnvLCCtype = "LC_CTYPE"
40 EnvLang = "LANG"
41 EnvRuneWidthEastAsian = "RUNEWIDTH_EASTASIAN"
42 EnvTerm = "TERM"
43 EnvTermProgram = "TERM_PROGRAM"
44 EnvTermProgramWsl = "TERM_PROGRAM_WSL"
45 EnvWTProfile = "WT_PROFILE_ID" // Windows Terminal
46 EnvConEmuANSI = "ConEmuANSI" // ConEmu
47 EnvAlacritty = "ALACRITTY_LOG" // Alacritty
48 EnvVTEVersion = "VTE_VERSION" // GNOME/VTE
49 )
50
51 const (
52 overwriteOn = "override_on"
53 overwriteOff = "override_off"
54
55 envModern = "modern_env"
56 envCjk = "locale_cjk"
57 envAscii = "default_ascii"
58 )
59
60 // CJK Language Codes (Prefixes)
61 // Covers ISO 639-1 (2-letter) and common full names used in some systems.
62 var cjkPrefixes = []string{
63 "zh", "ja", "ko", // Standard: Chinese, Japanese, Korean
64 "chi", "zho", // ISO 639-2/B and T for Chinese
65 "jpn", "kor", // ISO 639-2 for Japanese, Korean
66 "chinese", "japanese", "korean", // Full names (rare but possible in some legacy systems)
67 }
68
69 // CJK Region Codes
70 // Checks for specific regions that imply CJK font usage (e.g., en_HK).
71 var cjkRegions = map[string]bool{
72 "cn": true, // China
73 "tw": true, // Taiwan
74 "hk": true, // Hong Kong
75 "mo": true, // Macau
76 "jp": true, // Japan
77 "kr": true, // South Korea
78 "kp": true, // North Korea
79 "sg": true, // Singapore (Often uses CJK fonts)
80 }
81
82 // Modern environments that should use narrow borders (1-width box chars)
83 var modernEnvironments = map[string]bool{
84 // Terminal programs
85 "vscode": true, "visual studio code": true,
86 "iterm.app": true, "iterm2": true,
87 "windows terminal": true, "windowsterminal": true,
88 "alacritty": true, "kitty": true,
89 "hyper": true, "tabby": true, "terminus": true, "fluentterminal": true,
90 "warp": true, "ghostty": true, "rio": true,
91 "jetbrains-jediterm": true,
92
93 // Terminal types (TERM signatures)
94 "xterm-kitty": true, "xterm-ghostty": true, "wezterm": true,
95 }
96
97 var (
98 eastAsianOnce sync.Once
99 eastAsianVal bool
100
101 // Legacy override control
102 // Renamed to cfgMu to avoid conflict with width.go's mu
103 cfgMu sync.RWMutex
104 forceLegacyEastAsian = false
105 )
106
107 type Enviroment struct {
108 GOOS string `json:"goos"`
109 LC_ALL string `json:"lc_all"`
110 LC_CTYPE string `json:"lc_ctype"`
111 LANG string `json:"lang"`
112 RUNEWIDTH_EASTASIAN string `json:"runewidth_eastasian"`
113 TERM string `json:"term"`
114 TERM_PROGRAM string `json:"term_program"`
115 }
116
117 // State captures the calculated internal state.
118 type State struct {
119 NormalizedLocale string `json:"normalized_locale"`
120 IsCJKLocale bool `json:"is_cjk_locale"`
121 IsModernEnv bool `json:"is_modern_env"`
122 LegacyOverrideMode bool `json:"legacy_override_mode"`
123 }
124
125 // Detection aggregates all debug information regarding East Asian width detection.
126 type Detection struct {
127 AutoUseEastAsian bool `json:"auto_use_east_asian"`
128 DetectionMode string `json:"detection_mode"`
129 Raw Enviroment `json:"raw"`
130 Derived State `json:"derived"`
131 }
132
133 // EastAsianForceLegacy forces the detection logic to ignore modern environment checks.
134 // It relies solely on Locale detection. This is useful for applications that need
135 // strict backward compatibility.
136 //
137 // Note: This does NOT override RUNEWIDTH_EASTASIAN. User environment variables take precedence.
138 // This should be called before the first table render.
139 func EastAsianForceLegacy(force bool) {
140 cfgMu.Lock()
141 defer cfgMu.Unlock()
142 forceLegacyEastAsian = force
143 }
144
145 // EastAsianDetect checks the environment variables to determine if
146 // East Asian width calculations should be enabled.
147 func EastAsianDetect() bool {
148 eastAsianOnce.Do(func() {
149 eastAsianVal = detectEastAsian()
150 })
151 return eastAsianVal
152 }
153
154 // EastAsianConservative is a stricter version that only defaults to Narrow
155 // if the terminal is definitely known to be modern (e.g. VSCode, iTerm2).
156 // It avoids heuristics like checking "xterm" in the TERM variable.
157 func EastAsianConservative() bool {
158 // Check overrides first
159 if val, found := checkOverrides(); found {
160 return val
161 }
162
163 // Stricter modern environment detection
164 if isConservativeModernEnvironment() {
165 return false
166 }
167
168 // Fall back to locale
169 return checkLocale()
170 }
171
172 // EastAsianMode returns the decision path used for the current environment.
173 // Useful for debugging why a specific width was chosen.
174 func EastAsianMode() string {
175 // Check override
176 if val, found := checkOverrides(); found {
177 if val {
178 return overwriteOn
179 }
180 return overwriteOff
181 }
182
183 cfgMu.RLock()
184 legacy := forceLegacyEastAsian
185 cfgMu.RUnlock()
186
187 if legacy {
188 if checkLocale() {
189 return envCjk
190 }
191 return envAscii
192 }
193
194 if isModernEnvironment() {
195 return envModern
196 }
197
198 if checkLocale() {
199 return envCjk
200 }
201
202 return envAscii
203 }
204
205 // Debugging returns detailed information about the detection decision.
206 // Useful for users to include in Github issues.
207 func Debugging() Detection {
208 locale := getNormalizedLocale()
209
210 cfgMu.RLock()
211 legacy := forceLegacyEastAsian
212 cfgMu.RUnlock()
213
214 return Detection{
215 AutoUseEastAsian: EastAsianDetect(),
216 DetectionMode: EastAsianMode(),
217 Raw: Enviroment{
218 GOOS: runtime.GOOS,
219 LC_ALL: os.Getenv(EnvLCAll),
220 LC_CTYPE: os.Getenv(EnvLCCtype),
221 LANG: os.Getenv(EnvLang),
222 RUNEWIDTH_EASTASIAN: os.Getenv(EnvRuneWidthEastAsian),
223 TERM: os.Getenv(EnvTerm),
224 TERM_PROGRAM: os.Getenv(EnvTermProgram),
225 },
226 Derived: State{
227 NormalizedLocale: locale,
228 IsCJKLocale: isCJKLocale(locale),
229 IsModernEnv: isModernEnvironment(),
230 LegacyOverrideMode: legacy,
231 },
232 }
233 }
234
235 // detectEastAsian evaluates the environment and locale settings to determine if East Asian width rules should apply.
236 func detectEastAsian() bool {
237 // User Override check (Highest Priority)
238 if val, found := checkOverrides(); found {
239 return val
240 }
241
242 // Force Legacy Mode check
243 cfgMu.RLock()
244 isLegacy := forceLegacyEastAsian
245 cfgMu.RUnlock()
246
247 if isLegacy {
248 // Legacy mode ignores modern environment checks,
249 // relying solely on locale.
250 return checkLocale()
251 }
252
253 // Modern Environment Detection
254 // If modern, we assume Single Width (return false)
255 if isModernEnvironment() {
256 return false
257 }
258
259 // 4. Locale Fallback
260 return checkLocale()
261 }
262
263 // checkOverrides looks for RUNEWIDTH_EASTASIAN
264 func checkOverrides() (bool, bool) {
265 if rw := os.Getenv(EnvRuneWidthEastAsian); rw != "" {
266 rw = strings.ToLower(rw)
267 if rw == "0" || rw == "off" || rw == "false" || rw == "no" {
268 return false, true
269 }
270 if rw == "1" || rw == "on" || rw == "true" || rw == "yes" {
271 return true, true
272 }
273 }
274 return false, false
275 }
276
277 // checkLocale performs the string analysis on LANG/LC_ALL
278 func checkLocale() bool {
279 locale := getNormalizedLocale()
280 if locale == "" {
281 return false
282 }
283 return isCJKLocale(locale)
284 }
285
286 // isModernEnvironment performs comprehensive checks for modern terminal capabilities.
287 func isModernEnvironment() bool {
288 // Check TERM_PROGRAM (Most reliable)
289 if termProg := os.Getenv(EnvTermProgram); termProg != "" {
290 termProgLower := strings.ToLower(termProg)
291 if modernEnvironments[termProgLower] {
292 return true
293 }
294 }
295
296 // Check WSL specific variable
297 if os.Getenv(EnvTermProgramWsl) != "" {
298 return true
299 }
300
301 // Windows Specifics
302 if runtime.GOOS == "windows" {
303 // Windows Terminal
304 if os.Getenv(EnvWTProfile) != "" {
305 return true
306 }
307 // ConEmu/Cmder
308 if os.Getenv(EnvConEmuANSI) == "ON" {
309 return true
310 }
311 // Modern Windows console (Windows 10+) check via TERM
312 if term := os.Getenv(EnvTerm); term != "" {
313 termLower := strings.ToLower(term)
314 if strings.Contains(termLower, "xterm") ||
315 strings.Contains(termLower, "vt") {
316 return true
317 }
318 }
319 }
320
321 // VTE-based terminals (GNOME Terminal, Tilix, etc.)
322 if os.Getenv(EnvVTEVersion) != "" {
323 return true
324 }
325
326 // Check for Alacritty specifically
327 if os.Getenv(EnvAlacritty) != "" {
328 return true
329 }
330
331 // Check TERM for modern terminal signatures
332 if term := os.Getenv(EnvTerm); term != "" {
333 termLower := strings.ToLower(term)
334 // Specific modern terminals often put their name in TERM
335 if modernEnvironments[termLower] {
336 return true
337 }
338 // Heuristics for standard modern-capable descriptors
339 if strings.Contains(termLower, "xterm") && !strings.Contains(termLower, "xterm-mono") {
340 return true
341 }
342 if strings.Contains(termLower, "screen") ||
343 strings.Contains(termLower, "tmux") {
344 return true
345 }
346 }
347
348 return false
349 }
350
351 // isConservativeModernEnvironment performs strict checks only for known modern terminals.
352 func isConservativeModernEnvironment() bool {
353 termProg := strings.ToLower(os.Getenv(EnvTermProgram))
354
355 // Allow-list of definitely modern terminals
356 switch termProg {
357 case "vscode", "visual studio code":
358 return true
359 case "iterm.app", "iterm2":
360 return true
361 case "windows terminal", "windowsterminal":
362 return true
363 case "alacritty", "wezterm", "kitty", "ghostty":
364 return true
365 case "warp", "tabby", "hyper":
366 return true
367 }
368
369 // Windows Terminal via specific Env
370 if os.Getenv(EnvWTProfile) != "" {
371 return true
372 }
373
374 return false
375 }
376
377 // isCJKLocale determines if a given locale string corresponds to a CJK (Chinese, Japanese, Korean) language or region.
378 func isCJKLocale(locale string) bool {
379 // Check Language Prefix
380 for _, prefix := range cjkPrefixes {
381 if strings.HasPrefix(locale, prefix) {
382 return true
383 }
384 }
385
386 // Check Regions
387 parts := strings.Split(locale, "_")
388 if len(parts) > 1 {
389 for _, part := range parts[1:] {
390 if cjkRegions[part] {
391 return true
392 }
393 }
394 }
395
396 return false
397 }
398
399 // getNormalizedLocale returns the normalized locale by inspecting environment variables LC_ALL, LC_CTYPE, and LANG.
400 func getNormalizedLocale() string {
401 var locale string
402 if loc := os.Getenv(EnvLCAll); loc != "" {
403 locale = loc
404 } else if loc := os.Getenv(EnvLCCtype); loc != "" {
405 locale = loc
406 } else if loc := os.Getenv(EnvLang); loc != "" {
407 locale = loc
408 }
409
410 // Fast fail for empty or standard C/POSIX locales
411 if locale == "" || locale == "C" || locale == "POSIX" {
412 return ""
413 }
414
415 // Strip encoding and modifiers
416 if idx := strings.IndexByte(locale, '.'); idx != -1 {
417 locale = locale[:idx]
418 }
419 if idx := strings.IndexByte(locale, '@'); idx != -1 {
420 locale = locale[:idx]
421 }
422
423 return strings.ToLower(locale)
424 }