From d75166c01a20122706c8ffb0dad5d009a1631b85 Mon Sep 17 00:00:00 2001 From: DualFroz Date: Wed, 7 Oct 2026 20:08:48 +0200 Subject: [PATCH] twwidth: purge width cache in SetTabWidth the width cache key does not include the tab width, so after SetTabWidth, Width returned stale results for strings containing tabs. purge the cache like SetForceNarrow does, and add a test comparing Width with WidthNoCache after changing the tab width. --- pkg/twwidth/tab.go | 3 +++ pkg/twwidth/tab_test.go | 13 +++++++++++++ 2 files changed, 16 insertions(+) diff --git a/pkg/twwidth/tab.go b/pkg/twwidth/tab.go index f309c0b..4359548 100644 --- a/pkg/twwidth/tab.go +++ b/pkg/twwidth/tab.go @@ -280,6 +280,9 @@ func TabWidth() int { // SetTabWidth sets the global tab width. func SetTabWidth(w int) { TabInstance().SetWidth(w) + mu.Lock() + defer mu.Unlock() + widthCache.Purge() // Clear cache because widths might change } func envInt(k string) int { diff --git a/pkg/twwidth/tab_test.go b/pkg/twwidth/tab_test.go index b02bb57..36b821f 100644 --- a/pkg/twwidth/tab_test.go +++ b/pkg/twwidth/tab_test.go @@ -38,3 +38,16 @@ func TestTabinalSetWidth(t *testing.T) { } } } + +func TestSetTabWidthPurgesWidthCache(t *testing.T) { + orig := twwidth.TabWidth() + t.Cleanup(func() { twwidth.SetTabWidth(orig) }) + + const s = "a\tb" + for _, width := range []int{2, 4, 6} { + twwidth.SetTabWidth(width) + if got, want := twwidth.Width(s), twwidth.WidthNoCache(s); got != want { + t.Errorf("Width(%q) after SetTabWidth(%d) = %d, want %d", s, width, got, want) + } + } +}