wordWrap function

String wordWrap(
  1. String text, {
  2. int width = 40,
})

Wrap a string using a word wrap strategy.

Implementation

String wordWrap(String text, {int width = 40}) {
  // Split into lines.

  var lines = text.split('\n');

  // Trim white space.

  lines = lines.map((str) => str.trim()).toList();

  // Split into paragraphs since each paragraph is going to be word wrapped.

  var para = [];
  var currentPara = '';

  for (final line in lines) {
    if (line.isEmpty) {
      if (currentPara.isNotEmpty) {
        para.add(currentPara.trim());
        currentPara = '';
      }
    } else {
      if (currentPara.isNotEmpty) {
        currentPara += ' ';
      }
      currentPara += line.trim();
    }
  }

  // Add the last paragraph if there's any left after the loop

  if (currentPara.isNotEmpty) {
    para.add(currentPara.trim());
  }

  final pattern = RegExp('.{1,$width}(\\s+|\$)');

  //  para = para.map((str) => actualWordWrap(str, width)).toList();

  para = para
      .map(
        (str) =>
            str.replaceAllMapped(pattern, (match) => '${match.group(0)!}\n'),
      )
      .toList();

  // Combine the paragraphs into one string with empty lines between
  // them. 20240811 gjw added trim() to remove any white space at the end of the
  // string. Will this affect anythig else?

  final result = para.join('\n\n').trim();

  // text = result
  //     .replaceAllMapped(pattern, (match) => '${match.group(0)!}\n')
  //     .trim();

  // text = text.replaceAll(RegExp(r'^ +'), '');

  return result;
}