Skip to content

Commit

Permalink
Use character based columns
Browse files Browse the repository at this point in the history
Towards #74

Use `Characters` to operate based on grapheme clusters instead of code
units.
  • Loading branch information
natebosch committed May 25, 2022
1 parent 24151fd commit 96b6078
Show file tree
Hide file tree
Showing 2 changed files with 14 additions and 4 deletions.
17 changes: 13 additions & 4 deletions lib/src/file.dart
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,8 @@
import 'dart:math' as math;
import 'dart:typed_data';

import 'package:characters/characters.dart';

import 'location.dart';
import 'location_mixin.dart';
import 'span.dart';
Expand Down Expand Up @@ -184,7 +186,9 @@ class SourceFile {
throw RangeError('Line $line comes after offset $offset.');
}

return offset - lineStart;
final content = _decodedChars.sublist(lineStart, offset);
final characters = Characters(String.fromCharCodes(content));
return characters.length;
}

/// Gets the offset for a [line] and [column].
Expand All @@ -202,11 +206,16 @@ class SourceFile {
throw RangeError('Column may not be negative, was $column.');
}

final result = _lineStarts[line] + column;
if (result > length ||
(line + 1 < lines && result >= _lineStarts[line + 1])) {
final content = line < lines - 1
? _decodedChars.sublist(_lineStarts[line], _lineStarts[line + 1])
: _decodedChars.sublist(_lineStarts[line]);
final characters = Characters(String.fromCharCodes(content));
if (characters.length < column) {
throw RangeError("Line $line doesn't have $column columns.");
}
final withinLineLength =
characters.take(column).toString().codeUnits.length;
final result = _lineStarts[line] + withinLineLength;

return result;
}
Expand Down
1 change: 1 addition & 0 deletions pubspec.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ environment:
sdk: ">=2.14.0 <3.0.0"

dependencies:
characters: ^1.2.0
collection: ^1.15.0
path: ^1.8.0
term_glyph: ^1.2.0
Expand Down

0 comments on commit 96b6078

Please sign in to comment.