summaryrefslogtreecommitdiff
path: root/support/texlab/src/definition/latex_label.rs
blob: 5318982ccd9707dbadb094e1a3e321b010ebe32f (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
use crate::{
    feature::{DocumentView, FeatureProvider, FeatureRequest},
    outline::{Outline, OutlineContext, OutlineContextItem},
    protocol::{LocationLink, Options, RangeExt, TextDocumentPositionParams},
    symbol::build_section_tree,
    syntax::{latex, LatexLabelKind, SyntaxNode},
    workspace::DocumentContent,
};
use async_trait::async_trait;
use std::{path::Path, sync::Arc};

#[derive(Debug, PartialEq, Eq, Clone, Copy, Default)]
pub struct LatexLabelDefinitionProvider;

#[async_trait]
impl FeatureProvider for LatexLabelDefinitionProvider {
    type Params = TextDocumentPositionParams;
    type Output = Vec<LocationLink>;

    async fn execute<'a>(&'a self, req: &'a FeatureRequest<Self::Params>) -> Self::Output {
        let mut links = Vec::new();
        if let Some(reference) = Self::find_reference(req) {
            for doc in req.related() {
                let snapshot = Arc::clone(&req.view.snapshot);
                let view = DocumentView::analyze(
                    snapshot,
                    Arc::clone(&doc),
                    &req.options,
                    &req.current_dir,
                );
                Self::find_definitions(
                    &view,
                    &req.options,
                    &req.current_dir,
                    &reference,
                    &mut links,
                );
            }
        }
        links
    }
}

impl LatexLabelDefinitionProvider {
    fn find_reference(req: &FeatureRequest<TextDocumentPositionParams>) -> Option<&latex::Token> {
        if let DocumentContent::Latex(table) = &req.current().content {
            table
                .labels
                .iter()
                .flat_map(|label| label.names(&table))
                .find(|label| label.range().contains(req.params.position))
        } else {
            None
        }
    }

    fn find_definitions(
        view: &DocumentView,
        options: &Options,
        current_dir: &Path,
        reference: &latex::Token,
        links: &mut Vec<LocationLink>,
    ) {
        if let DocumentContent::Latex(table) = &view.current.content {
            let outline = Outline::analyze(view, options, current_dir);
            let section_tree = build_section_tree(view, table, options, current_dir);
            for label in &table.labels {
                if label.kind == LatexLabelKind::Definition {
                    let context = OutlineContext::parse(view, &outline, *label);
                    for name in label.names(&table) {
                        if name.text() == reference.text() {
                            let target_range = if let Some(OutlineContextItem::Section { .. }) =
                                context.as_ref().map(|ctx| &ctx.item)
                            {
                                section_tree
                                    .find(reference.text())
                                    .map(|sec| sec.full_range)
                            } else {
                                context.as_ref().map(|ctx| ctx.range)
                            };

                            links.push(LocationLink {
                                origin_selection_range: Some(reference.range()),
                                target_uri: view.current.uri.clone().into(),
                                target_range: target_range
                                    .unwrap_or_else(|| table[label.parent].range()),
                                target_selection_range: table[label.parent].range(),
                            });
                        }
                    }
                }
            }
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::{feature::FeatureTester, protocol::Range};
    use indoc::indoc;

    #[tokio::test]
    async fn empty_latex_document() {
        let actual_links = FeatureTester::new()
            .file("main.tex", "")
            .main("main.tex")
            .position(0, 0)
            .test_position(LatexLabelDefinitionProvider)
            .await;

        assert!(actual_links.is_empty());
    }

    #[tokio::test]
    async fn empty_bibtex_document() {
        let actual_links = FeatureTester::new()
            .file("main.bib", "")
            .main("main.bib")
            .position(0, 0)
            .test_position(LatexLabelDefinitionProvider)
            .await;

        assert!(actual_links.is_empty());
    }

    #[tokio::test]
    async fn unknown_context() {
        let actual_links = FeatureTester::new()
            .file("foo.tex", r#"\label{foo}"#)
            .file(
                "bar.tex",
                indoc!(
                    r#"
                        \begin{a}\begin{b}\label{foo}\end{b}\end{a}
                        \input{baz.tex}
                    "#
                ),
            )
            .file("baz.tex", r#"\ref{foo}"#)
            .main("baz.tex")
            .position(0, 5)
            .test_position(LatexLabelDefinitionProvider)
            .await;

        let expected_links = vec![LocationLink {
            origin_selection_range: Some(Range::new_simple(0, 5, 0, 8)),
            target_uri: FeatureTester::uri("bar.tex").into(),
            target_range: Range::new_simple(0, 18, 0, 29),
            target_selection_range: Range::new_simple(0, 18, 0, 29),
        }];

        assert_eq!(actual_links, expected_links);
    }
}