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
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
//! Shared indentation detection utility (D042).
//!
//! Analyzes source file content to determine the indentation style (tabs vs
//! spaces, width) used. Falls back to language-specific defaults when the
//! file has insufficient indented lines or mixed signals.
use crate::parser::LangId;
/// Detected indentation style.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum IndentStyle {
Tabs,
Spaces(u8),
}
impl IndentStyle {
/// Returns the whitespace string for one level of this indent.
pub fn as_str(&self) -> &'static str {
match self {
IndentStyle::Tabs => "\t",
IndentStyle::Spaces(2) => " ",
IndentStyle::Spaces(4) => " ",
IndentStyle::Spaces(8) => " ",
IndentStyle::Spaces(n) => {
// For uncommon widths, leak a static string. In practice
// this only fires for exotic indent widths (1, 3, 5, 6, 7).
let s: String = " ".repeat(*n as usize);
Box::leak(s.into_boxed_str())
}
}
}
/// Language-specific default when detection has low confidence.
pub fn default_for(lang: LangId) -> Self {
match lang {
LangId::Python => IndentStyle::Spaces(4),
LangId::TypeScript | LangId::Tsx | LangId::JavaScript | LangId::Vue => {
IndentStyle::Spaces(2)
}
LangId::Rust => IndentStyle::Spaces(4),
LangId::Go => IndentStyle::Tabs,
LangId::C | LangId::Cpp | LangId::Zig | LangId::CSharp | LangId::Bash => {
IndentStyle::Spaces(4)
}
LangId::Solidity => IndentStyle::Spaces(4),
LangId::Html => IndentStyle::Spaces(2),
LangId::Markdown => IndentStyle::Spaces(4),
}
}
}
/// Detect the indentation style of a source file.
///
/// Examines indented lines (those starting with whitespace) and determines
/// whether tabs or spaces dominate. For spaces, determines the most common
/// indent width by looking at the smallest indent unit.
///
/// Returns detected style if >50% of indented lines agree, otherwise falls
/// back to the language default.
pub fn detect_indent(source: &str, lang: LangId) -> IndentStyle {
let mut tab_count: u32 = 0;
let mut space_count: u32 = 0;
let mut indent_widths: [u32; 9] = [0; 9]; // index 1..8
for line in source.lines() {
if line.is_empty() {
continue;
}
let first = line.as_bytes()[0];
if first == b'\t' {
tab_count += 1;
} else if first == b' ' {
space_count += 1;
// Count leading spaces
let leading = line.len() - line.trim_start_matches(' ').len();
if leading > 0 && leading <= 8 {
indent_widths[leading] += 1;
}
}
}
let total = tab_count + space_count;
if total == 0 {
return IndentStyle::default_for(lang);
}
// Tabs win if >50% of indented lines use tabs
if tab_count > total / 2 {
return IndentStyle::Tabs;
}
// Spaces win if >50% of indented lines use spaces
if space_count > total / 2 {
// Determine the most likely indent unit width.
// The unit is the GCD of observed indent widths, or equivalently,
// the smallest width that has significant usage.
let width = determine_space_width(&indent_widths);
return IndentStyle::Spaces(width);
}
// Mixed / no clear winner — fall back
IndentStyle::default_for(lang)
}
/// Determine the most likely space indent width from observed leading-space counts.
///
/// Strategy: find the smallest observed indent width that forms a consistent
/// pattern (all other widths are multiples of it). Prefer the smallest actual
/// indent seen, not just the GCD.
fn determine_space_width(widths: &[u32; 9]) -> u8 {
// Find the smallest observed indent width
let smallest = (1..=8usize).find(|&i| widths[i] > 0);
let smallest = match smallest {
Some(s) => s,
None => return 4,
};
// Check if all observed widths are multiples of this smallest
let all_multiples = (1..=8).all(|i| widths[i] == 0 || i % smallest == 0);
if all_multiples && smallest >= 2 {
return smallest as u8;
}
// If smallest is 1 or doesn't divide evenly, try common widths
for &candidate in &[4u8, 2, 8] {
let c = candidate as usize;
let mut matching: u32 = 0;
let mut non_matching: u32 = 0;
for i in 1..=8 {
if widths[i] > 0 {
if i % c == 0 {
matching += widths[i];
} else {
non_matching += widths[i];
}
}
}
if matching > 0 && non_matching == 0 {
return candidate;
}
}
smallest as u8
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn detect_indent_tabs() {
let source = "fn main() {\n\tlet x = 1;\n\tlet y = 2;\n}\n";
assert_eq!(detect_indent(source, LangId::Rust), IndentStyle::Tabs);
}
#[test]
fn detect_indent_two_spaces() {
let source = "class Foo {\n bar() {}\n baz() {}\n}\n";
assert_eq!(
detect_indent(source, LangId::TypeScript),
IndentStyle::Spaces(2)
);
}
#[test]
fn detect_indent_four_spaces() {
let source =
"class Foo:\n def bar(self):\n pass\n def baz(self):\n pass\n";
assert_eq!(
detect_indent(source, LangId::Python),
IndentStyle::Spaces(4)
);
}
#[test]
fn detect_indent_empty_source_uses_default() {
assert_eq!(detect_indent("", LangId::Python), IndentStyle::Spaces(4));
assert_eq!(
detect_indent("", LangId::TypeScript),
IndentStyle::Spaces(2)
);
assert_eq!(detect_indent("", LangId::Go), IndentStyle::Tabs);
}
#[test]
fn detect_indent_no_indented_lines_uses_default() {
let source = "x = 1\ny = 2\n";
assert_eq!(
detect_indent(source, LangId::Python),
IndentStyle::Spaces(4)
);
}
#[test]
fn indent_style_as_str() {
assert_eq!(IndentStyle::Tabs.as_str(), "\t");
assert_eq!(IndentStyle::Spaces(2).as_str(), " ");
assert_eq!(IndentStyle::Spaces(4).as_str(), " ");
}
#[test]
fn detect_indent_four_spaces_with_nested() {
// Lines indented at 4 and 8 should detect 4-space indent
let source = "impl Foo {\n fn bar() {\n let x = 1;\n }\n}\n";
assert_eq!(detect_indent(source, LangId::Rust), IndentStyle::Spaces(4));
}
}