normalizeIndent function
Normalizes a indent, removing the common/global indent of the code.
Useful to remove indent caused due declaration inside a multiline String with it's own indentation.
Implementation
String normalizeIndent(String text) {
if (text.isEmpty) return text;
var lines = text.split(RegExp(r'[\r\n]'));
if (lines.length <= 2) return text;
// ignore: omit_local_variable_types
Map<String, int> indentCount = {};
for (var line in lines) {
var indent = line.split(RegExp(r'\S'))[0];
var count = indentCount[indent] ?? 0;
indentCount[indent] = count + 1;
}
if (indentCount.isEmpty) return text;
var identList = List.from(indentCount.keys)
..sort((a, b) => indentCount[b]!.compareTo(indentCount[a]!));
String mainIdent = identList[0];
if (mainIdent.isEmpty) return text;
for (var i = 0; i < lines.length; i++) {
var line = lines[i];
if (line.startsWith(mainIdent)) {
var line2 = line.substring(mainIdent.length);
lines[i] = line2;
}
}
var textNorm = lines.join('\n');
return textNorm;
}