Skip to main content

mq_lang/
selector.rs

1use std::fmt::{self, Display, Formatter};
2
3#[cfg(feature = "ast-json")]
4use serde::{Deserialize, Serialize};
5use thiserror::Error;
6
7use crate::{Ident, Token, TokenKind};
8
9/// Error type returned when an unknown selector is encountered during parsing.
10#[derive(Error, Clone, Debug, PartialOrd, Eq, Ord, PartialEq)]
11#[error("Unknown selector `{0}`")]
12pub struct UnknownSelector(pub Token);
13
14/// Parses a bracket-based selector string like `.[n]` (List) or `.[n][m]` (Table).
15///
16/// Returns `Some(Selector)` if the string matches, `None` otherwise.
17fn parse_bracket_selector(s: &str) -> Option<Selector> {
18    let inner = s.strip_prefix(".[")?;
19    let (first, rest) = inner.split_once(']')?;
20
21    if !first.is_empty() && !first.bytes().all(|b| b.is_ascii_digit()) {
22        return None;
23    }
24    let first_idx: Option<usize> = if first.is_empty() {
25        None
26    } else {
27        Some(first.parse().ok()?)
28    };
29
30    if rest.is_empty() {
31        // ".[n]" → List
32        return Some(Selector::List(first_idx, None));
33    }
34
35    let inner2 = rest.strip_prefix('[')?;
36    let (second, tail) = inner2.split_once(']')?;
37    if !tail.is_empty() {
38        return None;
39    }
40    if !second.is_empty() && !second.bytes().all(|b| b.is_ascii_digit()) {
41        return None;
42    }
43    let second_idx: Option<usize> = if second.is_empty() {
44        None
45    } else {
46        Some(second.parse().ok()?)
47    };
48    // ".[n][m]" → Table
49    Some(Selector::Table(first_idx, second_idx))
50}
51
52impl UnknownSelector {
53    /// Creates a new `UnknownSelector` error with the given token.
54    pub fn new(token: Token) -> Self {
55        Self(token)
56    }
57}
58
59/// Unescapes `\"` and `\\` sequences in a quoted property key.
60fn unescape_property_key(s: &str) -> String {
61    let mut result = String::with_capacity(s.len());
62    let mut chars = s.chars();
63    while let Some(c) = chars.next() {
64        if c == '\\' {
65            if let Some(next) = chars.next() {
66                result.push(next);
67            }
68        } else {
69            result.push(c);
70        }
71    }
72    result
73}
74
75/// Escapes `"` and `\` characters in a property key for display as `."key"`.
76fn escape_property_key(key: &str) -> String {
77    let mut result = String::with_capacity(key.len() + 2);
78    for c in key.chars() {
79        match c {
80            '"' => result.push_str("\\\""),
81            '\\' => result.push_str("\\\\"),
82            _ => result.push(c),
83        }
84    }
85    result
86}
87
88/// A selector for matching specific types of markdown nodes.
89///
90/// Selectors are used to query and filter markdown documents, similar to CSS selectors
91/// for HTML. Each variant matches a specific type of markdown element.
92#[cfg_attr(feature = "ast-json", derive(Serialize, Deserialize))]
93#[derive(PartialEq, PartialOrd, Debug, Eq, Clone)]
94pub enum Selector {
95    /// Matches blockquote elements (e.g., `> quoted text`).
96    Blockquote,
97    /// Matches footnote definitions.
98    Footnote,
99    /// Matches list elements.
100    ///
101    /// The first `Option<usize>` specifies an item index, the second `Option<bool>` indicates ordered/unordered.
102    List(Option<usize>, Option<bool>),
103    /// Matches TOML frontmatter blocks.
104    Toml,
105    /// Matches YAML frontmatter blocks.
106    Yaml,
107    /// Matches line break elements.
108    Break,
109    /// Matches inline code elements (e.g., `` `code` ``).
110    InlineCode,
111    /// Matches inline math elements (e.g., `$math$`).
112    InlineMath,
113    /// Matches strikethrough/delete elements (e.g., `~~text~~`).
114    Delete,
115    /// Matches emphasis elements (e.g., `*text*` or `_text_`).
116    Emphasis,
117    /// Matches footnote references (e.g., `[^1]`).
118    FootnoteRef,
119    /// Matches raw HTML elements.
120    Html,
121    /// Matches image elements (e.g., `![alt](url)`).
122    Image,
123    /// Matches image reference elements (e.g., `![alt][ref]`).
124    ImageRef,
125    /// Matches MDX JSX text elements.
126    MdxJsxTextElement,
127    /// Matches link elements (e.g., `[text](url)`). Also matches wikilinks when the `wikilink` feature is enabled.
128    Link,
129    /// Matches link reference elements (e.g., `[text][ref]`).
130    LinkRef,
131    /// Matches Obsidian-style wikilink elements (e.g., `[[target]]` or `[[target|text]]`).
132    WikiLink,
133    /// Matches Obsidian-style callout elements (e.g., `> [!NOTE]` or `> [!WARNING] title`).
134    Callout,
135    /// Matches Obsidian-style embed elements (e.g., `![[target]]` or `![[target|display]]`).
136    Embed,
137    /// Matches strong/bold elements (e.g., `**text**`).
138    Strong,
139    /// Matches code block elements.
140    Code,
141    /// Matches math block elements (e.g., `$$math$$`).
142    Math,
143    /// Matches heading elements.
144    ///
145    /// The `Option<u8>` specifies the heading level (1-6). If `None`, matches any heading level.
146    Heading(Option<u8>),
147    /// Matches table elements.
148    ///
149    /// The first `Option<usize>` specifies row index, the second specifies column index.
150    Table(Option<usize>, Option<usize>),
151    /// Matches table alignment elements.
152    TableAlign,
153    /// Matches text nodes.
154    Text,
155    /// Matches horizontal rule elements (e.g., `---`, `***`, `___`).
156    HorizontalRule,
157    /// Matches link/image definition elements.
158    Definition,
159    /// Matches MDX flow expression elements.
160    MdxFlowExpression,
161    /// Matches MDX text expression elements.
162    MdxTextExpression,
163    /// Matches MDX ES module import/export elements.
164    MdxJsEsm,
165    /// Matches MDX JSX flow elements.
166    MdxJsxFlowElement,
167    /// Matches recursively all child nodes.
168    Recursive,
169    /// Matches a task list markdown node.
170    Task,
171    /// Matches a task list markdown node with an unchecked status.
172    Todo,
173    /// Matches a task list markdown node with a checked status.
174    Done,
175    /// Matches a specific attribute of a markdown node.
176    Attr(AttrKind),
177    /// Matches a specific property of a dict or array.
178    Property(Ident),
179}
180
181/// Represents an attribute that can be accessed from markdown nodes.
182///
183/// Attributes allow extracting specific properties from markdown elements,
184/// such as the URL from a link or the language from a code block.
185#[cfg_attr(feature = "ast-json", derive(Serialize, Deserialize))]
186#[derive(PartialEq, PartialOrd, Debug, Eq, Clone)]
187pub enum AttrKind {
188    /// The text value or content of a node.
189    Value,
190    /// Collection of values (used for certain node types).
191    Values,
192    /// The children nodes of an element.
193    Children,
194
195    /// The programming language identifier for code blocks.
196    Lang,
197    /// Additional metadata for code blocks.
198    Meta,
199    /// The fence character used for code blocks (e.g., `` ` `` or `~`).
200    Fence,
201
202    /// The URL for links and images.
203    Url,
204    /// The alt text for images.
205    Alt,
206    /// The title attribute for links and images.
207    Title,
208
209    /// The identifier for references (LinkRef, ImageRef, FootnoteRef, Definition, Footnote).
210    Ident,
211    /// The label for references.
212    Label,
213
214    /// The depth level of a heading (1-6).
215    Depth,
216    /// Alias for `Depth` - the level of a heading.
217    Level,
218
219    /// The index of a list item within its parent list.
220    Index,
221    /// Whether a list is ordered (numbered) or unordered.
222    Ordered,
223    /// The checked status of a task list item.
224    Checked,
225
226    /// The column index of a table cell.
227    Column,
228    /// The row index of a table cell.
229    Row,
230
231    /// The alignment of a table header (left, right, center, none).
232    Align,
233
234    /// The name attribute for MDX JSX elements.
235    Name,
236    /// The kind/type of an Obsidian callout (e.g. `"NOTE"`, `"WARNING"`).
237    Kind,
238
239    /// The 1-indexed source line the node starts on (`None` if unparsed/synthetic).
240    Line,
241    /// The 1-indexed source line the node ends on (`None` if unparsed/synthetic).
242    EndLine,
243}
244
245impl Display for AttrKind {
246    fn fmt(&self, f: &mut Formatter<'_>) -> Result<(), fmt::Error> {
247        match self {
248            AttrKind::Value => write!(f, ".value"),
249            AttrKind::Values => write!(f, ".values"),
250            AttrKind::Children => write!(f, ".children"),
251            AttrKind::Lang => write!(f, ".lang"),
252            AttrKind::Meta => write!(f, ".meta"),
253            AttrKind::Fence => write!(f, ".fence"),
254            AttrKind::Url => write!(f, ".url"),
255            AttrKind::Alt => write!(f, ".alt"),
256            AttrKind::Title => write!(f, ".title"),
257            AttrKind::Ident => write!(f, ".ident"),
258            AttrKind::Label => write!(f, ".label"),
259            AttrKind::Depth => write!(f, ".depth"),
260            AttrKind::Level => write!(f, ".level"),
261            AttrKind::Index => write!(f, ".index"),
262            AttrKind::Ordered => write!(f, ".ordered"),
263            AttrKind::Checked => write!(f, ".checked"),
264            AttrKind::Column => write!(f, ".column"),
265            AttrKind::Row => write!(f, ".row"),
266            AttrKind::Align => write!(f, ".align"),
267            AttrKind::Name => write!(f, ".name"),
268            AttrKind::Kind => write!(f, ".kind"),
269            AttrKind::Line => write!(f, ".line"),
270            AttrKind::EndLine => write!(f, ".end_line"),
271        }
272    }
273}
274
275/// Declares the simple selector names once, generating both `Selector::from_selector_str`
276/// and `SELECTOR_NAMES`.
277macro_rules! selector_table {
278    ($($($name:literal)|+ => $selector:expr,)+) => {
279        /// Every name accepted by `Selector::from_selector_str`.
280        pub const SELECTOR_NAMES: &[&str] = &[$($($name),+),+];
281
282        impl Selector {
283            /// Converts a dot-prefixed selector string (e.g. `".text"`, `".h"`) to a `Selector`.
284            ///
285            /// Returns `None` for unknown or non-simple selectors (bracket forms, quoted keys).
286            pub fn from_selector_str(s: &str) -> Option<Self> {
287                match s {
288                    $($($name)|+ => Some($selector),)+
289                    _ => None,
290                }
291            }
292        }
293    };
294}
295
296selector_table! {
297    ".h" | ".heading" => Selector::Heading(None),
298    ".h1" => Selector::Heading(Some(1)),
299    ".h2" => Selector::Heading(Some(2)),
300    ".h3" => Selector::Heading(Some(3)),
301    ".h4" => Selector::Heading(Some(4)),
302    ".h5" => Selector::Heading(Some(5)),
303    ".h6" => Selector::Heading(Some(6)),
304    ".>" | ".blockquote" => Selector::Blockquote,
305    ".^" | ".footnote" => Selector::Footnote,
306    ".<" | ".mdx_jsx_flow_element" => Selector::MdxJsxFlowElement,
307    ".**" | ".emphasis" => Selector::Emphasis,
308    ".$$" | ".math" => Selector::Math,
309    ".horizontal_rule" | ".hr" | ".---" | ".***" | ".___" => Selector::HorizontalRule,
310    ".{}" | ".mdx_text_expression" => Selector::MdxTextExpression,
311    ".[^]" | ".footnote_ref" => Selector::FootnoteRef,
312    ".definition" => Selector::Definition,
313    ".break" | ".br" => Selector::Break,
314    ".delete" => Selector::Delete,
315    ".<>" | ".html" => Selector::Html,
316    ".image" => Selector::Image,
317    ".image_ref" => Selector::ImageRef,
318    ".code_inline" | ".inline_code" => Selector::InlineCode,
319    ".math_inline" | ".inline_math" => Selector::InlineMath,
320    ".link" => Selector::Link,
321    ".link_ref" => Selector::LinkRef,
322    ".wikilink" => Selector::WikiLink,
323    ".callout" => Selector::Callout,
324    ".embed" => Selector::Embed,
325    ".[]" | ".list" | ".li" => Selector::List(None, None),
326    ".task" => Selector::Task,
327    ".todo" => Selector::Todo,
328    ".done" => Selector::Done,
329    ".toml" => Selector::Toml,
330    ".strong" => Selector::Strong,
331    ".yaml" => Selector::Yaml,
332    ".code" | ".code_block" => Selector::Code,
333    ".mdx_js_esm" => Selector::MdxJsEsm,
334    ".mdx_jsx_text_element" => Selector::MdxJsxTextElement,
335    ".mdx_flow_expression" => Selector::MdxFlowExpression,
336    ".text" | ".p" | ".paragraph" => Selector::Text,
337    ".[][]" | ".table" => Selector::Table(None, None),
338    ".table_align" => Selector::TableAlign,
339    ".." => Selector::Recursive,
340    ".value" => Selector::Attr(AttrKind::Value),
341    ".values" => Selector::Attr(AttrKind::Values),
342    ".children" | ".cn" => Selector::Attr(AttrKind::Children),
343    ".lang" => Selector::Attr(AttrKind::Lang),
344    ".meta" => Selector::Attr(AttrKind::Meta),
345    ".fence" => Selector::Attr(AttrKind::Fence),
346    ".url" => Selector::Attr(AttrKind::Url),
347    ".alt" => Selector::Attr(AttrKind::Alt),
348    ".title" => Selector::Attr(AttrKind::Title),
349    ".ident" => Selector::Attr(AttrKind::Ident),
350    ".label" => Selector::Attr(AttrKind::Label),
351    ".depth" => Selector::Attr(AttrKind::Depth),
352    ".level" => Selector::Attr(AttrKind::Level),
353    ".index" => Selector::Attr(AttrKind::Index),
354    ".ordered" => Selector::Attr(AttrKind::Ordered),
355    ".checked" => Selector::Attr(AttrKind::Checked),
356    ".column" => Selector::Attr(AttrKind::Column),
357    ".row" => Selector::Attr(AttrKind::Row),
358    ".align" => Selector::Attr(AttrKind::Align),
359    ".name" => Selector::Attr(AttrKind::Name),
360    ".kind" => Selector::Attr(AttrKind::Kind),
361    ".line" => Selector::Attr(AttrKind::Line),
362    ".end_line" => Selector::Attr(AttrKind::EndLine),
363}
364
365impl TryFrom<&Token> for Selector {
366    type Error = UnknownSelector;
367
368    fn try_from(token: &Token) -> Result<Self, Self::Error> {
369        if let TokenKind::Selector(s) = &token.kind {
370            if let Some(sel) = Self::from_selector_str(s.as_str()) {
371                return Ok(sel);
372            }
373            if let Some(sel) = parse_bracket_selector(s.as_str()) {
374                return Ok(sel);
375            }
376            // Quoted property selector: ."key" is the only way to access dict keys
377            if let Some(quoted) = s.strip_prefix(".\"").and_then(|r| r.strip_suffix('"')) {
378                return Ok(Selector::Property(Ident::new(&unescape_property_key(quoted))));
379            }
380            Err(UnknownSelector(token.clone()))
381        } else {
382            Err(UnknownSelector(token.clone()))
383        }
384    }
385}
386
387impl Display for Selector {
388    fn fmt(&self, f: &mut Formatter<'_>) -> Result<(), fmt::Error> {
389        match self {
390            Selector::Heading(None) => write!(f, ".h"),
391            Selector::Heading(Some(1)) => write!(f, ".h1"),
392            Selector::Heading(Some(2)) => write!(f, ".h2"),
393            Selector::Heading(Some(3)) => write!(f, ".h3"),
394            Selector::Heading(Some(4)) => write!(f, ".h4"),
395            Selector::Heading(Some(5)) => write!(f, ".h5"),
396            Selector::Heading(Some(6)) => write!(f, ".h6"),
397            Selector::Heading(Some(n)) => write!(f, ".h{}", n),
398            Selector::Blockquote => write!(f, ".blockquote"),
399            Selector::Footnote => write!(f, ".footnote"),
400            Selector::List(None, None) => write!(f, ".list"),
401            Selector::List(Some(idx), None) => write!(f, ".[{}]", idx),
402            Selector::List(Some(idx), _) => write!(f, ".[{}]", idx),
403            Selector::List(None, _) => write!(f, ".[]"),
404            Selector::Toml => write!(f, ".toml"),
405            Selector::Yaml => write!(f, ".yaml"),
406            Selector::Break => write!(f, ".break"),
407            Selector::InlineCode => write!(f, ".code_inline"),
408            Selector::InlineMath => write!(f, ".math_inline"),
409            Selector::Delete => write!(f, ".delete"),
410            Selector::Emphasis => write!(f, ".emphasis"),
411            Selector::FootnoteRef => write!(f, ".footnote_ref"),
412            Selector::Html => write!(f, ".html"),
413            Selector::Image => write!(f, ".image"),
414            Selector::ImageRef => write!(f, ".image_ref"),
415            Selector::MdxJsxTextElement => write!(f, ".mdx_jsx_text_element"),
416            Selector::Link => write!(f, ".link"),
417            Selector::LinkRef => write!(f, ".link_ref"),
418            Selector::WikiLink => write!(f, ".wikilink"),
419            Selector::Callout => write!(f, ".callout"),
420            Selector::Embed => write!(f, ".embed"),
421            Selector::Strong => write!(f, ".strong"),
422            Selector::Code => write!(f, ".code"),
423            Selector::Math => write!(f, ".math"),
424            Selector::Table(None, None) => write!(f, ".table"),
425            Selector::Table(Some(row), None) => write!(f, ".[{}][]", row),
426            Selector::Table(Some(row), Some(col)) => write!(f, ".[{}][{}]", row, col),
427            Selector::Table(None, Some(col)) => write!(f, ".[][{}]", col),
428            Selector::TableAlign => write!(f, ".table_align"),
429            Selector::Text => write!(f, ".text"),
430            Selector::HorizontalRule => write!(f, ".horizontal_rule"),
431            Selector::Definition => write!(f, ".definition"),
432            Selector::MdxFlowExpression => write!(f, ".mdx_flow_expression"),
433            Selector::MdxTextExpression => write!(f, ".mdx_text_expression"),
434            Selector::MdxJsEsm => write!(f, ".mdx_js_esm"),
435            Selector::MdxJsxFlowElement => write!(f, ".mdx_jsx_flow_element"),
436            Selector::Recursive => write!(f, ".."),
437            Selector::Task => write!(f, ".task"),
438            Selector::Todo => write!(f, ".todo"),
439            Selector::Done => write!(f, ".done"),
440            Selector::Attr(attr) => write!(f, "{}", attr),
441            Selector::Property(property) => property.resolve_with(|s| write!(f, ".\"{}\"", escape_property_key(s))),
442        }
443    }
444}
445
446impl Selector {
447    /// Returns `true` if this is an attribute selector.
448    pub fn is_attribute_selector(&self) -> bool {
449        matches!(self, Selector::Attr(_))
450    }
451
452    /// Returns the selector as a string without a leading dot.
453    pub fn name(&self) -> String {
454        self.to_string().trim_start_matches('.').to_string()
455    }
456}
457
458#[cfg(test)]
459mod tests {
460    use crate::{
461        ArenaId, Position, Range, Token, TokenKind,
462        selector::{AttrKind, Selector, UnknownSelector},
463    };
464    use rstest::rstest;
465    use smol_str::SmolStr;
466
467    #[rstest]
468    // Heading selectors
469    #[case::heading(".h", Selector::Heading(None), ".h")]
470    #[case::heading_h1(".h1", Selector::Heading(Some(1)), ".h1")]
471    #[case::heading_h2(".h2", Selector::Heading(Some(2)), ".h2")]
472    #[case::heading_h3(".h3", Selector::Heading(Some(3)), ".h3")]
473    #[case::heading_h4(".h4", Selector::Heading(Some(4)), ".h4")]
474    #[case::heading_h5(".h5", Selector::Heading(Some(5)), ".h5")]
475    #[case::heading_h6(".h6", Selector::Heading(Some(6)), ".h6")]
476    // Blockquote
477    #[case::blockquote(".blockquote", Selector::Blockquote, ".blockquote")]
478    #[case::blockquote_alias(".>", Selector::Blockquote, ".blockquote")]
479    // Footnote
480    #[case::footnote(".footnote", Selector::Footnote, ".footnote")]
481    #[case::footnote_alias(".^", Selector::Footnote, ".footnote")]
482    // MDX JSX Flow Element
483    #[case::mdx_jsx_flow_element(".mdx_jsx_flow_element", Selector::MdxJsxFlowElement, ".mdx_jsx_flow_element")]
484    #[case::mdx_jsx_flow_element_alias(".<", Selector::MdxJsxFlowElement, ".mdx_jsx_flow_element")]
485    // Emphasis
486    #[case::emphasis(".emphasis", Selector::Emphasis, ".emphasis")]
487    #[case::emphasis_alias(".**", Selector::Emphasis, ".emphasis")]
488    // Math
489    #[case::math(".math", Selector::Math, ".math")]
490    #[case::math_alias(".$$", Selector::Math, ".math")]
491    // Horizontal Rule
492    #[case::horizontal_rule(".horizontal_rule", Selector::HorizontalRule, ".horizontal_rule")]
493    #[case::horizontal_rule_alias_hr(".hr", Selector::HorizontalRule, ".horizontal_rule")]
494    #[case::horizontal_rule_alias_dash(".---", Selector::HorizontalRule, ".horizontal_rule")]
495    #[case::horizontal_rule_alias_star(".***", Selector::HorizontalRule, ".horizontal_rule")]
496    #[case::horizontal_rule_alias_underscore(".___", Selector::HorizontalRule, ".horizontal_rule")]
497    // MDX Text Expression
498    #[case::mdx_text_expression(".mdx_text_expression", Selector::MdxTextExpression, ".mdx_text_expression")]
499    #[case::mdx_text_expression_alias(".{}", Selector::MdxTextExpression, ".mdx_text_expression")]
500    // Footnote Reference
501    #[case::footnote_ref(".footnote_ref", Selector::FootnoteRef, ".footnote_ref")]
502    #[case::footnote_ref_alias(".[^]", Selector::FootnoteRef, ".footnote_ref")]
503    // Definition
504    #[case::definition(".definition", Selector::Definition, ".definition")]
505    // Break
506    #[case::break_selector(".break", Selector::Break, ".break")]
507    #[case::break_alias_br(".br", Selector::Break, ".break")]
508    // Delete
509    #[case::delete(".delete", Selector::Delete, ".delete")]
510    // HTML
511    #[case::html(".html", Selector::Html, ".html")]
512    #[case::html_alias(".<>", Selector::Html, ".html")]
513    // Image
514    #[case::image(".image", Selector::Image, ".image")]
515    // Image Reference
516    #[case::image_ref(".image_ref", Selector::ImageRef, ".image_ref")]
517    // Inline Code
518    #[case::code_inline(".code_inline", Selector::InlineCode, ".code_inline")]
519    #[case::inline_code_alias(".inline_code", Selector::InlineCode, ".code_inline")]
520    // Inline Math
521    #[case::math_inline(".math_inline", Selector::InlineMath, ".math_inline")]
522    #[case::inline_math_alias(".inline_math", Selector::InlineMath, ".math_inline")]
523    // Link
524    #[case::link(".link", Selector::Link, ".link")]
525    // Link Reference
526    #[case::link_ref(".link_ref", Selector::LinkRef, ".link_ref")]
527    // WikiLink
528    #[case::wikilink(".wikilink", Selector::WikiLink, ".wikilink")]
529    // List
530    #[case::list(".list", Selector::List(None, None), ".list")]
531    #[case::list_bracket(".[]", Selector::List(None, None), ".list")]
532    #[case::list_alias_li(".li", Selector::List(None, None), ".list")]
533    #[case::list_with_index(".[1]", Selector::List(Some(1), None), ".[1]")]
534    // Task List
535    #[case::task(".task", Selector::Task, ".task")]
536    #[case::task(".todo", Selector::Todo, ".todo")]
537    #[case::task(".done", Selector::Done, ".done")]
538    // TOML
539    #[case::toml(".toml", Selector::Toml, ".toml")]
540    // Strong
541    #[case::strong(".strong", Selector::Strong, ".strong")]
542    // YAML
543    #[case::yaml(".yaml", Selector::Yaml, ".yaml")]
544    // Code
545    #[case::code(".code", Selector::Code, ".code")]
546    #[case::code_block_alias(".code_block", Selector::Code, ".code")]
547    // MDX JS ESM
548    #[case::mdx_js_esm(".mdx_js_esm", Selector::MdxJsEsm, ".mdx_js_esm")]
549    // MDX JSX Text Element
550    #[case::mdx_jsx_text_element(".mdx_jsx_text_element", Selector::MdxJsxTextElement, ".mdx_jsx_text_element")]
551    // MDX Flow Expression
552    #[case::mdx_flow_expression(".mdx_flow_expression", Selector::MdxFlowExpression, ".mdx_flow_expression")]
553    // Text
554    #[case::text(".text", Selector::Text, ".text")]
555    #[case::text_alias_p(".p", Selector::Text, ".text")]
556    #[case::text_alias_paragraph(".paragraph", Selector::Text, ".text")]
557    // Table
558    #[case::table(".table", Selector::Table(None, None), ".table")]
559    #[case::table_bracket(".[][]", Selector::Table(None, None), ".table")]
560    #[case::table_row_any(".[1][]", Selector::Table(Some(1), None), ".[1][]")]
561    #[case::table_row_col(".[1][2]", Selector::Table(Some(1), Some(2)), ".[1][2]")]
562    #[case::table_any_col(".[][2]", Selector::Table(None, Some(2)), ".[][2]")]
563    // Table Align
564    #[case::table_align(".table_align", Selector::TableAlign, ".table_align")]
565    // Recursive
566    #[case::recursive("..", Selector::Recursive, "..")]
567    // Attribute selectors - Common
568    #[case::attr_value(".value", Selector::Attr(AttrKind::Value), ".value")]
569    #[case::attr_values(".values", Selector::Attr(AttrKind::Values), ".values")]
570    #[case::attr_children(".children", Selector::Attr(AttrKind::Children), ".children")]
571    // Attribute selectors - Code
572    #[case::attr_lang(".lang", Selector::Attr(AttrKind::Lang), ".lang")]
573    #[case::attr_meta(".meta", Selector::Attr(AttrKind::Meta), ".meta")]
574    #[case::attr_fence(".fence", Selector::Attr(AttrKind::Fence), ".fence")]
575    // Attribute selectors - Link/Image
576    #[case::attr_url(".url", Selector::Attr(AttrKind::Url), ".url")]
577    #[case::attr_alt(".alt", Selector::Attr(AttrKind::Alt), ".alt")]
578    #[case::attr_title(".title", Selector::Attr(AttrKind::Title), ".title")]
579    // Attribute selectors - Reference
580    #[case::attr_ident(".ident", Selector::Attr(AttrKind::Ident), ".ident")]
581    #[case::attr_label(".label", Selector::Attr(AttrKind::Label), ".label")]
582    // Attribute selectors - Heading
583    #[case::attr_depth(".depth", Selector::Attr(AttrKind::Depth), ".depth")]
584    #[case::attr_level(".level", Selector::Attr(AttrKind::Level), ".level")]
585    // Attribute selectors - List
586    #[case::attr_index(".index", Selector::Attr(AttrKind::Index), ".index")]
587    #[case::attr_ordered(".ordered", Selector::Attr(AttrKind::Ordered), ".ordered")]
588    #[case::attr_checked(".checked", Selector::Attr(AttrKind::Checked), ".checked")]
589    // Attribute selectors - TableCell
590    #[case::attr_column(".column", Selector::Attr(AttrKind::Column), ".column")]
591    #[case::attr_row(".row", Selector::Attr(AttrKind::Row), ".row")]
592    // Attribute selectors - TableHeader
593    #[case::attr_align(".align", Selector::Attr(AttrKind::Align), ".align")]
594    // Attribute selectors - MDX
595    #[case::attr_name(".name", Selector::Attr(AttrKind::Name), ".name")]
596    // Attribute selectors - Position
597    #[case::attr_line(".line", Selector::Attr(AttrKind::Line), ".line")]
598    #[case::attr_end_line(".end_line", Selector::Attr(AttrKind::EndLine), ".end_line")]
599    // Property selectors: quoted form (."key") – the only way to access dict keys
600    #[case::property_quoted_h1(".\"h1\"", Selector::Property("h1".into()), ".\"h1\"")]
601    #[case::property_quoted_url(".\"url\"", Selector::Property("url".into()), ".\"url\"")]
602    #[case::property_quoted_with_space(".\"my key\"", Selector::Property("my key".into()), ".\"my key\"")]
603    #[case::property_quoted_escaped_quote(".\"my\\\"key\"", Selector::Property("my\"key".into()), ".\"my\\\"key\"")]
604    #[case::property_quoted_escaped_backslash(".\"my\\\\key\"", Selector::Property("my\\key".into()), ".\"my\\\\key\"")]
605    #[case::property_quoted_empty(".\"\"", Selector::Property("".into()), ".\"\"")]
606    fn test_selector_try_from_and_display(
607        #[case] input: &str,
608        #[case] expected_selector: Selector,
609        #[case] expected_display: &str,
610    ) {
611        // Test TryFrom
612        let selector = Selector::try_from(&Token {
613            kind: TokenKind::Selector(SmolStr::new(input)),
614            range: Range {
615                start: Position::new(0, 0),
616                end: Position::new(0, 0),
617            },
618            module_id: ArenaId::new(0),
619        })
620        .expect("Should parse valid selector");
621        assert_eq!(selector, expected_selector);
622
623        // Test Display
624        assert_eq!(selector.to_string(), expected_display);
625    }
626
627    #[rstest]
628    #[case(".")]
629    #[case(".mykey")]
630    #[case(".my_key")]
631    #[case(".unknown")]
632    #[case(".hedaing")]
633    fn test_selector_try_from_invalid(#[case] input: &str) {
634        let token = Token {
635            kind: TokenKind::Selector(SmolStr::new(input)),
636            range: Range {
637                start: Position::new(0, 0),
638                end: Position::new(0, 0),
639            },
640            module_id: ArenaId::new(0),
641        };
642        let result = Selector::try_from(&token);
643        assert!(result.is_err());
644        if let Err(e) = result {
645            assert_eq!(e, UnknownSelector(token));
646        }
647    }
648}