Skip to content

docs: Clarify usage #245

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 14 commits into from
Jul 3, 2025
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
18 changes: 5 additions & 13 deletions examples/highlight_message.rs
Original file line number Diff line number Diff line change
@@ -1,5 +1,7 @@
use annotate_snippets::{AnnotationKind, Group, Level, Renderer, Snippet};
use anstyle::AnsiColor;
use anstyle::Effects;
use anstyle::Style;

fn main() {
let source = r#"// Make sure "highlighted" code is colored purple
Expand All @@ -25,20 +27,10 @@ fn main() {
query(wrapped_fn);
}"#;

let magenta = annotate_snippets::renderer::AnsiColor::Magenta
.on_default()
.effects(Effects::BOLD);
const MAGENTA: Style = AnsiColor::Magenta.on_default().effects(Effects::BOLD);
let message = format!(
"expected fn pointer `{}for<'a>{} fn(Box<{}(dyn Any + Send + 'a){}>) -> Pin<_>`
found fn item `fn(Box<{}(dyn Any + Send + 'static){}>) -> Pin<_> {}{{wrapped_fn}}{}`",
magenta.render(),
magenta.render_reset(),
magenta.render(),
magenta.render_reset(),
magenta.render(),
magenta.render_reset(),
magenta.render(),
magenta.render_reset()
"expected fn pointer `{MAGENTA}for<'a>{MAGENTA:#} fn(Box<{MAGENTA}(dyn Any + Send + 'a){MAGENTA:#}>) -> Pin<_>`
found fn item `fn(Box<{MAGENTA}(dyn Any + Send + 'static){MAGENTA:#}>) -> Pin<_> {MAGENTA}{{wrapped_fn}}{MAGENTA:#}`",
);

let message = &[
Expand Down
110 changes: 88 additions & 22 deletions src/level.rs
Original file line number Diff line number Diff line change
Expand Up @@ -36,40 +36,20 @@ pub const HELP: Level<'_> = Level {
level: LevelInner::Help,
};

/// [`Title`] severity level
/// Severity level for [`Title`]s and [`Message`]s
#[derive(Clone, Debug, PartialEq, Eq, PartialOrd, Ord)]
pub struct Level<'a> {
pub(crate) name: Option<Option<Cow<'a, str>>>,
pub(crate) level: LevelInner,
}

/// # Constructors
impl<'a> Level<'a> {
pub const ERROR: Level<'a> = ERROR;
pub const WARNING: Level<'a> = WARNING;
pub const INFO: Level<'a> = INFO;
pub const NOTE: Level<'a> = NOTE;
pub const HELP: Level<'a> = HELP;

/// Replace the name describing this [`Level`]
///
/// <div class="warning">
///
/// Text passed to this function is considered "untrusted input", as such
/// all text is passed through a normalization function. Pre-styled text is
/// not allowed to be passed to this function.
///
/// </div>
pub fn with_name(self, name: impl Into<OptionCow<'a>>) -> Level<'a> {
Level {
name: Some(name.into().0),
level: self.level,
}
}

/// Do not show the [`Level`]s name
pub fn no_name(self) -> Level<'a> {
self.with_name(None::<&str>)
}
}

impl<'a> Level<'a> {
Expand All @@ -84,6 +64,15 @@ impl<'a> Level<'a> {
/// not allowed to be passed to this function.
///
/// </div>
///
/// # Example
///
/// ```rust
/// # use annotate_snippets::{Group, Snippet, AnnotationKind, Level};
/// let input = &[
/// Group::with_title(Level::ERROR.title("mismatched types").id("E0308"))
/// ];
/// ```
pub fn title(self, text: impl Into<Cow<'a, str>>) -> Title<'a> {
Title {
level: self,
Expand All @@ -102,6 +91,20 @@ impl<'a> Level<'a> {
/// used to normalize untrusted text before it is passed to this function.
///
/// </div>
///
/// # Example
///
/// ```rust
/// # use annotate_snippets::{Group, Snippet, AnnotationKind, Level};
/// let input = &[
/// Group::with_title(Level::ERROR.title("mismatched types").id("E0308"))
/// .element(
/// Level::NOTE
/// .no_name()
/// .message("expected reference `&str`\nfound reference `&'static [u8; 0]`"),
/// ),
/// ];
/// ```
pub fn message(self, text: impl Into<Cow<'a, str>>) -> Message<'a> {
Message {
level: self,
Expand All @@ -126,6 +129,69 @@ impl<'a> Level<'a> {
}
}

/// # Customize the `Level`
impl<'a> Level<'a> {
/// Replace the name describing this [`Level`]
///
/// <div class="warning">
///
/// Text passed to this function is considered "untrusted input", as such
/// all text is passed through a normalization function. Pre-styled text is
/// not allowed to be passed to this function.
///
/// </div>
///
/// # Example
///
/// ```rust
#[doc = include_str!("../examples/custom_level.rs")]
/// ```
#[doc = include_str!("../examples/custom_level.svg")]
pub fn with_name(self, name: impl Into<OptionCow<'a>>) -> Level<'a> {
Level {
name: Some(name.into().0),
level: self.level,
}
}

/// Do not show the [`Level`]s name
///
/// # Example
///
/// ```rust
/// # use annotate_snippets::{Group, Snippet, AnnotationKind, Level};
///let source = r#"fn main() {
/// let b: &[u8] = include_str!("file.txt"); //~ ERROR mismatched types
/// let s: &str = include_bytes!("file.txt"); //~ ERROR mismatched types
/// }"#;
/// let input = &[
/// Group::with_title(Level::ERROR.title("mismatched types").id("E0308"))
/// .element(
/// Snippet::source(source)
/// .path("$DIR/mismatched-types.rs")
/// .annotation(
/// AnnotationKind::Primary
/// .span(105..131)
/// .label("expected `&str`, found `&[u8; 0]`"),
/// )
/// .annotation(
/// AnnotationKind::Context
/// .span(98..102)
/// .label("expected due to this"),
/// ),
/// )
/// .element(
/// Level::NOTE
/// .no_name()
/// .message("expected reference `&str`\nfound reference `&'static [u8; 0]`"),
/// ),
/// ];
/// ```
pub fn no_name(self) -> Level<'a> {
self.with_name(None::<&str>)
}
}

#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord)]
pub(crate) enum LevelInner {
Error,
Expand Down
4 changes: 2 additions & 2 deletions src/renderer/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -484,7 +484,7 @@ impl Renderer {
}

if let Some(path) = &cause.path {
let mut origin = Origin::new(path.as_ref());
let mut origin = Origin::path(path.as_ref());
origin.primary = true;

let source_map = SourceMap::new(&cause.source, cause.line_start);
Expand Down Expand Up @@ -719,7 +719,7 @@ impl Renderer {
is_cont: bool,
) {
if let Some(path) = &snippet.path {
let mut origin = Origin::new(path.as_ref());
let mut origin = Origin::path(path.as_ref());
// print out the span location and spacer before we print the annotated source
// to do this, we need to know if this span will be primary
let is_primary = primary_path == Some(&origin.path);
Expand Down
6 changes: 3 additions & 3 deletions src/renderer/styled_buffer.rs
Original file line number Diff line number Diff line change
Expand Up @@ -51,14 +51,14 @@ impl StyledBuffer {
let ch_style = style.color_spec(level, stylesheet);
if ch_style != current_style {
if !line.is_empty() {
write!(str, "{}", current_style.render_reset())?;
write!(str, "{current_style:#}")?;
}
current_style = ch_style;
write!(str, "{}", current_style.render())?;
write!(str, "{current_style}")?;
}
write!(str, "{ch}")?;
}
write!(str, "{}", current_style.render_reset())?;
write!(str, "{current_style:#}")?;
if i != self.lines.len() - 1 {
writeln!(str)?;
}
Expand Down
32 changes: 29 additions & 3 deletions src/snippet.rs
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,13 @@ pub(crate) struct Id<'a> {
/// A [diagnostic][crate::Renderer::render] is made of several `Group`s.
/// `Group`s are used to [annotate][AnnotationKind::Primary] [`Snippet`]s
/// with different [semantic reasons][Title].
///
/// # Example
///
/// ```rust
#[doc = include_str!("../examples/highlight_message.rs")]
/// ```
#[doc = include_str!("../examples/highlight_message.svg")]
#[derive(Clone, Debug)]
pub struct Group<'a> {
pub(crate) primary_level: Level<'a>,
Expand All @@ -36,6 +43,13 @@ impl<'a> Group<'a> {
}

/// Create a title-less group with a primary [`Level`] for [`Annotation`]s
///
/// # Example
///
/// ```rust
#[doc = include_str!("../examples/elide_header.rs")]
/// ```
#[doc = include_str!("../examples/elide_header.svg")]
pub fn with_level(level: Level<'a>) -> Self {
Self {
primary_level: level,
Expand Down Expand Up @@ -386,9 +400,21 @@ impl<'a> Patch<'a> {
}
}

/// The referenced location (e.g. a path)
/// A source location [`Element`] in a [`Group`]
///
/// If you have source available, see instead [`Snippet`]
///
/// # Example
///
/// ```rust
/// # use annotate_snippets::{Group, Snippet, AnnotationKind, Level, Origin};
/// let input = &[
/// Group::with_title(Level::ERROR.title("mismatched types").id("E0308"))
/// .element(
/// Origin::path("$DIR/mismatched-types.rs")
/// )
/// ];
/// ```
#[derive(Clone, Debug)]
pub struct Origin<'a> {
pub(crate) path: Cow<'a, str>,
Expand All @@ -405,7 +431,7 @@ impl<'a> Origin<'a> {
/// not allowed to be passed to this function.
///
/// </div>
pub fn new(path: impl Into<Cow<'a, str>>) -> Self {
pub fn path(path: impl Into<Cow<'a, str>>) -> Self {
Self {
path: path.into(),
line: None,
Expand Down Expand Up @@ -441,7 +467,7 @@ impl<'a> Origin<'a> {

impl<'a> From<Cow<'a, str>> for Origin<'a> {
fn from(origin: Cow<'a, str>) -> Self {
Self::new(origin)
Self::path(origin)
}
}

Expand Down
2 changes: 1 addition & 1 deletion tests/color/multiline_removal_suggestion.rs
Original file line number Diff line number Diff line change
Expand Up @@ -88,7 +88,7 @@ fn main() {}
),
Group::with_title(Level::NOTE.title("required by a bound in `flatten`"))
.element(
Origin::new("/rustc/FAKE_PREFIX/library/core/src/iter/traits/iterator.rs")
Origin::path("/rustc/FAKE_PREFIX/library/core/src/iter/traits/iterator.rs")
.line(1556)
.char_column(4),
),
Expand Down
4 changes: 2 additions & 2 deletions tests/formatter.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2400,7 +2400,7 @@ fn secondary_title_no_level_text() {
.element(
Level::NOTE
.no_name()
.title("expected reference `&str`\nfound reference `&'static [u8; 0]`"),
.message("expected reference `&str`\nfound reference `&'static [u8; 0]`"),
),
];

Expand Down Expand Up @@ -2445,7 +2445,7 @@ fn secondary_title_custom_level_text() {
.element(
Level::NOTE
.with_name(Some("custom"))
.title("expected reference `&str`\nfound reference `&'static [u8; 0]`"),
.message("expected reference `&str`\nfound reference `&'static [u8; 0]`"),
),
];

Expand Down
2 changes: 1 addition & 1 deletion tests/rustc_tests.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1743,7 +1743,7 @@ fn main() {
Level::NOTE
.title("for a trait to be dyn compatible it needs to allow building a vtable\nfor more information, visit <https://doc.rust-lang.org/reference/items/traits.html#dyn-compatibility>"))
.element(
Origin::new("$SRC_DIR/core/src/cmp.rs")
Origin::path("$SRC_DIR/core/src/cmp.rs")
.line(334)
.char_column(14)
.primary(true)
Expand Down