commit method

NestedPrinter commit()

Applies all pending edits and returns a NestedPrinter containing the rewritten string and source map information. file.location is given to the underlying printer to indicate the name of the generated file that will contains the source map information.

Throws UnsupportedError if the edits were overlapping. If no edits were made, the printer simply contains the original string.

Implementation

NestedPrinter commit() {
  var printer = NestedPrinter();
  if (_edits.isEmpty) {
    return printer..add(original, location: _loc(0), isOriginal: true);
  }

  // Sort edits by start location.
  _edits.sort();

  var consumed = 0;
  for (var edit in _edits) {
    if (consumed > edit.begin) {
      var sb = StringBuffer();
      sb
        ..write(file?.location(edit.begin).toolString)
        ..write(': overlapping edits. Insert at offset ')
        ..write(edit.begin)
        ..write(' but have consumed ')
        ..write(consumed)
        ..write(' input characters. List of edits:');
      for (var e in _edits) {
        sb
          ..write('\n    ')
          ..write(e);
      }
      throw UnsupportedError(sb.toString());
    }

    // Add characters from the original string between this edit and the last
    // one, if any.
    var betweenEdits = original.substring(consumed, edit.begin);
    printer
      ..add(betweenEdits, location: _loc(consumed), isOriginal: true)
      ..add(edit.replace, location: _loc(edit.begin));
    consumed = edit.end;
  }

  // Add any text from the end of the original string that was not replaced.
  printer.add(original.substring(consumed),
      location: _loc(consumed), isOriginal: true);
  return printer;
}