1use arborium_theme::{HIGHLIGHTS, tag_to_name};
2use rouge_theme::Rgba;
3use serde::{Deserialize, Serialize};
4use std::{collections::BTreeMap, ops::Range, sync::Arc};
5
6#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Hash, Serialize, Deserialize)]
7pub struct FontStyle {
8 #[serde(default)]
9 pub bold: bool,
10 #[serde(default)]
11 pub italic: bool,
12 #[serde(default)]
13 pub underline: bool,
14}
15
16#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
17pub struct HighlightId(u8);
18
19impl HighlightId {
20 #[must_use]
21 pub fn from_tag(tag: &str) -> Option<Self> {
22 tag_to_name(tag)?;
23 let index = HIGHLIGHTS
24 .iter()
25 .position(|highlight| highlight.tag == tag)?;
26 u8::try_from(index).ok().map(Self)
27 }
28}
29
30#[derive(Debug, Clone, PartialEq, Eq)]
32pub struct HighlightSpan {
33 pub range: Range<usize>,
34 pub highlight: HighlightId,
35}
36
37#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
39pub struct SyntaxStyle {
40 pub foreground: Rgba,
41 #[serde(default)]
42 pub font_style: FontStyle,
43}
44
45#[derive(Debug, Clone, PartialEq, Eq)]
46pub struct SyntaxTheme {
47 highlights: Arc<[Option<SyntaxStyle>]>,
48}
49
50impl SyntaxTheme {
51 #[must_use]
52 pub fn new(captures: &BTreeMap<String, SyntaxStyle>) -> Self {
53 Self {
54 highlights: HIGHLIGHTS
55 .iter()
56 .map(|highlight| {
57 tag_to_name(highlight.tag)
58 .and_then(|name| capture_style(captures, capture_for_name(name)))
59 })
60 .collect(),
61 }
62 }
63
64 #[must_use]
65 pub fn highlight(&self, id: HighlightId) -> Option<SyntaxStyle> {
66 self.highlights.get(usize::from(id.0)).copied().flatten()
67 }
68}
69
70impl Default for SyntaxTheme {
71 fn default() -> Self {
72 Self::new(&BTreeMap::new())
73 }
74}
75
76fn capture_for_name(name: &'static str) -> &'static str {
77 match name {
78 "title" => "markup.heading",
79 "strong" => "markup.bold",
80 "emphasis" => "markup.italic",
81 "link" => "markup.link",
82 "literal" => "markup.raw",
83 "strikethrough" => "markup.strikethrough",
84 name => name,
85 }
86}
87
88#[must_use]
89pub fn capture_style(
90 captures: &BTreeMap<String, SyntaxStyle>,
91 capture: &str,
92) -> Option<SyntaxStyle> {
93 let mut candidate = capture;
94 loop {
95 if let Some(style) = captures.get(candidate) {
96 return Some(*style);
97 }
98 let (parent, _) = candidate.rsplit_once('.')?;
99 candidate = parent;
100 }
101}