summaryrefslogtreecommitdiff
path: root/support/texlab/src/completion/latex/label.rs
blob: f8d74f4a224be727c37787298581646beaa127bd (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
156
use super::combinators::{self, ArgumentContext, Parameter};
use crate::completion::factory;
use crate::range::RangeExt;
use crate::syntax::*;
use crate::workspace::*;
use futures_boxed::boxed;
use lsp_types::*;
use std::sync::Arc;

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

impl FeatureProvider for LatexLabelCompletionProvider {
    type Params = CompletionParams;
    type Output = Vec<CompletionItem>;

    #[boxed]
    async fn execute<'a>(&'a self, request: &'a FeatureRequest<Self::Params>) -> Self::Output {
        let parameters = LANGUAGE_DATA
            .label_commands
            .iter()
            .filter(|cmd| cmd.kind.is_reference())
            .map(|cmd| Parameter::new(&cmd.name, cmd.index));

        combinators::argument(request, parameters, |context| {
            async move {
                let source = Self::find_source(&context);
                let mut items = Vec::new();
                for document in request.related_documents() {
                    let workspace = Arc::clone(&request.view.workspace);
                    let view = DocumentView::new(workspace, Arc::clone(&document));
                    let outline = Outline::from(&view);

                    if let SyntaxTree::Latex(tree) = &document.tree {
                        for label in tree
                            .structure
                            .labels
                            .iter()
                            .filter(|label| label.kind == LatexLabelKind::Definition)
                            .filter(|label| Self::is_included(tree, label, source))
                        {
                            let outline_context = OutlineContext::parse(&view, &label, &outline);
                            for name in label.names() {
                                let text = name.text().to_owned();
                                let text_edit = TextEdit::new(context.range, text.clone());
                                let item = factory::label(
                                    request,
                                    text,
                                    text_edit,
                                    outline_context.as_ref(),
                                );
                                items.push(item);
                            }
                        }
                    }
                }
                items
            }
        })
        .await
    }
}

impl LatexLabelCompletionProvider {
    fn find_source(context: &ArgumentContext) -> LatexLabelReferenceSource {
        match LANGUAGE_DATA
            .label_commands
            .iter()
            .find(|cmd| cmd.name == context.parameter.name && cmd.index == context.parameter.index)
            .map(|cmd| cmd.kind)
            .unwrap()
        {
            LatexLabelKind::Definition => unreachable!(),
            LatexLabelKind::Reference(source) => source,
        }
    }

    fn is_included(
        tree: &LatexSyntaxTree,
        label: &LatexLabel,
        source: LatexLabelReferenceSource,
    ) -> bool {
        match source {
            LatexLabelReferenceSource::Everything => true,
            LatexLabelReferenceSource::Math => tree
                .env
                .environments
                .iter()
                .filter(|env| env.left.is_math())
                .any(|env| env.range().contains_exclusive(label.start())),
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use lsp_types::Position;

    #[test]
    fn test_inside_of_ref() {
        let items = test_feature(
            LatexLabelCompletionProvider,
            FeatureSpec {
                files: vec![
                    FeatureSpec::file(
                        "foo.tex",
                        "\\addbibresource{bar.bib}\\include{baz}\n\\ref{}",
                    ),
                    FeatureSpec::file("bar.bib", ""),
                    FeatureSpec::file("baz.tex", "\\label{foo}\\label{bar}\\ref{baz}"),
                ],
                main_file: "foo.tex",
                position: Position::new(1, 5),
                ..FeatureSpec::default()
            },
        );
        let labels: Vec<&str> = items.iter().map(|item| item.label.as_ref()).collect();
        assert_eq!(labels, vec!["foo", "bar"]);
    }

    #[test]
    fn test_outside_of_ref() {
        let items = test_feature(
            LatexLabelCompletionProvider,
            FeatureSpec {
                files: vec![
                    FeatureSpec::file("foo.tex", "\\include{bar}\\ref{}"),
                    FeatureSpec::file("bar.tex", "\\label{foo}\\label{bar}"),
                ],
                main_file: "foo.tex",
                position: Position::new(1, 6),
                ..FeatureSpec::default()
            },
        );
        assert!(items.is_empty());
    }

    #[test]
    fn test_eqref() {
        let items = test_feature(
            LatexLabelCompletionProvider,
            FeatureSpec {
                files: vec![FeatureSpec::file(
                    "foo.tex",
                    "\\begin{align}\\label{foo}\\end{align}\\label{bar}\n\\eqref{}",
                )],
                main_file: "foo.tex",
                position: Position::new(1, 7),
                ..FeatureSpec::default()
            },
        );
        let labels: Vec<&str> = items.iter().map(|item| item.label.as_ref()).collect();
        assert_eq!(labels, vec!["foo"]);
    }
}