miette icon indicating copy to clipboard operation
miette copied to clipboard

Allow disabling of line/column display with an option

Open zen-xu opened this issue 3 years ago • 5 comments

use miette::{Diagnostic, SourceSpan};
use thiserror::Error;

#[derive(Error, Debug, Diagnostic)]
#[error("oops!")]
#[diagnostic(
    code(oops::my::bad),
    url(docsrs),
    help("try doing it better next time?")
)]
struct MyBad {
    // The Source that we're gonna be printing snippets out of.
    // This can be a String if you don't have or care about file names.
    #[source_code]
    src: NamedSource,
    // Snippets and highlights can be included in the diagnostic!
    #[label("This bit here")]
    bad_bit: SourceSpan,
}

/*
Now let's define a function!

Use this Result type (or its expanded version) as the return type
throughout your app (but NOT your libraries! Those should always return concrete
types!).
*/
use miette::{NamedSource, Result};
fn this_fails() -> Result<()> {
    // You can use plain strings as a `Source`, or anything that implements
    // the one-method `Source` trait.
    let src = "source\n  text\n    here".to_string();

    Err(MyBad {
        src: NamedSource::new("bad_file.rs", src),
        bad_bit: (9, 4).into(),
    })?;

    Ok(())
}

/*
Now to get everything printed nicely, just return a Result<()>
and you're all set!

Note: You can swap out the default reporter for a custom one using `miette::set_hook()`
*/
fn main() -> Result<()> {
    // kaboom~
    this_fails()?;

    Ok(())
}

截屏2021-10-23 下午10 05 19

Why it's 1:1 rather than 2:3?

zen-xu avatar Oct 23 '21 14:10 zen-xu

This is by design. That 1:1 is actually referring to the beginning of the overall snippet, not the highlight. This is because miette supports multiple highlights, and to clarify where this context is actually starting.

It might seem kinda surprising in cases like these where the error context begins at 1:1, but if you were looking at several lines into a source file, it would be more useful, imo.

Does that make sense?

zkat avatar Oct 23 '21 15:10 zkat

So can I specify it manually

zen-xu avatar Oct 24 '21 00:10 zen-xu

not in the latest miette, no.

zkat avatar Oct 24 '21 02:10 zkat

I hope this feature can be implemented some day😆

zen-xu avatar Oct 24 '21 03:10 zen-xu

I would take a PR to disable displaying this in the default graphical renderer, for folks who think this might be confusing and would rather just go by the existing line numbers. Would that work for you? Just an option that can be switched off.

zkat avatar Oct 24 '21 03:10 zkat