tinymist_query/analysis/completion/
typst_specific.rs

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
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
//! Completion by typst specific semantics, like `font`, `package`, `label`, or
//! `typst::foundations::Value`.

use typst::foundations::Symbol;

use super::*;
impl CompletionPair<'_, '_, '_> {
    /// Add completions for all font families.
    pub fn font_completions(&mut self) {
        let equation = self.cursor.before_window(25).contains("equation");
        for (family, iter) in self.worker.world().clone().book().families() {
            let detail = summarize_font_family(iter);
            if !equation || family.contains("Math") {
                self.value_completion(
                    None,
                    &Value::Str(family.into()),
                    false,
                    Some(detail.as_str()),
                );
            }
        }
    }

    /// Add completions for current font features.
    pub fn font_feature_completions(&mut self) {
        // todo: add me
    }

    /// Add completions for all available packages.
    pub fn package_completions(&mut self, all_versions: bool) {
        let w = self.worker.world().clone();
        let mut packages: Vec<_> = w
            .packages()
            .iter()
            .map(|(spec, desc)| (spec, desc.clone()))
            .collect();
        // local_packages to references and add them to the packages
        let local_packages_refs = self.worker.ctx.local_packages();
        packages.extend(
            local_packages_refs
                .iter()
                .map(|spec| (spec, Some(eco_format!("{} v{}", spec.name, spec.version)))),
        );

        packages.sort_by_key(|(spec, _)| (&spec.namespace, &spec.name, Reverse(spec.version)));
        if !all_versions {
            packages.dedup_by_key(|(spec, _)| (&spec.namespace, &spec.name));
        }
        for (package, description) in packages {
            self.value_completion(
                None,
                &Value::Str(format_str!("{package}")),
                false,
                description.as_deref(),
            );
        }
    }

    /// Add completions for raw block tags.
    pub fn raw_completions(&mut self) {
        for (name, mut tags) in RawElem::languages() {
            let lower = name.to_lowercase();
            if !tags.contains(&lower.as_str()) {
                tags.push(lower.as_str());
            }

            tags.retain(|tag| is_ident(tag));
            if tags.is_empty() {
                continue;
            }

            self.push_completion(Completion {
                kind: CompletionKind::Constant,
                label: name.into(),
                apply: Some(tags[0].into()),
                detail: Some(repr::separated_list(&tags, " or ").into()),
                ..Completion::default()
            });
        }
    }

    /// Add completions for labels and references.
    pub fn ref_completions(&mut self) {
        self.label_completions_(false, true);
    }

    /// Add completions for labels and references.
    pub fn label_completions(&mut self, only_citation: bool) {
        self.label_completions_(only_citation, false);
    }

    /// Add completions for labels and references.
    pub fn label_completions_(&mut self, only_citation: bool, ref_label: bool) {
        let Some(document) = self.worker.document else {
            return;
        };
        let (labels, split) = analyze_labels(document);

        let head = &self.cursor.text[..self.cursor.from];
        let at = head.ends_with('@');
        let open = !at && !head.ends_with('<');
        let close = !at && !self.cursor.after.starts_with('>');
        let citation = !at && only_citation;

        let (skip, take) = if at || ref_label {
            (0, usize::MAX)
        } else if citation {
            (split, usize::MAX)
        } else {
            (0, split)
        };

        for DynLabel {
            label,
            label_desc,
            detail,
            bib_title,
        } in labels.into_iter().skip(skip).take(take)
        {
            if !self.worker.seen_casts.insert(hash128(&label)) {
                continue;
            }
            let label: EcoString = label.resolve().as_str().into();
            let completion = Completion {
                kind: CompletionKind::Reference,
                apply: Some(eco_format!(
                    "{}{}{}",
                    if open { "<" } else { "" },
                    label.as_str(),
                    if close { ">" } else { "" }
                )),
                label: label.clone(),
                label_details: label_desc.clone(),
                filter_text: Some(label.clone()),
                detail: detail.clone(),
                ..Completion::default()
            };

            if let Some(bib_title) = bib_title {
                // Note that this completion re-uses the above `apply` field to
                // alter the `bib_title` to the corresponding label.
                self.push_completion(Completion {
                    kind: CompletionKind::Constant,
                    label: bib_title.clone(),
                    label_details: Some(label),
                    filter_text: Some(bib_title),
                    detail,
                    ..completion.clone()
                });
            }

            self.push_completion(completion);
        }
    }

    /// Add a completion for a specific value.
    pub fn value_completion(
        &mut self,
        label: Option<EcoString>,
        value: &Value,
        parens: bool,
        docs: Option<&str>,
    ) {
        self.value_completion_(
            value,
            ValueCompletionInfo {
                label,
                parens,
                label_details: None,
                docs,
                bound_self: false,
            },
        );
    }

    /// Add a completion for a specific value.
    pub fn value_completion_(&mut self, value: &Value, extras: ValueCompletionInfo) {
        let ValueCompletionInfo {
            label,
            parens,
            label_details,
            docs,
            bound_self,
        } = extras;

        // Prevent duplicate completions from appearing.
        if !self.worker.seen_casts.insert(hash128(&(&label, &value))) {
            return;
        }

        let at = label.as_deref().is_some_and(|field| !is_ident(field));
        let label = label.unwrap_or_else(|| value.repr());

        let detail = docs.map(Into::into).or_else(|| match value {
            Value::Symbol(symbol) => Some(symbol_detail(symbol.get())),
            Value::Func(func) => func.docs().map(plain_docs_sentence),
            Value::Type(ty) => Some(plain_docs_sentence(ty.docs())),
            v => {
                let repr = v.repr();
                (repr.as_str() != label).then_some(repr)
            }
        });
        let label_details = label_details.or_else(|| match value {
            Value::Symbol(s) => Some(symbol_label_detail(s.get())),
            _ => None,
        });

        let mut apply = None;
        if parens && matches!(value, Value::Func(_)) {
            let mode = self.cursor.leaf_mode();
            let ty = Ty::Value(InsTy::new(value.clone()));
            let kind_checker = CompletionKindChecker {
                symbols: HashSet::default(),
                functions: HashSet::from_iter([&ty]),
            };
            let mut fn_feat = FnCompletionFeat::default();
            // todo: unify bound self checking
            fn_feat.bound_self = bound_self;
            let fn_feat = fn_feat.check(kind_checker.functions.iter().copied());
            self.func_completion(mode, fn_feat, label, label_details, detail, parens);
            return;
        } else if at {
            apply = Some(eco_format!("at(\"{label}\")"));
        } else {
            let apply_label = &mut label.as_str();
            if apply_label.ends_with('"') && self.cursor.after.starts_with('"') {
                if let Some(trimmed) = apply_label.strip_suffix('"') {
                    *apply_label = trimmed;
                }
            }
            let from_before = slice_at(self.cursor.text, 0..self.cursor.from);
            if apply_label.starts_with('"') && from_before.ends_with('"') {
                if let Some(trimmed) = apply_label.strip_prefix('"') {
                    *apply_label = trimmed;
                }
            }

            if apply_label.len() != label.len() {
                apply = Some((*apply_label).into());
            }
        }

        self.push_completion(Completion {
            kind: value_to_completion_kind(value),
            label,
            apply,
            detail,
            label_details,
            ..Completion::default()
        });
    }

    pub fn symbol_completions(&mut self, label: EcoString, symbol: &Symbol) {
        let ch = symbol.get();
        let kind = CompletionKind::Symbol(ch);
        self.push_completion(Completion {
            kind,
            label: label.clone(),
            label_details: Some(symbol_label_detail(ch)),
            detail: Some(symbol_detail(ch)),
            ..Completion::default()
        });

        let is_stepless = self.cursor.ctx.analysis.completion_feat.is_stepless();
        if is_stepless {
            self.symbol_var_completions(symbol, Some(&label));
        }
    }

    pub fn symbol_var_completions(&mut self, symbol: &Symbol, prefix: Option<&str>) {
        for modifier in symbol.modifiers() {
            if let Ok(modified) = symbol.clone().modified(modifier) {
                let label = match &prefix {
                    Some(prefix) => eco_format!("{prefix}.{modifier}"),
                    None => modifier.into(),
                };

                self.symbol_completions(label, &modified);
            }
        }
    }
}

#[derive(Debug, Clone, Default)]
pub struct ValueCompletionInfo<'a> {
    pub label: Option<EcoString>,
    pub parens: bool,
    pub label_details: Option<EcoString>,
    pub docs: Option<&'a str>,
    pub bound_self: bool,
}