typst-ide 0.15.1

IDE functionality for Typst.
Documentation
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
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
use std::fmt::Write;

use ecow::{EcoString, eco_format};
use typst::engine::Sink;
use typst::foundations::{
    AsOutput, Capturer, CastInfo, Func, ParamInfo, Repr, Value, repr,
};
use typst::layout::Length;
use typst::syntax::ast::AstNode;
use typst::syntax::{LinkedNode, Side, Source, SyntaxKind, ast};
use typst::utils::{Numeric, round_with_precision};
use typst_eval::CapturesVisitor;

use crate::analyze::analyze_expr_with_fallback;
use crate::docs::{find_param_docs, find_value_docs};
use crate::utils::summarize_font_family;
use crate::{IdeWorld, analyze_expr, analyze_import, analyze_labels};

/// Describe the item under the cursor.
///
/// Passing a `document` (from a previous compilation) is optional, but enhances
/// the tooltips. Label tooltips, for instance, are only generated when the
/// document is available.
pub fn tooltip(
    world: &dyn IdeWorld,
    output: Option<impl AsOutput>,
    source: &Source,
    cursor: usize,
    side: Side,
) -> Option<Tooltip> {
    let leaf = LinkedNode::new(source.root()).leaf_at(cursor, side)?;
    if leaf.kind().is_trivia() {
        return None;
    }

    named_param_tooltip(world, &leaf)
        .or_else(|| font_tooltip(world, &leaf))
        .or_else(|| output.and_then(|output| label_tooltip(output, &leaf)))
        .or_else(|| import_tooltip(world, &leaf))
        .or_else(|| expr_tooltip(world, &leaf))
        .or_else(|| closure_tooltip(&leaf))
}

/// A hover tooltip.
#[derive(Debug, Clone, PartialEq)]
pub enum Tooltip {
    /// A string of text.
    Text(EcoString),
    /// A string of Typst code.
    Code(EcoString),
}

/// Tooltip for a hovered expression.
fn expr_tooltip(world: &dyn IdeWorld, leaf: &LinkedNode) -> Option<Tooltip> {
    let mut ancestor = leaf;
    while !ancestor.is::<ast::Expr>() {
        ancestor = ancestor.parent()?;
    }

    let expr = ancestor.cast::<ast::Expr>()?;
    // We only analyze embeddable code expressions or math expressions that
    // access variables.
    let analyze = expr.hash()
        || matches!(
            expr,
            ast::Expr::MathIdent(_)
                | ast::Expr::MathFieldAccess(_)
                | ast::Expr::MathCall(_)
        );
    if !analyze {
        return None;
    }

    let values = analyze_expr(world, ancestor);

    if let [(value, _), rest @ ..] = values.as_slice()
        && rest.iter().all(|(v, _)| value == v)
    {
        if let Some(docs) = find_value_docs(world, value) {
            return Some(Tooltip::Text(docs.summary()));
        }

        if let &Value::Length(length) = value
            && let Some(tooltip) = length_tooltip(length)
        {
            return Some(tooltip);
        }
    }

    if expr.is_literal() {
        return None;
    }

    let mut last = None;
    let mut pieces: Vec<EcoString> = vec![];
    let mut iter = values.iter();
    for (value, _) in (&mut iter).take(Sink::MAX_VALUES - 1) {
        if let Some((prev, count)) = &mut last {
            if *prev == value {
                *count += 1;
                continue;
            } else if *count > 1 {
                write!(pieces.last_mut().unwrap(), " (×{count})").unwrap();
            }
        }
        pieces.push(value.repr());
        last = Some((value, 1));
    }

    if let Some((_, count)) = last
        && count > 1
    {
        write!(pieces.last_mut().unwrap(), " (×{count})").unwrap();
    }

    if iter.next().is_some() {
        pieces.push("...".into());
    }

    let tooltip = repr::pretty_comma_list(&pieces, false);
    (!tooltip.is_empty()).then(|| Tooltip::Code(tooltip.into()))
}

/// Tooltips for imports.
fn import_tooltip(world: &dyn IdeWorld, leaf: &LinkedNode) -> Option<Tooltip> {
    if leaf.kind() == SyntaxKind::Star
        && let Some(parent) = leaf.parent()
        && let Some(import) = parent.cast::<ast::ModuleImport>()
        && let Some(node) = parent.find(import.source().span())
        && let Some(value) = analyze_import(world, &node)
        && let Some(scope) = value.scope()
    {
        let names: Vec<_> =
            scope.iter().map(|(name, ..)| eco_format!("`{name}`")).collect();
        let list = repr::separated_list(&names, "and");
        return Some(Tooltip::Text(eco_format!("This star imports {list}")));
    }

    None
}

/// Tooltip for a hovered closure.
fn closure_tooltip(leaf: &LinkedNode) -> Option<Tooltip> {
    // Only show this tooltip when hovering over the equals sign or arrow of
    // the closure. Showing it across the whole subtree is too noisy.
    if !matches!(leaf.kind(), SyntaxKind::Eq | SyntaxKind::Arrow) {
        return None;
    }

    // Find the closure to analyze.
    let parent = leaf.parent()?;
    if parent.kind() != SyntaxKind::Closure {
        return None;
    }

    // Analyze the closure's captures.
    let mut visitor = CapturesVisitor::new(None, Capturer::Function);
    visitor.visit(parent);

    let captures = visitor.finish();
    let mut names: Vec<_> =
        captures.iter().map(|(name, ..)| eco_format!("`{name}`")).collect();
    if names.is_empty() {
        return None;
    }

    names.sort();

    let tooltip = repr::separated_list(&names, "and");
    Some(Tooltip::Text(eco_format!("This closure captures {tooltip}")))
}

/// Tooltip text for a hovered length.
fn length_tooltip(length: Length) -> Option<Tooltip> {
    length.em.is_zero().then(|| {
        Tooltip::Code(eco_format!(
            "{}pt = {}mm = {}cm = {}in",
            round_with_precision(length.abs.to_pt(), 2),
            round_with_precision(length.abs.to_mm(), 2),
            round_with_precision(length.abs.to_cm(), 2),
            round_with_precision(length.abs.to_inches(), 2),
        ))
    })
}

/// Tooltip for a hovered reference or label.
fn label_tooltip(output: impl AsOutput, leaf: &LinkedNode) -> Option<Tooltip> {
    let target = match leaf.kind() {
        SyntaxKind::RefMarker => leaf.leaf_text().trim_start_matches('@'),
        SyntaxKind::Label => {
            leaf.leaf_text().trim_start_matches('<').trim_end_matches('>')
        }
        _ => return None,
    };

    for (label, detail) in analyze_labels(output).0 {
        if label.resolve().as_str() == target {
            return Some(Tooltip::Text(detail?));
        }
    }

    None
}

/// Tooltips for components of a named parameter.
fn named_param_tooltip(world: &dyn IdeWorld, leaf: &LinkedNode) -> Option<Tooltip> {
    let (func, named) =
        // Ensure that we are in a named pair in the arguments to a function
        // call or set rule.
        if let Some(parent) = leaf.parent()
        && let Some(named) = parent.cast::<ast::Named>()
        && let Some(grand) = parent.parent()
        && matches!(grand.kind(), SyntaxKind::Args | SyntaxKind::MathArgs)
        && let Some(grand_grand) = grand.parent()
        && let Some(expr) = grand_grand.cast::<ast::Expr>()
        && let Some(callee_span) = match expr {
            ast::Expr::FuncCall(call) => Some(call.callee().span()),
            ast::Expr::MathCall(call) => Some(call.callee().span()),
            ast::Expr::SetRule(set) => Some(set.target().span()),
            _ => None,
        }
        && let Some(callee) = grand_grand.find(callee_span)

        // Find metadata about the function.
        && let Some(value) = analyze_expr_with_fallback(world, &callee)
        && let Ok(func) = value.cast::<Func>()
         { (func, named) }
        else { return None; };

    // Hovering over the parameter name.
    if leaf.index() == 0
        && let Some(ident) = leaf.cast::<ast::Ident>()
        && let Some(param) = func.param(&ident)
        && let Some(docs) = find_param_docs(world, &param)
    {
        return Some(Tooltip::Text(docs.summary()));
    }

    // Hovering over a string parameter value.
    if let Some(string) = leaf.cast::<ast::Str>()
        && let Some(param) = func.param(&named.name())
        && let ParamInfo::Native(param) = param
        && let Some(docs) = find_string_doc(&param.input, &string.get())
    {
        return Some(Tooltip::Text(docs.into()));
    }

    None
}

/// Find documentation for a castable string.
fn find_string_doc(info: &CastInfo, string: &str) -> Option<&'static str> {
    match info {
        CastInfo::Value(Value::Str(s), docs) if s.as_str() == string => Some(docs),
        CastInfo::Union(options) => {
            options.iter().find_map(|option| find_string_doc(option, string))
        }
        _ => None,
    }
}

/// Tooltip for font.
fn font_tooltip(world: &dyn IdeWorld, leaf: &LinkedNode) -> Option<Tooltip> {
    // Ensure that we are on top of a string.
    if let Some(string) = leaf.cast::<ast::Str>()
        && let lower = string.get().to_lowercase()

        // Ensure that we are in the arguments to the text function.
        && let Some(parent) = leaf.parent()
        && let Some(named) = parent.cast::<ast::Named>()
        && named.name().as_str() == "font"

        // Find the font family.
        && let book = world.book()
        && let Some((_, iter)) = book
            .families()
            .find(|&(family, _)| family.to_lowercase().as_str() == lower.as_str())
    {
        let detail = summarize_font_family(iter.filter_map(|id| book.info(id)));
        return Some(Tooltip::Text(detail));
    }

    None
}

#[cfg(test)]
mod tests {
    use std::borrow::Borrow;

    use typst::syntax::Side;
    use typst_layout::PagedDocument;

    use super::{Tooltip, tooltip};
    use crate::tests::{FilePos, TestWorld, WorldLike};

    type Response = Option<Tooltip>;

    trait ResponseExt {
        /// Assert that there is no tooltip.
        fn must_be_none(&self) -> &Self;
        /// Assert that the tooltip equals the given message.
        fn must_be_text(&self, text: &str) -> &Self;
        /// Assert that the tooltip equals the given code.
        fn must_be_code(&self, code: &str) -> &Self;
    }

    impl ResponseExt for Response {
        #[track_caller]
        fn must_be_none(&self) -> &Self {
            assert_eq!(*self, None);
            self
        }

        #[track_caller]
        fn must_be_text(&self, text: &str) -> &Self {
            assert_eq!(*self, Some(Tooltip::Text(text.into())));
            self
        }

        #[track_caller]
        fn must_be_code(&self, code: &str) -> &Self {
            assert_eq!(*self, Some(Tooltip::Code(code.into())));
            self
        }
    }

    #[track_caller]
    fn test(world: impl WorldLike, pos: impl FilePos, side: Side) -> Response {
        let world = world.acquire();
        let world = world.borrow();
        let (source, cursor) = pos.resolve(world);
        let doc = typst::compile::<PagedDocument>(world).output.ok();
        tooltip(world, doc.as_ref(), &source, cursor, side)
    }

    #[test]
    fn test_tooltip() {
        test("#let x = 1 + 2", -1, Side::After).must_be_none();
        test("#let x = 1 + 2", 5, Side::After).must_be_code("3");
        test("#let x = 1 + 2", 6, Side::Before).must_be_code("3");
    }

    /// Literal values don't get a tooltip, just idenfitifers.
    #[test]
    fn test_tooltip_math_literals() {
        let world = "$x'^2 &!= \\u{3C0} \"is\" pi #true$";
        test(world, 0 /*  $  */, Side::After).must_be_none();
        test(world, 1 /*  x  */, Side::After).must_be_none();
        test(world, 2 /*  '  */, Side::After).must_be_none();
        test(world, 3 /*  ^  */, Side::After).must_be_none();
        test(world, 4 /*  2  */, Side::After).must_be_none();
        test(world, 5 /*     */, Side::After).must_be_none();
        test(world, 6 /*  &  */, Side::After).must_be_none();
        test(world, 7 /*  != */, Side::After).must_be_none();
        test(world, 10 /* \\ */, Side::After).must_be_none();
        test(world, 11 /* u  */, Side::After).must_be_none();
        test(world, 12 /* {  */, Side::After).must_be_none();
        test(world, 13 /* 3  */, Side::After).must_be_none();
        test(world, 19 /* \" */, Side::After).must_be_none();
        test(world, 20 /* is */, Side::After).must_be_none();
        test(world, 24 /* pi */, Side::After)
            .must_be_code("symbol(\"Ï€\", (\"alt\", \"Ï–\"))");
        test(world, 27 /* \# */, Side::After).must_be_none();
        test(world, 28 /*true*/, Side::After).must_be_none();
    }

    #[test]
    fn test_tooltip_math_field_access() {
        test("$pi.alt$", 1, Side::After).must_be_code("symbol(\"Ï€\", (\"alt\", \"Ï–\"))");
        test("$pi.alt$", 3, Side::After).must_be_code("symbol(\"Ï–\")");
        test("$pi.alt$", 4, Side::After).must_be_code("symbol(\"Ï–\")");
    }

    #[test]
    fn test_tooltip_set() {
        let box_desc = "An inline-level container that sizes content.";
        let fill_desc = "The box's background color.";
        let red = "rgb(\"#ff4136\")";
        test("#set box(fill: red,)", 0 /*#*/, Side::After).must_be_none();
        test("#set box(fill: red,)", 1 /*s*/, Side::After).must_be_none();
        test("#set box(fill: red,)", 5 /*b*/, Side::After).must_be_text(box_desc);
        test("#set box(fill: red,)", 8 /*(*/, Side::After).must_be_none();
        test("#set box(fill: red,)", 9 /*f*/, Side::After).must_be_text(fill_desc);
        test("#set box(fill: red,)", 13 /*:*/, Side::After).must_be_none();
        test("#set box(fill: red,)", 15 /*r*/, Side::After).must_be_code(red);
        test("#set box(fill: red,)", 18 /*,*/, Side::After).must_be_none();
        test("#set box(fill: red,)", 19 /*)*/, Side::After).must_be_none();
    }

    #[test]
    fn test_tooltip_function_call() {
        let box_desc = "An inline-level container that sizes content.";
        // Function value
        test("#box", 0 /*#*/, Side::After).must_be_none();
        test("#box", 1 /*b*/, Side::After).must_be_text(box_desc);
        test("#(box)", 0 /*#*/, Side::After).must_be_none();
        test("#(box)", 1 /*(*/, Side::After).must_be_text(box_desc);
        test("#(box)", 2 /*b*/, Side::After).must_be_text(box_desc);
        test("#(box)", 5 /*)*/, Side::After).must_be_text(box_desc);
        // Basic call
        test("#box()", 1 /*b*/, Side::After).must_be_text(box_desc);
        test("#box()", 4 /*(*/, Side::After).must_be_code("box()");
        test("#box()", 5 /*)*/, Side::After).must_be_code("box()");
        // Field access call
        test("#std.box()", 1 /*s*/, Side::After).must_be_code("<module global>");
        test("#std.box()", 4 /*.*/, Side::After).must_be_text(box_desc);
        test("#std.box()", 5 /*b*/, Side::After).must_be_text(box_desc);
        test("#std.box()", 8 /*(*/, Side::After).must_be_code("box()");
        // Positional args and trailing comma
        test("#box([],)", 4 /*(*/, Side::After).must_be_code("box(body: [])");
        test("#box([],)", 5 /*[*/, Side::After).must_be_code("[]");
        test("#box([],)", 6 /*]*/, Side::After).must_be_code("[]");
        test("#box([],)", 7 /*,*/, Side::After).must_be_code("box(body: [])");
        test("#box([],)", 8 /*)*/, Side::After).must_be_code("box(body: [])");
        // Content args
        test("#box[]", 4 /*[*/, Side::After).must_be_code("[]");
        test("#box[]", 5 /*]*/, Side::After).must_be_code("[]");
        // Named args
        let fill_desc = "The box's background color.";
        let red_box = "box(fill: rgb(\"#ff4136\"))";
        test("#box(fill:red,)", 5 /*f*/, Side::After).must_be_text(fill_desc);
        test("#box(fill:red,)", 9 /*:*/, Side::After).must_be_code(red_box);
        test("#box(fill:red,)", 10 /*r*/, Side::After).must_be_code("rgb(\"#ff4136\")");
        test("#box(fill:red,)", 13 /*,*/, Side::After).must_be_code(red_box);
        // Spread args
        test("#box(..none,)", 5 /*.*/, Side::After).must_be_code("box()");
        test("#box(..none,)", 7 /*(*/, Side::After).must_be_none();
        test("#box(..none,)", 11 /*,*/, Side::After).must_be_code("box()");
        test("#box(..([],))", 5 /*.*/, Side::After).must_be_code("box(body: [])");
        test("#box(..([],))", 7 /*(*/, Side::After).must_be_code("([],)");
    }

    #[test]
    fn test_tooltip_math_function_call() {
        // Content plus parens
        test("$f(x)$", 1 /*f*/, Side::After).must_be_none();
        test("$f(x)$", 2 /*(*/, Side::After).must_be_none();
        test("$f(x)$", 3 /*x*/, Side::After).must_be_none();
        test("$sin()$", 1 /*s*/, Side::After)
            .must_be_code("op(text: [sin], limits: false)");
        // Actual function call + empty arg + trailing comma
        let vec_z = "vec(children: ([ℤ], []))";
        test("$vec(ZZ, ,)$", 1 /*v*/, Side::After).must_be_text("A column vector.");
        test("$vec(ZZ, ,)$", 4 /*(*/, Side::After).must_be_code(vec_z);
        test("$vec(ZZ, ,)$", 5 /*Z*/, Side::After).must_be_code("symbol(\"ℤ\")");
        test("$vec(ZZ, ,)$", 7 /*,*/, Side::After).must_be_code(vec_z);
        test("$vec(ZZ, ,)$", 8 /* */, Side::After).must_be_none();
        test("$vec(ZZ, ,)$", 9 /*,*/, Side::After).must_be_code(vec_z);
        test("$vec(ZZ, ,)$", 10 /*)*/, Side::After).must_be_code(vec_z);
        // Named args
        let vec_gap = "vec(gap: 0% + 1em, children: ())";
        test("$vec(gap:#1em)$", 5 /*g*/, Side::After)
            .must_be_text("The gap between elements.");
        test("$vec(gap:#1em)$", 8 /*:*/, Side::After).must_be_code(vec_gap);
        test("$vec(gap:#1em)$", 10 /*1*/, Side::After).must_be_none();
        // 2d args and spread args
        let mat = "mat(rows: (([1],), ([2],)))";
        test("$mat(1; ..#([2],))$", 1 /*m*/, Side::After).must_be_text("A matrix.");
        test("$mat(1; ..#([2],))$", 5 /*1*/, Side::After).must_be_none();
        test("$mat(1; ..#([2],))$", 6 /*;*/, Side::After).must_be_code(mat);
        test("$mat(1; ..#([2],))$", 8 /*.*/, Side::After).must_be_code(mat);
        test("$mat(1; ..#([2],))$", 10 /*#*/, Side::After).must_be_code(mat);
        test("$mat(1; ..#([2],))$", 11 /*(*/, Side::After).must_be_code("([2],)");
        // Symbol function and named arg
        test("$hat(i,size:#1em)$", 1, Side::After).must_be_code("symbol(\"^\")");
        test("$hat(i,size:#1em)$", 7, Side::After)
            .must_be_text("The size of the accent, relative to the width of the base.");
        // Field access call
        let box_desc = "An inline-level container that sizes content.";
        test("$std.box()$", 1 /*s*/, Side::After).must_be_code("<module global>");
        test("$std.box()$", 4 /*.*/, Side::After).must_be_text(box_desc);
        test("$std.box()$", 5 /*b*/, Side::After).must_be_text(box_desc);
        test("$std.box()$", 8 /*(*/, Side::After).must_be_code("box()");
    }

    #[test]
    fn test_tooltip_empty_contextual() {
        test("#{context}", -1, Side::Before).must_be_code("context()");
    }

    #[test]
    fn test_tooltip_closure() {
        test("#let f(x) = x + y", 11, Side::Before)
            .must_be_text("This closure captures `y`");
        // Same tooltip if `y` is defined first.
        test("#let y = 10; #let f(x) = x + y", 24, Side::Before)
            .must_be_text("This closure captures `y`");
        // Names are sorted.
        test("#let f(x) = x + y + z + a", 11, Side::Before)
            .must_be_text("This closure captures `a`, `y`, and `z`");
        // Names are de-duplicated.
        test("#let f(x) = x + y + z + y", 11, Side::Before)
            .must_be_text("This closure captures `y` and `z`");
        // With arrow syntax.
        test("#let f = (x) => x + y", 15, Side::Before)
            .must_be_text("This closure captures `y`");
        // No recursion with arrow syntax.
        test("#let f = (x) => x + y + f", 13, Side::After)
            .must_be_text("This closure captures `f` and `y`");
    }

    #[test]
    fn test_tooltip_import() {
        let world = TestWorld::new("#import \"other.typ\": a, b")
            .with_source("other.typ", "#let (a, b, c) = (1, 2, 3)");
        test(&world, -5, Side::After).must_be_code("1");
    }

    #[test]
    fn test_tooltip_star_import() {
        let world = TestWorld::new("#import \"other.typ\": *")
            .with_source("other.typ", "#let (a, b, c) = (1, 2, 3)");
        test(&world, -2, Side::Before).must_be_none();
        test(&world, -2, Side::After).must_be_text("This star imports `a`, `b`, and `c`");
    }

    #[test]
    fn test_tooltip_field_call() {
        let world = TestWorld::new("#import \"other.typ\"\n#other.f()")
            .with_source("other.typ", "#let f = (x) => 1");
        test(&world, -4, Side::After).must_be_code("(..) => ..");
    }

    #[test]
    fn test_tooltip_reference() {
        test("#figure(caption: [Hi])[]<f> @f", -1, Side::Before).must_be_text("Hi");
    }

    #[test]
    fn test_tooltip_user_function() {
        let world = TestWorld::new("#import \"lib.typ\"\n#lib.foo(none, tree: 2)")
            .with_source("lib.typ", crate::tests::EXAMPLE_CLOSURE);
        // Function itself.
        test(&world, -17, Side::After).must_be_text("A useful function.");
        // Named parameter.
        test(&world, -7, Side::After).must_be_text("Tree with three slashes.");
    }

    #[test]
    fn test_tooltip_user_function_in_math() {
        let world = TestWorld::new("#import \"lib.typ\"\n$lib.foo(none, tree: 2)$")
            .with_source("lib.typ", crate::tests::EXAMPLE_CLOSURE);
        // Function itself.
        test(&world, -18, Side::After).must_be_text("A useful function.");
        // Named parameter.
        test(&world, -8, Side::After).must_be_text("Tree with three slashes.");
    }
}