Debian Codegraph @

pkg/twwidth/tab.go

raw
1 package twwidth
2
3 import (
4 "bufio"
5 "os"
6 "path/filepath"
7 "strconv"
8 "strings"
9 "sync"
10 )
11
12 type Tab rune
13
14 const (
15 TabWidthDefault = 8
16 TabString Tab = '\t'
17 )
18
19 // IsTab returns true if t equals the default tab.
20 func (t Tab) IsTab() bool {
21 return t == TabString
22 }
23
24 func (t Tab) Byte() byte {
25 return byte(t)
26 }
27
28 func (t Tab) Rune() rune {
29 return rune(t)
30 }
31
32 func (t Tab) String() string {
33 return string(t)
34 }
35
36 // IsTab returns true if r is a tab rune.
37 func IsTab(r rune) bool {
38 return r == TabString.Rune()
39 }
40
41 type Tabinal struct {
42 once sync.Once
43 width int
44 mu sync.RWMutex
45 }
46
47 func (t *Tabinal) String() string {
48 return TabString.String()
49 }
50
51 // Size returns the current tab width, default if unset.
52 func (t *Tabinal) Size() int {
53 t.once.Do(t.init)
54
55 t.mu.RLock()
56 w := t.width
57 t.mu.RUnlock()
58
59 if w <= 0 {
60 return TabWidthDefault
61 }
62 return w
63 }
64
65 // SetWidth sets the tab width if valid (1–32).
66 func (t *Tabinal) SetWidth(w int) {
67 if w <= 0 || w > 32 {
68 return
69 }
70 t.mu.Lock()
71 t.width = w
72 t.mu.Unlock()
73 }
74
75 func (t *Tabinal) init() {
76 w := t.detect()
77 t.mu.Lock()
78 t.width = w
79 t.mu.Unlock()
80 }
81
82 // detect determines tab width using env, editorconfig, project, or term.
83 func (t *Tabinal) detect() int {
84 if w := envInt("TABWIDTH"); w > 0 {
85 return clamp(w)
86 }
87 if w := envInt("TS"); w > 0 {
88 return clamp(w)
89 }
90 if w := envInt("VIM_TABSTOP"); w > 0 {
91 return clamp(w)
92 }
93 if w := editorConfigTabWidth(); w > 0 {
94 return w
95 }
96 if w := projectHeuristic(); w > 0 {
97 return w
98 }
99 if w := termHeuristic(); w > 0 {
100 return w
101 }
102 return 0
103 }
104
105 func editorConfigTabWidth() int {
106 dir, err := os.Getwd()
107 if err != nil {
108 return 0
109 }
110
111 for dir != "" && dir != "/" && dir != "." {
112 path := filepath.Join(dir, ".editorconfig")
113 if w := parseEditorConfig(path); w > 0 {
114 return clamp(w)
115 }
116 parent := filepath.Dir(dir)
117 if parent == dir {
118 break
119 }
120 dir = parent
121 }
122 return 0
123 }
124
125 // parseEditorConfig reads tab_width or indent_size from a file.
126 func parseEditorConfig(path string) int {
127 f, err := os.Open(path)
128 if err != nil {
129 return 0
130 }
131 defer f.Close()
132
133 scanner := bufio.NewScanner(f)
134 inMatch := false
135 globalWidth := 0
136
137 for scanner.Scan() {
138 line := strings.TrimSpace(scanner.Text())
139 if line == "" || strings.HasPrefix(line, "#") || strings.HasPrefix(line, ";") {
140 continue
141 }
142
143 if strings.HasPrefix(line, "[") && strings.HasSuffix(line, "]") {
144 pattern := line[1 : len(line)-1]
145 inMatch = pattern == "*"
146
147 knownExts := []string{".go", ".py", ".js", ".ts", ".java", ".rs"}
148 for _, ext := range knownExts {
149 if strings.Contains(pattern, ext) {
150 inMatch = true
151 break
152 }
153 }
154 continue
155 }
156
157 if !inMatch && globalWidth == 0 {
158 continue
159 }
160
161 parts := strings.SplitN(line, "=", 2)
162 if len(parts) != 2 {
163 continue
164 }
165 key := strings.TrimSpace(parts[0])
166 val := strings.TrimSpace(parts[1])
167
168 switch key {
169 case "tab_width":
170 if w, err := strconv.Atoi(val); err == nil && w > 0 {
171 if inMatch {
172 return clamp(w)
173 }
174 if globalWidth == 0 {
175 globalWidth = w
176 }
177 }
178 case "indent_size":
179 if val == "tab" {
180 continue
181 }
182 if w, err := strconv.Atoi(val); err == nil && w > 0 {
183 if inMatch {
184 return clamp(w)
185 }
186 if globalWidth == 0 {
187 globalWidth = w
188 }
189 }
190 }
191 }
192
193 return globalWidth
194 }
195
196 // projectHeuristic returns 4 for known project types.
197 func projectHeuristic() int {
198 dir, err := os.Getwd()
199 if err != nil {
200 return 0
201 }
202
203 indicators := []string{
204 "go.mod", "go.sum",
205 "package.json", "package-lock.json", "yarn.lock", "pnpm-lock.yaml",
206 "setup.py", "pyproject.toml", "requirements.txt", "Pipfile",
207 "pom.xml", "build.gradle", "build.gradle.kts",
208 "Cargo.toml",
209 "composer.json",
210 }
211
212 for _, indicator := range indicators {
213 if _, err := os.Stat(filepath.Join(dir, indicator)); err == nil {
214 return 4
215 }
216 }
217
218 patterns := []string{"*.go", "*.py", "*.js", "*.ts", "*.java", "*.rs"}
219 for _, pattern := range patterns {
220 if matches, _ := filepath.Glob(filepath.Join(dir, pattern)); len(matches) > 0 {
221 return 4
222 }
223 }
224
225 return 0
226 }
227
228 // termHeuristic returns a default width based on the TERM variable.
229 func termHeuristic() int {
230 termEnv := strings.ToLower(os.Getenv("TERM"))
231 if termEnv == "" {
232 return 0
233 }
234
235 if strings.Contains(termEnv, "vt52") {
236 return 2
237 }
238
239 if strings.Contains(termEnv, "xterm") ||
240 strings.Contains(termEnv, "screen") ||
241 strings.Contains(termEnv, "tmux") ||
242 strings.Contains(termEnv, "linux") ||
243 strings.Contains(termEnv, "ansi") ||
244 strings.Contains(termEnv, "rxvt") {
245 return TabWidthDefault
246 }
247
248 return 0
249 }
250
251 func clamp(w int) int {
252 if w <= 0 {
253 return 0
254 }
255 if w > 32 {
256 return 32
257 }
258 return w
259 }
260
261 var (
262 globalTab *Tabinal
263 globalTabOnce sync.Once
264 )
265
266 // TabInstance returns the singleton Tabinal.
267 func TabInstance() *Tabinal {
268 globalTabOnce.Do(func() {
269 globalTab = &Tabinal{}
270 })
271 return globalTab
272 }
273
274 // TabWidth returns the detected global tab width.
275 func TabWidth() int {
276 return TabInstance().Size()
277 }
278
279 // SetTabWidth sets the global tab width.
280 func SetTabWidth(w int) {
281 TabInstance().SetWidth(w)
282 }
283
284 func envInt(k string) int {
285 v := os.Getenv(k)
286 w, _ := strconv.Atoi(v)
287 return w
288 }