formatNumberedLines function
Formats content like cat -n, starting at the 1-based offset.
Implementation
String formatNumberedLines(String content, {required int offset, required int limit}) {
final lines = content.split('\n');
if (lines.length > 1 && lines.last.isEmpty) {
lines.removeLast();
}
final start = offset - 1;
if (start >= lines.length) {
return '(The file has ${lines.length} lines; offset $offset is past the end.)';
}
final end = (start + limit).clamp(0, lines.length);
final width = '$end'.length;
final buffer = StringBuffer();
for (var index = start; index < end; index++) {
var line = lines[index];
if (line.length > _maxLineLength) {
line = '${line.substring(0, _maxLineLength)}... [line truncated]';
}
buffer.writeln('${'${index + 1}'.padLeft(width)}\t$line');
}
if (end < lines.length) {
buffer.writeln('\n(Showing lines ${start + 1}-$end of ${lines.length}. Use offset to read more.)');
}
return buffer.toString().trimRight();
}