summaryrefslogtreecommitdiff
path: root/support/texlab/src/hover/latex/citation.rs
blob: 8b5468e52e0a68c09424101d4745c6e1fc46bbf0 (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
use crate::{
    citeproc::render_citation,
    feature::{FeatureProvider, FeatureRequest},
    protocol::{Hover, HoverContents, RangeExt, TextDocumentPositionParams},
    syntax::{bibtex, Span, SyntaxNode},
    workspace::DocumentContent,
};
use async_trait::async_trait;
use log::warn;

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

#[async_trait]
impl FeatureProvider for LatexCitationHoverProvider {
    type Params = TextDocumentPositionParams;
    type Output = Option<Hover>;

    async fn execute<'a>(&'a self, req: &'a FeatureRequest<Self::Params>) -> Self::Output {
        let (tree, src_key, entry) = Self::get_entry(req)?;
        if entry.is_comment() {
            None
        } else {
            let key = entry.key.as_ref()?;
            match render_citation(&tree, key.text()) {
                Some(markdown) => Some(Hover {
                    contents: HoverContents::Markup(markdown),
                    range: Some(src_key.range()),
                }),
                None => {
                    warn!("Failed to render entry: {}", key.text());
                    None
                }
            }
        }
    }
}

impl LatexCitationHoverProvider {
    fn get_entry(
        req: &FeatureRequest<TextDocumentPositionParams>,
    ) -> Option<(&bibtex::Tree, &Span, &bibtex::Entry)> {
        let key = Self::get_key(req)?;
        for tree in req
            .related()
            .iter()
            .filter_map(|doc| doc.content.as_bibtex())
        {
            for entry in tree
                .children(tree.root)
                .filter_map(|node| tree.as_entry(node))
            {
                if let Some(current_key) = &entry.key {
                    if current_key.text() == key.text {
                        return Some((tree, key, entry));
                    }
                }
            }
        }
        None
    }

    fn get_key(req: &FeatureRequest<TextDocumentPositionParams>) -> Option<&Span> {
        match &req.current().content {
            DocumentContent::Latex(table) => table
                .citations
                .iter()
                .flat_map(|citation| citation.keys(&table))
                .find(|key| key.range().contains(req.params.position))
                .map(|token| &token.span),
            DocumentContent::Bibtex(tree) => tree
                .children(tree.root)
                .filter_map(|node| tree.as_entry(node))
                .filter_map(|entry| entry.key.as_ref())
                .find(|key| key.range().contains(req.params.position))
                .map(|token| &token.span),
        }
    }
}

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

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

        assert_eq!(actual_hover, None);
    }

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

        assert_eq!(actual_hover, None);
    }

    #[tokio::test]
    async fn inside_label() {
        let actual_hover = FeatureTester::new()
            .file(
                "main.bib",
                "@article{foo, author = {Foo Bar}, title = {Baz Qux}, year = 1337}",
            )
            .file(
                "main.tex",
                indoc!(
                    r#"
                        \addbibresource{main.bib}
                        \cite{foo}
                    "#
                ),
            )
            .main("main.tex")
            .position(1, 7)
            .test_position(LatexCitationHoverProvider)
            .await
            .unwrap();

        let expected_hover = Hover {
            contents: HoverContents::Markup(MarkupContent {
                kind: MarkupKind::Markdown,
                value: "Bar, F. (1337). *Baz Qux*.".into(),
            }),
            range: Some(Range::new_simple(1, 6, 1, 9)),
        };

        assert_eq!(actual_hover, expected_hover);
    }

    #[tokio::test]
    async fn inside_entry() {
        let actual_hover = FeatureTester::new()
            .file(
                "main.bib",
                "@article{foo, author = {Foo Bar}, title = {Baz Qux}, year = 1337}",
            )
            .file(
                "main.tex",
                indoc!(
                    r#"
                        \addbibresource{main.bib}
                        \cite{foo}
                    "#
                ),
            )
            .main("main.bib")
            .position(0, 11)
            .test_position(LatexCitationHoverProvider)
            .await
            .unwrap();

        let expected_hover = Hover {
            contents: HoverContents::Markup(MarkupContent {
                kind: MarkupKind::Markdown,
                value: "Bar, F. (1337). *Baz Qux*.".into(),
            }),
            range: Some(Range::new_simple(0, 9, 0, 12)),
        };

        assert_eq!(actual_hover, expected_hover);
    }
}