Skip to content

feat: Allow setting the primary level for a group #235

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 4 commits into from
Jul 1, 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
22 changes: 22 additions & 0 deletions examples/elide_header.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
use annotate_snippets::{AnnotationKind, Group, Level, Renderer, Snippet};

fn main() {
let source = r#"# Docstring followed by a newline

def foobar(door, bar={}):
"""
"""
"#;

let message = &[Group::new()
.primary_level(Level::NOTE)
.element(
Snippet::source(source)
.fold(false)
.annotation(AnnotationKind::Primary.span(56..58).label("B006")),
)
.element(Level::HELP.title("Replace with `None`; initialize within function"))];

let renderer = Renderer::styled();
anstream::println!("{}", renderer.render(message));
}
44 changes: 44 additions & 0 deletions examples/elide_header.svg
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
18 changes: 10 additions & 8 deletions src/renderer/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -275,14 +275,16 @@ impl Renderer {
if og_primary_path.is_none() && primary_path.is_some() {
og_primary_path = primary_path;
}
let level = group
.elements
.iter()
.find_map(|s| match &s {
Element::Title(title) => Some(title.level.clone()),
_ => None,
})
.unwrap_or(Level::ERROR);
let level = group.primary_level.clone().unwrap_or_else(|| {
group
.elements
.first()
.and_then(|s| match &s {
Element::Title(title) => Some(title.level.clone()),
_ => None,
})
.unwrap_or(Level::ERROR)
});
let mut source_map_annotated_lines = VecDeque::new();
let mut max_depth = 0;
for e in &group.elements {
Expand Down
27 changes: 23 additions & 4 deletions src/snippet.rs
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,7 @@ pub(crate) struct Id<'a> {
/// An [`Element`] container
#[derive(Clone, Debug)]
pub struct Group<'a> {
pub(crate) primary_level: Option<Level<'a>>,
pub(crate) elements: Vec<Element<'a>>,
}

Expand All @@ -31,7 +32,10 @@ impl Default for Group<'_> {

impl<'a> Group<'a> {
pub fn new() -> Self {
Self { elements: vec![] }
Self {
primary_level: None,
elements: vec![],
}
}

pub fn element(mut self, section: impl Into<Element<'a>>) -> Self {
Expand All @@ -44,6 +48,15 @@ impl<'a> Group<'a> {
self
}

/// Set the primary [`Level`] for this [`Group`].
///
/// If not specified, use the [`Level`] of the first element in a [`Group`]
/// if it is a [`Title`]. If not it will default to [`Level::ERROR`].
pub fn primary_level(mut self, level: Level<'a>) -> Self {
self.primary_level = Some(level);
self
}

pub fn is_empty(&self) -> bool {
self.elements.is_empty()
}
Expand Down Expand Up @@ -262,10 +275,16 @@ impl<'a> Annotation<'a> {
#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord)]
#[non_exhaustive]
pub enum AnnotationKind {
/// Color to the [`Level`] the first [`Title`] in [`Group`]. If no [`Title`]
/// is present, it will default to `error`.
/// Match the primary [`Level`] of the group.
///
/// See [`Group::primary_level`] for details about how this is determined
Primary,
/// "secondary"; fixed color
/// Additional context to explain the [`Primary`][Self::Primary]
/// [`Annotation`]
///
/// See also [`Renderer::context`].
///
/// [`Renderer::context`]: crate::renderer::Renderer
Context,
}

Expand Down
7 changes: 7 additions & 0 deletions tests/examples.rs
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,13 @@ fn custom_level() {
assert_example(target, expected);
}

#[test]
fn elide_header() {
let target = "elide_header";
let expected = snapbox::file!["../examples/elide_header.svg": TermSvg];
assert_example(target, expected);
}

#[test]
fn expected_type() {
let target = "expected_type";
Expand Down