| 1 |
package twwidth |
| 2 |
|
| 3 |
import ( |
| 4 |
"bytes" |
| 5 |
"regexp" |
| 6 |
"strings" |
| 7 |
"sync" |
| 8 |
|
| 9 |
"github.com/clipperhouse/displaywidth" |
| 10 |
"github.com/mattn/go-runewidth" |
| 11 |
"github.com/olekukonko/tablewriter/pkg/twcache" |
| 12 |
) |
| 13 |
|
| 14 |
const ( |
| 15 |
cacheCapacity = 8192 |
| 16 |
|
| 17 |
cachePrefix = "0:" |
| 18 |
cacheEastAsianPrefix = "1:" |
| 19 |
) |
| 20 |
|
| 21 |
// Options allows for configuring width calculation on a per-call basis. |
| 22 |
type Options struct { |
| 23 |
EastAsianWidth bool |
| 24 |
|
| 25 |
// Explicitly force box drawing chars to be narrow |
| 26 |
// regardless of EastAsianWidth setting. |
| 27 |
ForceNarrowBorders bool |
| 28 |
} |
| 29 |
|
| 30 |
// globalOptions holds the global displaywidth configuration, including East Asian width settings. |
| 31 |
var globalOptions Options |
| 32 |
|
| 33 |
// mu protects access to globalOptions for thread safety. |
| 34 |
var mu sync.Mutex |
| 35 |
|
| 36 |
// ansi is a compiled regular expression for stripping ANSI escape codes from strings. |
| 37 |
var ansi = Filter() |
| 38 |
|
| 39 |
func init() { |
| 40 |
isEastAsian := EastAsianDetect() |
| 41 |
|
| 42 |
cond := runewidth.NewCondition() |
| 43 |
cond.EastAsianWidth = isEastAsian |
| 44 |
|
| 45 |
globalOptions = Options{ |
| 46 |
EastAsianWidth: isEastAsian, |
| 47 |
|
| 48 |
// Auto-enable ForceNarrowBorders for edge cases. |
| 49 |
// If EastAsianWidth is ON (e.g. forced via Env Var), but we detect |
| 50 |
// a modern environment, we might technically want to narrow borders |
| 51 |
// while keeping text wide. |
| 52 |
ForceNarrowBorders: isEastAsian && isModernEnvironment(), |
| 53 |
} |
| 54 |
|
| 55 |
widthCache = twcache.NewLRU[cacheKey, int](cacheCapacity) |
| 56 |
} |
| 57 |
|
| 58 |
// Display calculates the visual width of a string using a specific runewidth.Condition. |
| 59 |
// Deprecated: use WidthWithOptions with the new twwidth.Options struct instead. |
| 60 |
// This function is kept for backward compatibility. |
| 61 |
func Display(cond *runewidth.Condition, str string) int { |
| 62 |
opts := Options{EastAsianWidth: cond.EastAsianWidth} |
| 63 |
return WidthWithOptions(str, opts) |
| 64 |
} |
| 65 |
|
| 66 |
// Filter compiles and returns a regular expression for matching ANSI escape sequences, |
| 67 |
// including CSI (Control Sequence Introducer) and OSC (Operating System Command) sequences. |
| 68 |
// The returned regex can be used to strip ANSI codes from strings. |
| 69 |
func Filter() *regexp.Regexp { |
| 70 |
regESC := "\x1b" // ASCII escape character |
| 71 |
regBEL := "\x07" // ASCII bell character |
| 72 |
|
| 73 |
// ANSI string terminator: either ESC+\ or BEL |
| 74 |
regST := "(" + regexp.QuoteMeta(regESC+"\\") + "|" + regexp.QuoteMeta(regBEL) + ")" |
| 75 |
// Control Sequence Introducer (CSI): ESC[ followed by parameters and a final byte |
| 76 |
regCSI := regexp.QuoteMeta(regESC+"[") + "[\x30-\x3f]*[\x20-\x2f]*[\x40-\x7e]" |
| 77 |
// Operating System Command (OSC): ESC] followed by arbitrary content until a terminator |
| 78 |
regOSC := regexp.QuoteMeta(regESC+"]") + ".*?" + regST |
| 79 |
|
| 80 |
// Combine CSI and OSC patterns into a single regex |
| 81 |
return regexp.MustCompile("(" + regCSI + "|" + regOSC + ")") |
| 82 |
} |
| 83 |
|
| 84 |
// GetCacheStats returns current cache statistics |
| 85 |
func GetCacheStats() (size, capacity int, hitRate float64) { |
| 86 |
mu.Lock() |
| 87 |
defer mu.Unlock() |
| 88 |
|
| 89 |
if widthCache == nil { |
| 90 |
return 0, 0, 0 |
| 91 |
} |
| 92 |
return widthCache.Len(), widthCache.Cap(), widthCache.HitRate() |
| 93 |
} |
| 94 |
|
| 95 |
// IsEastAsian returns the current East Asian width setting. |
| 96 |
// This function is thread-safe. |
| 97 |
// |
| 98 |
// Example: |
| 99 |
// |
| 100 |
// if twdw.IsEastAsian() { |
| 101 |
// // Handle East Asian width characters |
| 102 |
// } |
| 103 |
func IsEastAsian() bool { |
| 104 |
mu.Lock() |
| 105 |
defer mu.Unlock() |
| 106 |
return globalOptions.EastAsianWidth |
| 107 |
} |
| 108 |
|
| 109 |
// SetCondition sets the global East Asian width setting based on a runewidth.Condition. |
| 110 |
// Deprecated: use SetOptions with the new twwidth.Options struct instead. |
| 111 |
// This function is kept for backward compatibility. |
| 112 |
func SetCondition(cond *runewidth.Condition) { |
| 113 |
mu.Lock() |
| 114 |
defer mu.Unlock() |
| 115 |
newEastAsianWidth := cond.EastAsianWidth |
| 116 |
if globalOptions.EastAsianWidth != newEastAsianWidth { |
| 117 |
globalOptions.EastAsianWidth = newEastAsianWidth |
| 118 |
widthCache.Purge() |
| 119 |
} |
| 120 |
} |
| 121 |
|
| 122 |
// SetEastAsian enables or disables East Asian width handling globally. |
| 123 |
// This function is thread-safe. |
| 124 |
// |
| 125 |
// Example: |
| 126 |
// |
| 127 |
// twdw.SetEastAsian(true) // Enable East Asian width handling |
| 128 |
func SetEastAsian(enable bool) { |
| 129 |
SetOptions(Options{EastAsianWidth: enable}) |
| 130 |
} |
| 131 |
|
| 132 |
// SetForceNarrow to preserve the new flag, or create a new setter |
| 133 |
func SetForceNarrow(enable bool) { |
| 134 |
mu.Lock() |
| 135 |
defer mu.Unlock() |
| 136 |
globalOptions.ForceNarrowBorders = enable |
| 137 |
widthCache.Purge() // Clear cache because widths might change |
| 138 |
} |
| 139 |
|
| 140 |
// SetOptions sets the global options for width calculation. |
| 141 |
// This function is thread-safe. |
| 142 |
func SetOptions(opts Options) { |
| 143 |
mu.Lock() |
| 144 |
defer mu.Unlock() |
| 145 |
if globalOptions.EastAsianWidth != opts.EastAsianWidth || globalOptions.ForceNarrowBorders != opts.ForceNarrowBorders { |
| 146 |
globalOptions = opts |
| 147 |
widthCache.Purge() |
| 148 |
} |
| 149 |
} |
| 150 |
|
| 151 |
// Truncate shortens a string to fit within a specified visual width, optionally |
| 152 |
// appending a suffix (e.g., "..."). It preserves ANSI escape sequences and adds |
| 153 |
// a reset sequence (\x1b[0m) if needed to prevent formatting bleed. The function |
| 154 |
// respects the global East Asian width setting and is thread-safe. |
| 155 |
// |
| 156 |
// If maxWidth is negative, an empty string is returned. If maxWidth is zero and |
| 157 |
// a suffix is provided, the suffix is returned. If the string's visual width is |
| 158 |
// less than or equal to maxWidth, the string (and suffix, if provided and fits) |
| 159 |
// is returned unchanged. |
| 160 |
// |
| 161 |
// Example: |
| 162 |
// |
| 163 |
// s := twdw.Truncate("Hello\x1b[31mWorld", 5, "...") // Returns "Hello..." |
| 164 |
// s = twdw.Truncate("Hello", 10) // Returns "Hello" |
| 165 |
func Truncate(s string, maxWidth int, suffix ...string) string { |
| 166 |
if maxWidth < 0 { |
| 167 |
return "" |
| 168 |
} |
| 169 |
|
| 170 |
suffixStr := strings.Join(suffix, "") |
| 171 |
sDisplayWidth := Width(s) // Uses global cached Width |
| 172 |
suffixDisplayWidth := Width(suffixStr) // Uses global cached Width |
| 173 |
|
| 174 |
// Case 1: Original string is visually empty. |
| 175 |
if sDisplayWidth == 0 { |
| 176 |
// If suffix is provided and fits within maxWidth (or if maxWidth is generous) |
| 177 |
if len(suffixStr) > 0 && suffixDisplayWidth <= maxWidth { |
| 178 |
return suffixStr |
| 179 |
} |
| 180 |
// If s has ANSI codes (len(s)>0) but maxWidth is 0, can't display them. |
| 181 |
if maxWidth == 0 && len(s) > 0 { |
| 182 |
return "" |
| 183 |
} |
| 184 |
return s // Returns "" or original ANSI codes |
| 185 |
} |
| 186 |
|
| 187 |
// Case 2: maxWidth is 0, but string has content. Cannot display anything. |
| 188 |
if maxWidth == 0 { |
| 189 |
return "" |
| 190 |
} |
| 191 |
|
| 192 |
// Case 3: String fits completely or fits with suffix. |
| 193 |
// Here, maxWidth is the total budget for the line. |
| 194 |
if sDisplayWidth <= maxWidth { |
| 195 |
// If the string contains ANSI, we must ensure it ends with a reset |
| 196 |
// to prevent bleeding, even if we don't truncate. |
| 197 |
safeS := s |
| 198 |
if strings.Contains(s, "\x1b") && !strings.HasSuffix(s, "\x1b[0m") { |
| 199 |
safeS += "\x1b[0m" |
| 200 |
} |
| 201 |
|
| 202 |
if len(suffixStr) == 0 { // No suffix. |
| 203 |
return safeS |
| 204 |
} |
| 205 |
// Suffix is provided. Check if s + suffix fits. |
| 206 |
if sDisplayWidth+suffixDisplayWidth <= maxWidth { |
| 207 |
return safeS + suffixStr |
| 208 |
} |
| 209 |
// s fits, but s + suffix is too long. Return s (with reset if needed). |
| 210 |
return safeS |
| 211 |
} |
| 212 |
|
| 213 |
// Case 4: String needs truncation (sDisplayWidth > maxWidth). |
| 214 |
// maxWidth is the total budget for the final string (content + suffix). |
| 215 |
mu.Lock() |
| 216 |
currentOpts := globalOptions |
| 217 |
mu.Unlock() |
| 218 |
|
| 219 |
// Special case for EastAsianDetect true: if only suffix fits, return suffix. |
| 220 |
// This was derived from previous test behavior. |
| 221 |
if len(suffixStr) > 0 && currentOpts.EastAsianWidth { |
| 222 |
provisionalContentWidth := maxWidth - suffixDisplayWidth |
| 223 |
if provisionalContentWidth == 0 { // Exactly enough space for suffix only |
| 224 |
return suffixStr |
| 225 |
} |
| 226 |
} |
| 227 |
|
| 228 |
// Calculate the budget for the content part, reserving space for the suffix. |
| 229 |
targetContentForIteration := maxWidth |
| 230 |
if len(suffixStr) > 0 { |
| 231 |
targetContentForIteration -= suffixDisplayWidth |
| 232 |
} |
| 233 |
|
| 234 |
// If content budget is negative, means not even suffix fits (or no suffix and no space). |
| 235 |
// However, if only suffix fits, it should be handled. |
| 236 |
if targetContentForIteration < 0 { |
| 237 |
// Can we still fit just the suffix? |
| 238 |
if len(suffixStr) > 0 && suffixDisplayWidth <= maxWidth { |
| 239 |
if strings.Contains(s, "\x1b[") { |
| 240 |
return "\x1b[0m" + suffixStr |
| 241 |
} |
| 242 |
return suffixStr |
| 243 |
} |
| 244 |
return "" // Cannot fit anything. |
| 245 |
} |
| 246 |
|
| 247 |
var contentBuf bytes.Buffer |
| 248 |
var currentContentDisplayWidth int |
| 249 |
var ansiSeqBuf bytes.Buffer |
| 250 |
inAnsiSequence := false |
| 251 |
ansiWrittenToContent := false |
| 252 |
|
| 253 |
for _, r := range s { |
| 254 |
if r == '\x1b' { |
| 255 |
inAnsiSequence = true |
| 256 |
ansiSeqBuf.Reset() |
| 257 |
ansiSeqBuf.WriteRune(r) |
| 258 |
} else if inAnsiSequence { |
| 259 |
ansiSeqBuf.WriteRune(r) |
| 260 |
seqBytes := ansiSeqBuf.Bytes() |
| 261 |
seqLen := len(seqBytes) |
| 262 |
terminated := false |
| 263 |
if seqLen >= 2 { |
| 264 |
introducer := seqBytes[1] |
| 265 |
switch introducer { |
| 266 |
case '[': |
| 267 |
if seqLen >= 3 && r >= 0x40 && r <= 0x7E { |
| 268 |
terminated = true |
| 269 |
} |
| 270 |
case ']': |
| 271 |
if r == '\x07' { |
| 272 |
terminated = true |
| 273 |
} else if seqLen > 1 && seqBytes[seqLen-2] == '\x1b' && r == '\\' { // Check for ST: \x1b\ |
| 274 |
terminated = true |
| 275 |
} |
| 276 |
} |
| 277 |
} |
| 278 |
if terminated { |
| 279 |
inAnsiSequence = false |
| 280 |
contentBuf.Write(ansiSeqBuf.Bytes()) |
| 281 |
ansiWrittenToContent = true |
| 282 |
ansiSeqBuf.Reset() |
| 283 |
} |
| 284 |
} else { // Normal character |
| 285 |
runeDisplayWidth := calculateRunewidth(r, currentOpts) |
| 286 |
if targetContentForIteration == 0 { // No budget for content at all |
| 287 |
break |
| 288 |
} |
| 289 |
if currentContentDisplayWidth+runeDisplayWidth > targetContentForIteration { |
| 290 |
break |
| 291 |
} |
| 292 |
contentBuf.WriteRune(r) |
| 293 |
currentContentDisplayWidth += runeDisplayWidth |
| 294 |
} |
| 295 |
} |
| 296 |
|
| 297 |
result := contentBuf.String() |
| 298 |
|
| 299 |
// Determine if we need to append a reset sequence to prevent color bleeding. |
| 300 |
// This is needed if we wrote any ANSI codes or if the input had active codes |
| 301 |
// that we might have cut off or left open. |
| 302 |
needsReset := false |
| 303 |
if (ansiWrittenToContent || (inAnsiSequence && strings.Contains(s, "\x1b["))) && (currentContentDisplayWidth > 0 || ansiWrittenToContent) { |
| 304 |
if !strings.HasSuffix(result, "\x1b[0m") { |
| 305 |
needsReset = true |
| 306 |
} |
| 307 |
} else if currentContentDisplayWidth > 0 && strings.Contains(result, "\x1b[") && !strings.HasSuffix(result, "\x1b[0m") && strings.Contains(s, "\x1b[") { |
| 308 |
needsReset = true |
| 309 |
} |
| 310 |
|
| 311 |
if needsReset { |
| 312 |
result += "\x1b[0m" |
| 313 |
} |
| 314 |
|
| 315 |
// Suffix is added if provided. |
| 316 |
if len(suffixStr) > 0 { |
| 317 |
result += suffixStr |
| 318 |
} |
| 319 |
return result |
| 320 |
} |
| 321 |
|
| 322 |
// Width calculates the visual width of a string using the global cache for performance. |
| 323 |
// It excludes ANSI escape sequences and accounts for the global East Asian width setting. |
| 324 |
// This function is thread-safe. |
| 325 |
// |
| 326 |
// Example: |
| 327 |
// |
| 328 |
// width := twdw.Width("Hello\x1b[31mWorld") // Returns 10 |
| 329 |
func Width(str string) int { |
| 330 |
// Fast path ASCII (Optimization) |
| 331 |
if len(str) == 1 && str[0] < 0x80 { |
| 332 |
// Treat tab as special case even in fast path |
| 333 |
if IsTab(rune(str[0])) { |
| 334 |
return TabWidth() |
| 335 |
} |
| 336 |
// Only printable ASCII has a guaranteed width of 1; control |
| 337 |
// characters (width 0) fall through to the accurate path below. |
| 338 |
if str[0] >= 0x20 && str[0] != 0x7f { |
| 339 |
return 1 |
| 340 |
} |
| 341 |
} |
| 342 |
|
| 343 |
mu.Lock() |
| 344 |
currentOpts := globalOptions |
| 345 |
mu.Unlock() |
| 346 |
|
| 347 |
key := cacheKey{ |
| 348 |
eastAsian: currentOpts.EastAsianWidth, |
| 349 |
str: str, |
| 350 |
} |
| 351 |
|
| 352 |
// Check Cache (Optimization) |
| 353 |
if w, found := widthCache.Get(key); found { |
| 354 |
return w |
| 355 |
} |
| 356 |
|
| 357 |
//stripped := ansi.ReplaceAllLiteralString(str, "") |
| 358 |
calculatedWidth := 0 |
| 359 |
|
| 360 |
for _, r := range strip(str) { |
| 361 |
calculatedWidth += calculateRunewidth(r, currentOpts) |
| 362 |
} |
| 363 |
|
| 364 |
// Store in Cache |
| 365 |
widthCache.Add(key, calculatedWidth) |
| 366 |
return calculatedWidth |
| 367 |
} |
| 368 |
|
| 369 |
// WidthNoCache calculates the visual width of a string without using the global cache. |
| 370 |
// |
| 371 |
// Example: |
| 372 |
// |
| 373 |
// width := twdw.WidthNoCache("Hello\x1b[31mWorld") // Returns 10 |
| 374 |
func WidthNoCache(str string) int { |
| 375 |
// This function's behavior is equivalent to a one-shot calculation |
| 376 |
// using the current global options. The WidthWithOptions function |
| 377 |
// does not interact with the cache, thus fulfilling the requirement. |
| 378 |
mu.Lock() |
| 379 |
opts := globalOptions |
| 380 |
mu.Unlock() |
| 381 |
return WidthWithOptions(str, opts) |
| 382 |
} |
| 383 |
|
| 384 |
// WidthWithOptions calculates the visual width of a string with specific options, |
| 385 |
// bypassing the global settings and cache. This is useful for one-shot calculations |
| 386 |
// where global state is not desired. |
| 387 |
func WidthWithOptions(str string, opts Options) int { |
| 388 |
// stripped := ansi.ReplaceAllLiteralString(str, "") |
| 389 |
calculatedWidth := 0 |
| 390 |
for _, r := range strip(str) { |
| 391 |
calculatedWidth += calculateRunewidth(r, opts) |
| 392 |
} |
| 393 |
return calculatedWidth |
| 394 |
} |
| 395 |
|
| 396 |
// calculateRunewidth calculates the width of a single rune based on the provided options. |
| 397 |
// It applies narrow overrides for box drawing characters if configured and handles Tabs. |
| 398 |
func calculateRunewidth(r rune, opts Options) int { |
| 399 |
if opts.ForceNarrowBorders && isBoxDrawingChar(r) { |
| 400 |
return 1 |
| 401 |
} |
| 402 |
|
| 403 |
// Explicitly handle Tabinal to ensure tables have enough space |
| 404 |
// when TrimTab is Off. |
| 405 |
if IsTab(r) { |
| 406 |
return TabWidth() |
| 407 |
} |
| 408 |
|
| 409 |
dwOpts := displaywidth.Options{EastAsianWidth: opts.EastAsianWidth} |
| 410 |
return dwOpts.Rune(r) |
| 411 |
} |
| 412 |
|
| 413 |
// isBoxDrawingChar checks if a rune is within the Unicode Box Drawing range. |
| 414 |
func isBoxDrawingChar(r rune) bool { |
| 415 |
return r >= 0x2500 && r <= 0x257F |
| 416 |
} |
| 417 |
|
| 418 |
func strip(s string) string { |
| 419 |
if strings.IndexByte(s, '\x1b') == -1 { |
| 420 |
return s |
| 421 |
} |
| 422 |
return ansi.ReplaceAllLiteralString(s, "") |
| 423 |
} |