arborium_highlight/types.rs
1//! Core types for highlighting.
2
3use std::fmt;
4
5/// A span of highlighted text.
6///
7/// Spans come from grammar parsers and contain the raw capture name
8/// (e.g., "keyword.function", "include", "string.special.symbol").
9/// The capture name is later mapped to a theme slot for rendering.
10#[derive(Debug, Clone, PartialEq, Eq)]
11pub struct Span {
12 /// Byte offset where the span starts (inclusive).
13 pub start: u32,
14
15 /// Byte offset where the span ends (exclusive).
16 pub end: u32,
17
18 /// The capture name from the grammar's highlight query.
19 ///
20 /// Examples: "keyword", "function.builtin", "include", "storageclass"
21 /// All are mapped to theme slots via `arborium_theme::tag_for_capture()`.
22 pub capture: String,
23
24 /// Pattern index from the query (higher = later in highlights.scm = higher priority).
25 ///
26 /// When two spans have the exact same (start, end) range, the one with
27 /// higher pattern_index wins during deduplication. This matches the
28 /// tree-sitter convention where later patterns in a query override earlier ones.
29 pub pattern_index: u32,
30}
31
32/// An injection point for embedded languages.
33///
34/// Injections are detected by the grammar's injection query. For example,
35/// HTML can inject CSS and JavaScript into `<style>` and `<script>` tags.
36#[derive(Debug, Clone, PartialEq, Eq)]
37pub struct Injection {
38 /// Byte offset where the injection starts (inclusive).
39 pub start: u32,
40
41 /// Byte offset where the injection ends (exclusive).
42 pub end: u32,
43
44 /// The language to inject (e.g., "javascript", "css").
45 pub language: String,
46
47 /// Whether to include the node's children in the injection range.
48 pub include_children: bool,
49}
50
51/// Result of parsing a document with a grammar.
52#[derive(Debug, Clone, Default)]
53pub struct ParseResult {
54 /// Highlighted spans from this parse.
55 pub spans: Vec<Span>,
56
57 /// Injection points for other languages.
58 pub injections: Vec<Injection>,
59}
60
61/// Errors that can occur during highlighting.
62#[derive(Debug, Clone, PartialEq, Eq)]
63pub enum HighlightError {
64 /// The requested language is not supported.
65 UnsupportedLanguage(String),
66
67 /// An error occurred during parsing.
68 ParseError(String),
69}
70
71impl fmt::Display for HighlightError {
72 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
73 match self {
74 HighlightError::UnsupportedLanguage(lang) => {
75 write!(f, "unsupported language: {}", lang)
76 }
77 HighlightError::ParseError(msg) => {
78 write!(f, "parse error: {}", msg)
79 }
80 }
81 }
82}
83
84impl std::error::Error for HighlightError {}