summaryrefslogtreecommitdiff
path: root/support/texlab/src/features/completion/label.rs
blob: e6c02db5652aa7c500b111d95de2b7693948f995 (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
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
use lsp_types::CompletionParams;
use rowan::{ast::AstNode, TextRange};

use crate::{
    features::{cursor::CursorContext, lsp_kinds::Structure},
    render_label,
    syntax::latex,
    LabelledObject,
};

use super::types::{InternalCompletionItem, InternalCompletionItemData};

pub fn complete_labels<'a>(
    context: &'a CursorContext<CompletionParams>,
    items: &mut Vec<InternalCompletionItem<'a>>,
) -> Option<()> {
    let (range, is_math) = find_reference(context).or_else(|| find_reference_range(context))?;

    for document in context.request.workspace.documents_by_uri.values() {
        if let Some(data) = document.data.as_latex() {
            for label in latex::SyntaxNode::new_root(data.green.clone())
                .descendants()
                .filter_map(latex::LabelDefinition::cast)
            {
                if let Some(name) = label
                    .name()
                    .and_then(|name| name.key())
                    .map(|name| name.to_string())
                {
                    match render_label(&context.request.workspace, &name, Some(label)) {
                        Some(rendered_label) => {
                            let kind = match &rendered_label.object {
                                LabelledObject::Section { .. } => Structure::Section,
                                LabelledObject::Float { .. } => Structure::Float,
                                LabelledObject::Theorem { .. } => Structure::Theorem,
                                LabelledObject::Equation => Structure::Equation,
                                LabelledObject::EnumItem => Structure::Item,
                            };

                            if is_math && kind != Structure::Equation {
                                continue;
                            }

                            let header = rendered_label.detail();
                            let footer = match &rendered_label.object {
                                LabelledObject::Float { caption, .. } => Some(caption.clone()),
                                _ => None,
                            };

                            let text = format!("{} {}", name, rendered_label.reference());

                            let item = InternalCompletionItem::new(
                                range,
                                InternalCompletionItemData::Label {
                                    name,
                                    kind,
                                    header,
                                    footer,
                                    text,
                                },
                            );
                            items.push(item);
                        }
                        None => {
                            let kind = Structure::Label;
                            let header = None;
                            let footer = None;
                            let text = name.to_string();
                            let item = InternalCompletionItem::new(
                                range,
                                InternalCompletionItemData::Label {
                                    name,
                                    kind,
                                    header,
                                    footer,
                                    text,
                                },
                            );
                            items.push(item);
                        }
                    }
                }
            }
        }
    }

    Some(())
}

fn find_reference(context: &CursorContext<CompletionParams>) -> Option<(TextRange, bool)> {
    let (_, range, group) = context.find_curly_group_word_list()?;
    let reference = latex::LabelReference::cast(group.syntax().parent()?)?;
    let is_math = reference.command()?.text() == "\\eqref";
    Some((range, is_math))
}

fn find_reference_range(context: &CursorContext<CompletionParams>) -> Option<(TextRange, bool)> {
    let (_, range, group) = context.find_curly_group_word()?;
    latex::LabelReferenceRange::cast(group.syntax().parent()?)?;
    Some((range, false))
}

#[cfg(test)]
mod tests {
    use rowan::TextRange;

    use crate::features::testing::FeatureTester;

    use super::*;

    #[test]
    fn test_empty_latex_document() {
        let request = FeatureTester::builder()
            .files(vec![("main.tex", "")])
            .main("main.tex")
            .line(0)
            .character(0)
            .build()
            .completion();

        let context = CursorContext::new(request);
        let mut actual_items = Vec::new();
        complete_labels(&context, &mut actual_items);

        assert!(actual_items.is_empty());
    }

    #[test]
    fn test_empty_bibtex_document() {
        let request = FeatureTester::builder()
            .files(vec![("main.bib", "")])
            .main("main.bib")
            .line(0)
            .character(0)
            .build()
            .completion();

        let context = CursorContext::new(request);
        let mut actual_items = Vec::new();
        complete_labels(&context, &mut actual_items);

        assert!(actual_items.is_empty());
    }

    #[test]
    fn test_simple() {
        let request = FeatureTester::builder()
            .files(vec![("main.tex", "\\ref{}\\label{foo}")])
            .main("main.tex")
            .line(0)
            .character(5)
            .build()
            .completion();

        let context = CursorContext::new(request);
        let mut actual_items = Vec::new();
        complete_labels(&context, &mut actual_items);

        assert!(!actual_items.is_empty());
        for item in actual_items {
            assert_eq!(item.range, TextRange::new(5.into(), 5.into()));
        }
    }

    #[test]
    fn test_simple_range() {
        let request = FeatureTester::builder()
            .files(vec![("main.tex", "\\crefrange{\n\\label{foo}")])
            .main("main.tex")
            .line(0)
            .character(11)
            .build()
            .completion();

        let context = CursorContext::new(request);
        let mut actual_items = Vec::new();
        complete_labels(&context, &mut actual_items);

        assert!(!actual_items.is_empty());
        for item in actual_items {
            assert_eq!(item.range, TextRange::new(11.into(), 11.into()));
        }
    }

    #[test]
    fn test_multi_word() {
        let request = FeatureTester::builder()
            .files(vec![("main.tex", "\\ref{foo}\\label{foo bar}")])
            .main("main.tex")
            .line(0)
            .character(8)
            .build()
            .completion();

        let context = CursorContext::new(request);
        let mut actual_items = Vec::new();
        complete_labels(&context, &mut actual_items);

        assert!(!actual_items.is_empty());
        for item in actual_items {
            assert_eq!(item.range, TextRange::new(5.into(), 8.into()));
        }
    }
}