summaryrefslogtreecommitdiff
path: root/support/texlab/crates/completion/src/providers/label_def.rs
blob: a8966ed62ff4dcb21900f1b5e26f3bb61f355fa1 (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
use base_db::{
    semantics::{
        tex::{Label, LabelKind},
        Span,
    },
    util::queries::Object,
};
use rowan::ast::AstNode;
use rustc_hash::FxHashSet;
use syntax::latex;

use crate::{
    util::{find_curly_group_word, CompletionBuilder},
    CompletionParams,
};

pub fn complete_label_definitions<'a>(
    params: &'a CompletionParams<'a>,
    builder: &mut CompletionBuilder<'a>,
) -> Option<()> {
    let cursor = find_definition(params)?;

    let label_defs: FxHashSet<&str> = Label::find_all(&params.feature.project)
        .filter(|(_, label)| label.kind == LabelKind::Definition)
        .map(|(_, label)| label.name_text())
        .collect();

    let label_refs: FxHashSet<&str> = Label::find_all(&params.feature.project)
        .filter(|(_, label)| label.kind == LabelKind::Reference)
        .map(|(_, label)| label.name_text())
        .collect();

    for label in label_refs.difference(&label_defs) {
        let Some(score) = builder.matcher.score(label, &cursor.text) else {
            continue;
        };

        let data = crate::LabelData {
            name: label,
            header: None,
            footer: None,
            object: None,
            keywords: label.to_string(),
        };

        builder.items.push(crate::CompletionItem::new_simple(
            score,
            cursor.range,
            crate::CompletionItemData::Label(data),
        ));
    }

    Some(())
}

fn find_definition(params: &CompletionParams) -> Option<Span> {
    let (cursor, group) = find_curly_group_word(params)?;
    latex::LabelDefinition::cast(group.syntax().parent()?)?;
    Some(cursor)
}