use crate::parser::LangId;
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum IndentStyle {
Tabs,
Spaces(u8),
}
impl IndentStyle {
pub fn as_str(&self) -> &'static str {
match self {
IndentStyle::Tabs => "\t",
IndentStyle::Spaces(n) => {
static SPACES: [u8; u8::MAX as usize] = [b' '; u8::MAX as usize];
std::str::from_utf8(&SPACES[..*n as usize]).expect("ASCII spaces")
}
}
}
pub fn default_for(lang: LangId) -> Self {
match lang {
LangId::Python => IndentStyle::Spaces(4),
LangId::TypeScript
| LangId::Tsx
| LangId::JavaScript
| LangId::Vue
| LangId::Json
| LangId::Scala
| LangId::Ruby
| LangId::Lua
| LangId::Scss
| LangId::Yaml
| LangId::Toml => IndentStyle::Spaces(2),
LangId::Rust => IndentStyle::Spaces(4),
LangId::Go => IndentStyle::Tabs,
LangId::C
| LangId::Cpp
| LangId::Cuda
| LangId::Metal
| LangId::Zig
| LangId::CSharp
| LangId::Bash => IndentStyle::Spaces(4),
LangId::Solidity
| LangId::ObjC
| LangId::Java
| LangId::Kotlin
| LangId::Swift
| LangId::Php
| LangId::Perl
| LangId::Groovy
| LangId::Luau => IndentStyle::Spaces(4),
LangId::Html => IndentStyle::Spaces(2),
LangId::Markdown => IndentStyle::Spaces(4),
LangId::Pascal | LangId::R => IndentStyle::Spaces(2),
}
}
}
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];
for line in source.lines() {
if line.trim().is_empty() || line.trim_start().starts_with('*') {
continue;
}
let first = line.as_bytes()[0];
if first == b'\t' {
tab_count += 1;
} else if first == b' ' {
space_count += 1;
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);
}
if tab_count > total / 2 {
return IndentStyle::Tabs;
}
if space_count > total / 2 {
let width = determine_space_width(&indent_widths);
return IndentStyle::Spaces(width);
}
IndentStyle::default_for(lang)
}
test_support_visibility! {
fn determine_space_width(widths: &[u32; 9]) -> u8 {
let smallest = (1..=8usize).find(|&i| widths[i] > 0);
let smallest = match smallest {
Some(s) => s,
None => return 4,
};
let all_multiples = (1..=8).all(|i| widths[i] == 0 || i % smallest == 0);
if all_multiples && smallest >= 2 {
return smallest as u8;
}
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 > non_matching {
return candidate;
}
}
smallest as u8
}
}
pub fn source_line_ending(source: &str) -> &'static str {
let lf = source.bytes().filter(|byte| *byte == b'\n').count();
let crlf = source
.as_bytes()
.windows(2)
.filter(|pair| *pair == b"\r\n")
.count();
if crlf > 0 && crlf >= lf - crlf {
"\r\n"
} else {
"\n"
}
}