-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathhelper.go
74 lines (61 loc) · 1.51 KB
/
helper.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
package gvcode
import (
"bufio"
"strings"
)
type TabStyle uint8
const (
Tabs TabStyle = iota
Spaces
)
// GuessIndentation guesses which kind of indentation the editor is
// using, returing the kind, if mixed indent is used, and the indent
// size in the case if spaces indentation.
func GuessIndentation(text string) (TabStyle, bool, int) {
scanner := bufio.NewScanner(strings.NewReader(text))
var tabs, spaces int
var spaceWidths = make(map[int]int)
indentScanner := func(batchSize int) bool {
for scanner.Scan() {
line := scanner.Text()
if strings.TrimSpace(line) == "" {
continue // Ignore empty lines
}
// Count tabs and spaces
if strings.HasPrefix(line, "\t") {
tabs++
} else if strings.HasPrefix(line, " ") {
// Count leading spaces
leading := len(line) - len(strings.TrimLeft(line, " "))
spaces++
spaceWidths[leading]++
}
// Stop early if we've analyzed enough lines
if spaces+tabs > batchSize {
return true
}
}
return false
}
for {
hasMore := indentScanner(100)
if (tabs + spaces<=5 || spaces == tabs) && hasMore {
continue
}
mixedIndent := tabs>0 && spaces>0
mainIndent := Tabs
if tabs > spaces {
mainIndent = Tabs
} else if spaces > tabs {
mainIndent = Spaces
}
// If there are spaces, find the most common space width
bestWidth, maxFreq := 4, 0
for width, freq := range spaceWidths {
if width > 0 && freq > maxFreq {
bestWidth, maxFreq = width, freq
}
}
return mainIndent, mixedIndent, bestWidth
}
}