LineInfo.fromContent constructor

LineInfo.fromContent(
  1. String content
)

Initialize a newly created set of line information corresponding to the given file content. Lines end with \r, \n or \r\n.

Implementation

factory LineInfo.fromContent(String content) {
  const slashN = 0x0A;
  const slashR = 0x0D;

  var lineStarts = <int>[0];
  var length = content.length;
  for (var i = 0; i < length; i++) {
    var unit = content.codeUnitAt(i);
    // Special-case \r\n.
    if (unit == slashR) {
      // Peek ahead to detect a following \n.
      if (i + 1 < length && content.codeUnitAt(i + 1) == slashN) {
        // Line start will get registered at next index at the \n.
      } else {
        lineStarts.add(i + 1);
      }
    }
    // \n
    if (unit == slashN) {
      lineStarts.add(i + 1);
    }
  }

  return LineInfo(lineStarts);
}