Improve FileSpan.context
Previously, if FileSpan.end was directly after a newline,
FileSpan.context would include the entire next line in the span. Then
when this span was highlighted, the end would point confusingly to the
beginning of that next line.
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 2248a39..74ab342 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -1,3 +1,8 @@
+# 1.5.1
+
+* Produce better source span highlights for multi-line spans that cover the
+ entire last line of the span, including the newline.
+
# 1.5.0
* Improve the output of `SourceSpan.highlight()` and `SourceSpan.message()`:
diff --git a/lib/src/file.dart b/lib/src/file.dart
index 6154e13..18c46e6 100644
--- a/lib/src/file.dart
+++ b/lib/src/file.dart
@@ -291,8 +291,29 @@
FileLocation get start => new FileLocation._(file, _start);
FileLocation get end => new FileLocation._(file, _end);
String get text => file.getText(_start, _end);
- String get context => file.getText(file.getOffset(start.line),
- end.line == file.lines - 1 ? null : file.getOffset(end.line + 1));
+
+ String get context {
+ var endLine = file.getLine(_end);
+ var endColumn = file.getColumn(_end);
+
+ int endOffset;
+ if (endColumn == 0 && endLine != 0) {
+ // If [end] is at the very beginning of the line, the span covers the
+ // previous newline, so we only want to include the previous line in the
+ // context.
+ endOffset = _end;
+ } else if (endLine == file.lines - 1) {
+ // If the span covers the last line of the file, the context should go all
+ // the way to the end of the file.
+ endOffset = file.length;
+ } else {
+ // Otherwise, the context should cover the full line on which [end]
+ // appears.
+ endOffset = file.getOffset(endLine + 1);
+ }
+
+ return file.getText(file.getOffset(file.getLine(_start)), endOffset);
+ }
_FileSpan(this.file, this._start, this._end) {
if (_end < _start) {
diff --git a/pubspec.yaml b/pubspec.yaml
index ebd3a72..fc5ba2b 100644
--- a/pubspec.yaml
+++ b/pubspec.yaml
@@ -1,5 +1,5 @@
name: source_span
-version: 1.5.0
+version: 1.5.1
description: A library for identifying source spans and locations.
author: Dart Team <misc@dartlang.org>
diff --git a/test/highlight_test.dart b/test/highlight_test.dart
index 19f8ca8..71b58c3 100644
--- a/test/highlight_test.dart
+++ b/test/highlight_test.dart
@@ -158,6 +158,15 @@
});
test("highlights the full last line", () {
+ expect(file.span(4, 27).highlight(), equals("""
+ ,
+1 | foo bar baz
+ | ,-----^
+2 | \\ whiz bang boom
+ '"""));
+ });
+
+ test("highlights the full last line with no trailing newline", () {
expect(file.span(4, 26).highlight(), equals("""
,
1 | foo bar baz
@@ -176,7 +185,9 @@
'"""));
});
- test("highlights the full last line with no trailing newline", () {
+ test(
+ "highlights the full last line at the end of the file with no trailing"
+ " newline", () {
var file = new SourceFile.fromString("""
foo bar baz
whiz bang boom