detectIndentation method

int detectIndentation()

Implementation

int detectIndentation() {
  final lines = text.split("\n");
  final diffCount = <int, int>{};
  int previousIndent = 0;

  for (final line in lines) {
    if (line.trim().isEmpty) continue;

    final match = RegExp(r"^( +)\S").firstMatch(line);
    final currentIndent = match?.group(1)?.length ?? 0;

    final diff = (currentIndent - previousIndent).abs();
    if (diff >= 1 && diff <= 32) {
      diffCount[diff] = (diffCount[diff] ?? 0) + 1;
    }

    previousIndent = currentIndent;
  }

  if (diffCount.isEmpty) return tabSize > 0 ? tabSize : 2;

  int bestIndent = tabSize;
  int maxOccurrences = 0;

  diffCount.forEach((indent, count) {
    if (count > maxOccurrences) {
      maxOccurrences = count;
      bestIndent = indent;
    }
  });

  return bestIndent;
}