rustledger-lsp 0.21.0

Language Server Protocol implementation for Beancount
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
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
//! Signature help handler for directive syntax assistance.
//!
//! Provides syntax hints when typing beancount directives:
//! - After date: shows available directive types
//! - After directive keyword: shows expected parameters

use lsp_types::{
    Documentation, MarkupContent, MarkupKind, ParameterInformation, ParameterLabel, SignatureHelp,
    SignatureHelpParams, SignatureInformation,
};

use super::utils::PositionEncoding;

/// Trigger characters for signature help.
pub const TRIGGER_CHARACTERS: &[&str] = &[" ", "*", "!"];

/// Handle a signature help request.
pub fn handle_signature_help(
    params: &SignatureHelpParams,
    source: &str,
    encoding: PositionEncoding,
) -> Option<SignatureHelp> {
    let position = params.text_document_position_params.position;
    let line_idx = position.line as usize;
    let lines: Vec<&str> = source.lines().collect();
    let line = lines.get(line_idx)?;

    // Map `position.character` (in the negotiated encoding) to a
    // byte offset into `line`. Walks chars once; `len_utf8` /
    // `len_utf16` per char dispatch is the only encoding-sensitive
    // step.
    let col = position.character as usize;
    let mut acc = 0usize;
    let mut byte_col = 0usize;
    for ch in line.chars() {
        if acc >= col {
            break;
        }
        let u = match encoding {
            PositionEncoding::Utf8 => ch.len_utf8(),
            PositionEncoding::Utf16 => ch.len_utf16(),
        };
        if acc + u > col {
            break;
        }
        acc += u;
        byte_col += ch.len_utf8();
    }
    let text_before = &line[..byte_col];

    // Detect what kind of signature help to show
    detect_signature_context(text_before)
}

/// Detect the signature context based on text before cursor.
fn detect_signature_context(text: &str) -> Option<SignatureHelp> {
    let trimmed = text.trim_start();

    // Check if we're after a date (YYYY-MM-DD pattern)
    if let Some(after_date) = extract_after_date(trimmed) {
        return signature_after_date(after_date);
    }

    // Check for specific directive patterns
    if trimmed.starts_with("option") {
        return signature_for_option(trimmed);
    }

    if trimmed.starts_with("include") {
        return signature_for_include(trimmed);
    }

    if trimmed.starts_with("plugin") {
        return signature_for_plugin(trimmed);
    }

    None
}

/// Extract text after a date pattern.
fn extract_after_date(text: &str) -> Option<&str> {
    // Match YYYY-MM-DD pattern
    if text.len() >= 10 {
        let potential_date = &text[..10];
        if potential_date.chars().enumerate().all(|(i, c)| match i {
            0..=3 | 5..=6 | 8..=9 => c.is_ascii_digit(),
            4 | 7 => c == '-',
            _ => false,
        }) {
            return Some(text[10..].trim_start());
        }
    }
    None
}

/// Signature help after a date - show available directives.
fn signature_after_date(after_date: &str) -> Option<SignatureHelp> {
    let after_date = after_date.trim_start();

    // Determine which signature to show based on what follows
    if after_date.is_empty() {
        // Just typed date + space, show all options
        return Some(SignatureHelp {
            signatures: vec![
                transaction_signature(),
                open_signature(),
                close_signature(),
                balance_signature(),
                pad_signature(),
                note_signature(),
                document_signature(),
                event_signature(),
                price_signature(),
                commodity_signature(),
            ],
            active_signature: Some(0),
            active_parameter: Some(0),
        });
    }

    // Transaction flag
    if after_date == "*" || after_date == "!" {
        return Some(SignatureHelp {
            signatures: vec![transaction_signature()],
            active_signature: Some(0),
            active_parameter: Some(1), // payee parameter
        });
    }

    // After flag + space
    if after_date.starts_with("* ") || after_date.starts_with("! ") {
        let rest = &after_date[2..];
        let param = if rest.is_empty() {
            1 // payee
        } else if rest.contains('"') && rest.matches('"').count() >= 2 {
            2 // narration
        } else {
            1 // still on payee
        };
        return Some(SignatureHelp {
            signatures: vec![transaction_signature()],
            active_signature: Some(0),
            active_parameter: Some(param),
        });
    }

    // "txn" keyword
    if after_date.starts_with("txn") {
        return Some(SignatureHelp {
            signatures: vec![transaction_signature()],
            active_signature: Some(0),
            active_parameter: Some(1),
        });
    }

    // "open" directive
    if let Some(rest) = after_date.strip_prefix("open") {
        let rest = rest.trim_start();
        let param = if rest.is_empty() {
            0 // account
        } else if rest.contains(' ') {
            1 // currencies
        } else {
            0
        };
        return Some(SignatureHelp {
            signatures: vec![open_signature()],
            active_signature: Some(0),
            active_parameter: Some(param),
        });
    }

    // "close" directive
    if after_date.starts_with("close") {
        return Some(SignatureHelp {
            signatures: vec![close_signature()],
            active_signature: Some(0),
            active_parameter: Some(0),
        });
    }

    // "balance" directive
    if let Some(rest) = after_date.strip_prefix("balance") {
        let rest = rest.trim_start();
        let param = if rest.is_empty() {
            0 // account
        } else if rest.contains(' ') {
            1 // amount
        } else {
            0
        };
        return Some(SignatureHelp {
            signatures: vec![balance_signature()],
            active_signature: Some(0),
            active_parameter: Some(param),
        });
    }

    // "pad" directive
    if let Some(rest) = after_date.strip_prefix("pad") {
        let rest = rest.trim_start();
        let spaces = rest.matches(' ').count();
        let param = spaces.min(1);
        return Some(SignatureHelp {
            signatures: vec![pad_signature()],
            active_signature: Some(0),
            active_parameter: Some(param as u32),
        });
    }

    // "note" directive
    if let Some(rest) = after_date.strip_prefix("note") {
        let rest = rest.trim_start();
        let param = if rest.is_empty() || !rest.contains(' ') {
            0 // account
        } else {
            1 // note text
        };
        return Some(SignatureHelp {
            signatures: vec![note_signature()],
            active_signature: Some(0),
            active_parameter: Some(param),
        });
    }

    // "document" directive
    if let Some(rest) = after_date.strip_prefix("document") {
        let rest = rest.trim_start();
        let param = if rest.is_empty() || !rest.contains(' ') {
            0 // account
        } else {
            1 // path
        };
        return Some(SignatureHelp {
            signatures: vec![document_signature()],
            active_signature: Some(0),
            active_parameter: Some(param),
        });
    }

    // "event" directive
    if let Some(rest) = after_date.strip_prefix("event") {
        let rest = rest.trim_start();
        let param = if rest.is_empty() || !rest.contains('"') {
            0 // type
        } else {
            1 // description
        };
        return Some(SignatureHelp {
            signatures: vec![event_signature()],
            active_signature: Some(0),
            active_parameter: Some(param),
        });
    }

    // "price" directive
    if let Some(rest) = after_date.strip_prefix("price") {
        let rest = rest.trim_start();
        // The active parameter is the number of COMPLETE tokens: a trailing
        // space means the previous token is finished and the cursor has advanced
        // to the next parameter. Counting tokens alone left `price AAPL ` on
        // param 0 (commodity) instead of advancing to 1 (amount).
        let tokens = rest.split_whitespace().count();
        let complete = if rest.is_empty() || rest.ends_with(char::is_whitespace) {
            tokens
        } else {
            tokens.saturating_sub(1)
        };
        let param = complete.min(2);
        return Some(SignatureHelp {
            signatures: vec![price_signature()],
            active_signature: Some(0),
            active_parameter: Some(param as u32),
        });
    }

    // "commodity" directive
    if after_date.starts_with("commodity") {
        return Some(SignatureHelp {
            signatures: vec![commodity_signature()],
            active_signature: Some(0),
            active_parameter: Some(0),
        });
    }

    None
}

/// Signature help for option directive.
fn signature_for_option(text: &str) -> Option<SignatureHelp> {
    let rest = &text[6..].trim_start(); // after "option"
    let param = if rest.is_empty() || !rest.contains('"') {
        0 // name
    } else {
        1 // value
    };

    Some(SignatureHelp {
        signatures: vec![SignatureInformation {
            label: "option \"name\" \"value\"".to_string(),
            documentation: Some(Documentation::MarkupContent(MarkupContent {
                kind: MarkupKind::Markdown,
                value: "Set a beancount option.\n\nCommon options:\n- `title`: Ledger title\n- `operating_currency`: Main currency\n- `booking_method`: FIFO, LIFO, etc.".to_string(),
            })),
            parameters: Some(vec![
                ParameterInformation {
                    label: ParameterLabel::Simple("\"name\"".to_string()),
                    documentation: Some(Documentation::String("Option name".to_string())),
                },
                ParameterInformation {
                    label: ParameterLabel::Simple("\"value\"".to_string()),
                    documentation: Some(Documentation::String("Option value".to_string())),
                },
            ]),
            active_parameter: None,
        }],
        active_signature: Some(0),
        active_parameter: Some(param),
    })
}

/// Signature help for include directive.
fn signature_for_include(_text: &str) -> Option<SignatureHelp> {
    Some(SignatureHelp {
        signatures: vec![SignatureInformation {
            label: "include \"path\"".to_string(),
            documentation: Some(Documentation::MarkupContent(MarkupContent {
                kind: MarkupKind::Markdown,
                value: "Include another beancount file.\n\nPaths are relative to the current file."
                    .to_string(),
            })),
            parameters: Some(vec![ParameterInformation {
                label: ParameterLabel::Simple("\"path\"".to_string()),
                documentation: Some(Documentation::String("Path to beancount file".to_string())),
            }]),
            active_parameter: None,
        }],
        active_signature: Some(0),
        active_parameter: Some(0),
    })
}

/// Signature help for plugin directive.
fn signature_for_plugin(text: &str) -> Option<SignatureHelp> {
    let rest = &text[6..].trim_start(); // after "plugin"
    let param = if rest.is_empty() || !rest.contains('"') {
        0 // name
    } else if rest.matches('"').count() >= 2 {
        1 // config
    } else {
        0
    };

    Some(SignatureHelp {
        signatures: vec![SignatureInformation {
            label: "plugin \"name\" [\"config\"]".to_string(),
            documentation: Some(Documentation::MarkupContent(MarkupContent {
                kind: MarkupKind::Markdown,
                value: "Load a beancount plugin.\n\nBuilt-in plugins include:\n- `auto_accounts`\n- `check_commodity`\n- `coherent_cost`".to_string(),
            })),
            parameters: Some(vec![
                ParameterInformation {
                    label: ParameterLabel::Simple("\"name\"".to_string()),
                    documentation: Some(Documentation::String("Plugin module name".to_string())),
                },
                ParameterInformation {
                    label: ParameterLabel::Simple("\"config\"".to_string()),
                    documentation: Some(Documentation::String("Optional plugin configuration".to_string())),
                },
            ]),
            active_parameter: None,
        }],
        active_signature: Some(0),
        active_parameter: Some(param),
    })
}

fn transaction_signature() -> SignatureInformation {
    SignatureInformation {
        label: "YYYY-MM-DD [*|!] [\"payee\"] \"narration\"".to_string(),
        documentation: Some(Documentation::MarkupContent(MarkupContent {
            kind: MarkupKind::Markdown,
            value: "Create a transaction.\n\n- `*` = completed\n- `!` = pending\n\nFollowed by posting lines.".to_string(),
        })),
        parameters: Some(vec![
            ParameterInformation {
                label: ParameterLabel::Simple("[*|!]".to_string()),
                documentation: Some(Documentation::String("Transaction flag (* = completed, ! = pending)".to_string())),
            },
            ParameterInformation {
                label: ParameterLabel::Simple("\"payee\"".to_string()),
                documentation: Some(Documentation::String("Optional payee name".to_string())),
            },
            ParameterInformation {
                label: ParameterLabel::Simple("\"narration\"".to_string()),
                documentation: Some(Documentation::String("Transaction description".to_string())),
            },
        ]),
        active_parameter: None,
    }
}

fn open_signature() -> SignatureInformation {
    SignatureInformation {
        label: "YYYY-MM-DD open Account [Currency,...]".to_string(),
        documentation: Some(Documentation::MarkupContent(MarkupContent {
            kind: MarkupKind::Markdown,
            value: "Open a new account.\n\nAccount format: `Type:Subtype:Name`\n\nTypes: Assets, Liabilities, Equity, Income, Expenses".to_string(),
        })),
        parameters: Some(vec![
            ParameterInformation {
                label: ParameterLabel::Simple("Account".to_string()),
                documentation: Some(Documentation::String("Account name (e.g., Assets:Bank:Checking)".to_string())),
            },
            ParameterInformation {
                label: ParameterLabel::Simple("[Currency,...]".to_string()),
                documentation: Some(Documentation::String("Optional allowed currencies".to_string())),
            },
        ]),
        active_parameter: None,
    }
}

fn close_signature() -> SignatureInformation {
    SignatureInformation {
        label: "YYYY-MM-DD close Account".to_string(),
        documentation: Some(Documentation::MarkupContent(MarkupContent {
            kind: MarkupKind::Markdown,
            value: "Close an account.\n\nPrevents further postings after this date.".to_string(),
        })),
        parameters: Some(vec![ParameterInformation {
            label: ParameterLabel::Simple("Account".to_string()),
            documentation: Some(Documentation::String("Account to close".to_string())),
        }]),
        active_parameter: None,
    }
}

fn balance_signature() -> SignatureInformation {
    SignatureInformation {
        label: "YYYY-MM-DD balance Account Amount Currency".to_string(),
        documentation: Some(Documentation::MarkupContent(MarkupContent {
            kind: MarkupKind::Markdown,
            value: "Assert an account balance.\n\nVerifies the account has the specified balance at the start of this date.".to_string(),
        })),
        parameters: Some(vec![
            ParameterInformation {
                label: ParameterLabel::Simple("Account".to_string()),
                documentation: Some(Documentation::String("Account to check".to_string())),
            },
            ParameterInformation {
                label: ParameterLabel::Simple("Amount Currency".to_string()),
                documentation: Some(Documentation::String("Expected balance (e.g., 1000.00 USD)".to_string())),
            },
        ]),
        active_parameter: None,
    }
}

fn pad_signature() -> SignatureInformation {
    SignatureInformation {
        label: "YYYY-MM-DD pad Account PadAccount".to_string(),
        documentation: Some(Documentation::MarkupContent(MarkupContent {
            kind: MarkupKind::Markdown,
            value: "Automatically pad an account.\n\nInserts a transaction to bring the account to the expected balance (used with balance assertions).".to_string(),
        })),
        parameters: Some(vec![
            ParameterInformation {
                label: ParameterLabel::Simple("Account".to_string()),
                documentation: Some(Documentation::String("Account to pad".to_string())),
            },
            ParameterInformation {
                label: ParameterLabel::Simple("PadAccount".to_string()),
                documentation: Some(Documentation::String("Source account for padding (e.g., Equity:Opening-Balances)".to_string())),
            },
        ]),
        active_parameter: None,
    }
}

fn note_signature() -> SignatureInformation {
    SignatureInformation {
        label: "YYYY-MM-DD note Account \"text\"".to_string(),
        documentation: Some(Documentation::MarkupContent(MarkupContent {
            kind: MarkupKind::Markdown,
            value: "Add a note to an account.\n\nUseful for recording important events or changes."
                .to_string(),
        })),
        parameters: Some(vec![
            ParameterInformation {
                label: ParameterLabel::Simple("Account".to_string()),
                documentation: Some(Documentation::String("Account to annotate".to_string())),
            },
            ParameterInformation {
                label: ParameterLabel::Simple("\"text\"".to_string()),
                documentation: Some(Documentation::String("Note content".to_string())),
            },
        ]),
        active_parameter: None,
    }
}

fn document_signature() -> SignatureInformation {
    SignatureInformation {
        label: "YYYY-MM-DD document Account \"path\"".to_string(),
        documentation: Some(Documentation::MarkupContent(MarkupContent {
            kind: MarkupKind::Markdown,
            value:
                "Link a document to an account.\n\nUsed for attaching receipts, statements, etc."
                    .to_string(),
        })),
        parameters: Some(vec![
            ParameterInformation {
                label: ParameterLabel::Simple("Account".to_string()),
                documentation: Some(Documentation::String("Associated account".to_string())),
            },
            ParameterInformation {
                label: ParameterLabel::Simple("\"path\"".to_string()),
                documentation: Some(Documentation::String("Path to document file".to_string())),
            },
        ]),
        active_parameter: None,
    }
}

fn event_signature() -> SignatureInformation {
    SignatureInformation {
        label: "YYYY-MM-DD event \"type\" \"description\"".to_string(),
        documentation: Some(Documentation::MarkupContent(MarkupContent {
            kind: MarkupKind::Markdown,
            value: "Record an event.\n\nUsed for tracking life events, location changes, etc."
                .to_string(),
        })),
        parameters: Some(vec![
            ParameterInformation {
                label: ParameterLabel::Simple("\"type\"".to_string()),
                documentation: Some(Documentation::String(
                    "Event type (e.g., \"location\", \"employer\")".to_string(),
                )),
            },
            ParameterInformation {
                label: ParameterLabel::Simple("\"description\"".to_string()),
                documentation: Some(Documentation::String("Event description".to_string())),
            },
        ]),
        active_parameter: None,
    }
}

fn price_signature() -> SignatureInformation {
    SignatureInformation {
        label: "YYYY-MM-DD price Currency Amount QuoteCurrency".to_string(),
        documentation: Some(Documentation::MarkupContent(MarkupContent {
            kind: MarkupKind::Markdown,
            value: "Record a price for a commodity.\n\nUsed for tracking market prices of stocks, currencies, etc.".to_string(),
        })),
        parameters: Some(vec![
            ParameterInformation {
                label: ParameterLabel::Simple("Currency".to_string()),
                documentation: Some(Documentation::String("Base currency (e.g., AAPL, EUR)".to_string())),
            },
            ParameterInformation {
                label: ParameterLabel::Simple("Amount".to_string()),
                documentation: Some(Documentation::String("Price value".to_string())),
            },
            ParameterInformation {
                label: ParameterLabel::Simple("QuoteCurrency".to_string()),
                documentation: Some(Documentation::String("Quote currency (e.g., USD)".to_string())),
            },
        ]),
        active_parameter: None,
    }
}

fn commodity_signature() -> SignatureInformation {
    SignatureInformation {
        label: "YYYY-MM-DD commodity Currency".to_string(),
        documentation: Some(Documentation::MarkupContent(MarkupContent {
            kind: MarkupKind::Markdown,
            value: "Declare a commodity.\n\nOptionally followed by metadata lines.".to_string(),
        })),
        parameters: Some(vec![ParameterInformation {
            label: ParameterLabel::Simple("Currency".to_string()),
            documentation: Some(Documentation::String(
                "Commodity symbol (e.g., USD, AAPL)".to_string(),
            )),
        }]),
        active_parameter: None,
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_after_date_shows_directives() {
        let source = "2024-01-15 ";
        let params = SignatureHelpParams {
            context: None,
            text_document_position_params: lsp_types::TextDocumentPositionParams {
                text_document: lsp_types::TextDocumentIdentifier {
                    uri: "file:///test.beancount".parse().unwrap(),
                },
                position: lsp_types::Position::new(0, 11),
            },
            work_done_progress_params: Default::default(),
        };

        let help = handle_signature_help(&params, source, PositionEncoding::Utf16);
        assert!(help.is_some());

        let help = help.unwrap();
        assert!(!help.signatures.is_empty());
        assert!(help.signatures.len() >= 5); // Multiple directive options
    }

    #[test]
    fn test_transaction_flag() {
        let source = "2024-01-15 * ";
        let params = SignatureHelpParams {
            context: None,
            text_document_position_params: lsp_types::TextDocumentPositionParams {
                text_document: lsp_types::TextDocumentIdentifier {
                    uri: "file:///test.beancount".parse().unwrap(),
                },
                position: lsp_types::Position::new(0, 13),
            },
            work_done_progress_params: Default::default(),
        };

        let help = handle_signature_help(&params, source, PositionEncoding::Utf16);
        assert!(help.is_some());

        let help = help.unwrap();
        assert_eq!(help.signatures.len(), 1);
        assert!(help.signatures[0].label.contains("payee"));
    }

    #[test]
    fn test_open_directive() {
        let source = "2024-01-15 open ";
        let params = SignatureHelpParams {
            context: None,
            text_document_position_params: lsp_types::TextDocumentPositionParams {
                text_document: lsp_types::TextDocumentIdentifier {
                    uri: "file:///test.beancount".parse().unwrap(),
                },
                position: lsp_types::Position::new(0, 16),
            },
            work_done_progress_params: Default::default(),
        };

        let help = handle_signature_help(&params, source, PositionEncoding::Utf16);
        assert!(help.is_some());

        let help = help.unwrap();
        assert_eq!(help.signatures.len(), 1);
        assert!(help.signatures[0].label.contains("open"));
        assert_eq!(help.active_parameter, Some(0)); // Account parameter
    }

    #[test]
    fn test_price_directive_active_parameter_advances() {
        // After `price AAPL ` (commodity + trailing space) the active parameter
        // must advance to the amount (1), not stay on the commodity (0).
        let cases = [
            ("2024-01-15 price ", 17, 0u32),       // typing the commodity
            ("2024-01-15 price AAPL ", 22, 1),     // commodity done → amount
            ("2024-01-15 price AAPL 150 ", 26, 2), // amount done → currency
        ];
        for (source, col, expected) in cases {
            let params = SignatureHelpParams {
                context: None,
                text_document_position_params: lsp_types::TextDocumentPositionParams {
                    text_document: lsp_types::TextDocumentIdentifier {
                        uri: "file:///test.beancount".parse().unwrap(),
                    },
                    position: lsp_types::Position::new(0, col),
                },
                work_done_progress_params: Default::default(),
            };
            let help = handle_signature_help(&params, source, PositionEncoding::Utf16)
                .unwrap_or_else(|| panic!("signature help for {source:?}"));
            assert!(help.signatures[0].label.contains("price"));
            assert_eq!(
                help.active_parameter,
                Some(expected),
                "wrong active parameter for {source:?}"
            );
        }
    }

    #[test]
    fn test_option_directive() {
        let source = "option ";
        let params = SignatureHelpParams {
            context: None,
            text_document_position_params: lsp_types::TextDocumentPositionParams {
                text_document: lsp_types::TextDocumentIdentifier {
                    uri: "file:///test.beancount".parse().unwrap(),
                },
                position: lsp_types::Position::new(0, 7),
            },
            work_done_progress_params: Default::default(),
        };

        let help = handle_signature_help(&params, source, PositionEncoding::Utf16);
        assert!(help.is_some());

        let help = help.unwrap();
        assert!(help.signatures[0].label.contains("option"));
    }
}