Skip to content

how to annotate an empty span immediately before the start of a line? #176

Closed
@BurntSushi

Description

@BurntSushi

During the process of upgrading our copy of annotate-snippets in Ruff, I discovered that the way empty spans after a line terminator are handled had changed.

Previously:

use annotate_snippets::{
    display_list::{DisplayList, FormatOptions},
    snippet::{AnnotationType, Slice, Snippet, SourceAnnotation},
};

fn main() {
    let source = "#: E112\nif False:\nprint()\n#: E113\nprint()\n";
    let snippet = Snippet {
        title: None,
        footer: vec![],
        slices: vec![Slice {
            source,
            line_start: 7,
            origin: None,
            annotations: vec![SourceAnnotation {
                range: (18, 18),
                label: "E112",
                annotation_type: AnnotationType::Error,
            }],
            fold: false,
        }],
        opt: FormatOptions {
            color: false,
            anonymized_line_numbers: false,
            margin: None,
        },
    };
    println!("{message}", message = DisplayList::from(snippet));
}

had this output:

   |
 7 | #: E112
 8 | if False:
 9 | print()
   |  E112
10 | #: E113
11 | print()
   |

And now:

use annotate_snippets::{Level, Renderer, Snippet};

fn main() {
    let source = "#: E112\nif False:\nprint()\n#: E113\nprint()\n";
    let src_annotation = Level::Error.span(18..18).label("E112");
    let snippet =
        Snippet::source(source).line_start(7).annotation(src_annotation);
    let message = Level::Error.title("").snippet(snippet);

    println!("{}", Renderer::plain().render(message));
}

Has this output:

error
   |
 7 | #: E112
 8 | if False:
   |          ^ E112
 9 | print()
10 | #: E113
11 | print()
   |

Now, to be clear, the previous output seems to be a bit buggy since the ^ is missing. But the rendering matched up with the line following the line terminator, where as the new version of annotate-snippets matches up with the line preceding the line terminator.

If you change the span from 18..18 above to 17..17 (i.e., just before the line terminator), the rendered output doesn't actually change. So to me it seems like if the span comes after the line terminator, it should probably point to the beginning of the next line?

Anyway, I don't know exactly what the right behavior should be here, so my goal here is just to understand if this change was intentional, and if so, what the thinking is behind it. Or are empty spans discouraged in general?

(As you might imagine, a system that organically grew around the old behavior is difficult to adapt to the new behavior.)

Metadata

Metadata

Assignees

Labels

No labels
No labels

Type

No type

Projects

No projects

Milestone

No milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions