typst_analyzer_analysis/hints/
handle.rs

1use regex::Regex;
2use tower_lsp::lsp_types::*;
3
4pub fn calculate_inlay_hints(doc: &str) -> Result<Vec<InlayHint>, anyhow::Error> {
5    let mut hints: Vec<InlayHint> = Vec::new();
6
7    // Regex to match any word within angle brackets and @word
8    let angle_brackets_re: Regex = Regex::new(r"<(\w+)>")?;
9    let at_word_re: Regex = Regex::new(r"@(\w+)")?;
10
11    doc.lines().enumerate().for_each(|(line_idx, line)| {
12        // Match words within angle brackets
13        angle_brackets_re.captures_iter(line).for_each(|cap| {
14            if let Some(matched_word) = cap.get(1) {
15                let start = cap.get(0).expect("msg").start();
16                hints.push(InlayHint {
17                    position: Position {
18                        line: line_idx as u32,
19                        character: start as u32 + 1,
20                    },
21                    label: InlayHintLabel::String("label".to_owned()),
22                    kind: Some(InlayHintKind::TYPE),
23                    text_edits: None,
24                    tooltip: Some(InlayHintTooltip::String(format!(
25                        "Suggested label for <{}>",
26                        matched_word.as_str()
27                    ))),
28                    padding_left: Some(true),
29                    padding_right: Some(true),
30                    data: None,
31                });
32            }
33        });
34
35        // Match @word patterns
36        at_word_re.captures_iter(line).for_each(|cap| {
37            if let Some(matched_word) = cap.get(1) {
38                let start = cap.get(0).expect("msg").start();
39                hints.push(InlayHint {
40                    position: Position {
41                        line: line_idx as u32,
42                        character: start as u32 + 1,
43                    },
44                    label: InlayHintLabel::String("reference".to_owned()),
45                    kind: Some(InlayHintKind::TYPE),
46                    text_edits: None,
47                    tooltip: Some(InlayHintTooltip::String(format!(
48                        "Reference for @{}",
49                        matched_word.as_str()
50                    ))),
51                    padding_left: Some(true),
52                    padding_right: Some(true),
53                    data: None,
54                });
55            }
56        });
57    });
58    Ok(hints)
59}