Files
lucisv/docs/features/inline-templates/README.md
T
lucioandClaude Fable 5 9d47b6d02b Inline templates M15: ghost text finishes the block you open
textDocument/inlineCompletion (LSP 3.18): typing `if (` offers grey
`) begin … end` and a line-ending `begin` offers its `end`; Tab accepts
as a snippet, cursor in the condition first, indented body second.
Token-based triggers (comments/strings/identifiers never fire), offered
only while the construct is really unclosed (paren stack, pairs.rs for
begin/end). Response types hand-rolled: lsp-types 0.97's item is the old
draft, and vscode-languageclient 9 only makes a SnippetString from
insertText {kind:"snippet"} — shape pinned in unit, e2e and smoke tests.
vfmt.inlineTemplates (default on) turns it off; VS Code extension opts
into the proposed client feature. QA: Eof-sentinel fix so a trigger at
the true end of file still offers.

Co-Authored-By: Claude Fable 5 <[email protected]>
2026-08-25 13:30:43 -07:00

423 lines
24 KiB
Markdown
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
# inline-templates
## Goal
Ghost text that finishes a block as you open it. Type `if (` and grey
`) begin … end` appears after the cursor; press Tab and the snippet is
inserted with the cursor inside the parens, a second Tab jumping to the
indented body line. Type `begin` at the end of a line and the matching
`end` appears the same way. This is LSP 3.18's
`textDocument/inlineCompletion`, served by `vfmt-server` and opted into by
the VS Code extension. It is the completion-templates tier without the
completion widget: the same skeletons, offered at the moment the user has
already committed to the construct, so accepting one costs a single key.
## Assumptions
- **The client understands snippet inline completions.** LSP 3.18 gives no
way to negotiate that, unlike `completionItem.snippetSupport`: the
`InlineCompletionClientCapabilities` the protocol defines carries only
`dynamicRegistration`. Every item is therefore sent as
`insertText: { "kind": "snippet", "value": … }`, the 3.18 `StringValue`
shape, which is the only spelling `vscode-languageclient` turns into a
working `SnippetString`. A client that ignored the object and rendered it
as text would show literal `${1:cond}` — no client in use does, and the
request is only ever sent by a client that registered for it.
- **Trigger detection reads the token stream, never the raw text.** A
buffer that does not lex has no tokens, so it is silently declined —
the same trade `completion.rs` makes, and for the same reason (an open
string or block comment is the commonest way to break the lexer while
typing).
- **The suppression heuristic is a token-stream match, not a parse.** See
Handshakes below for the exact rule and what it cannot see (`` `ifdef ``
arms, macro bodies). Being wrong costs one unwanted grey suggestion the
user ignores, never a buffer edit — nothing is inserted until Tab.
- **There is no position gate**, unlike the completion tier's
`at_statement` / `at_item`. Having just typed `if (` or `begin` at the
end of a line is already a far stronger signal than a two-letter prefix
in a completion list, and both bodies are legal at *both* positions
anyway: `if (…) begin … end` is a statement inside a procedural block
and a conditional generate construct at module scope, and a bare
`begin … end` is a block in either. Adding the gate would only cost
correct suggestions in the places the heuristic misreads.
- **`vfmt.inlineTemplates` unset means on.** Every other `vfmt.*` setting
is "no opinion until a client says otherwise"; this one's absence
resolves to `true`, which is what the VS Code default declares.
- The indent step is `vfmt.indent`, falling back to 2 — exactly what the
template tier of `completion.rs` uses. The server does not read
`vfmt.toml` for this (it does not read it for completion either).
## Handshakes
**Consumed**
- `vlog_parser::token::{Token, TokenKind}` — the lexed buffer on
`Document.tokens`. Keyword identity is `kind == Keyword && text == …`,
so `my_if (`, `// if (` and `"if ("` cannot trigger: an identifier is
`Ident`, a comment is trivia and never a token, and a string literal is
one `String` token.
- `crate::pairs::analyze` — the scope matcher. The `begin` trigger fires
only when `analyze` reports *this* `begin` (matched by its own span) in
`unmatched_open`. That is stricter and more honest than a global count:
`always_comb begin` / freshly typed `begin` / `end` leaves the *new*
`begin` matched by the existing `end`, and no ghost appears.
- `crate::completion::layout_at` — **new, exported for this module.** It is
the body of what used to be `completion.rs`'s private `layout`, taken by
offset instead of by `Word`, so the ghost body and the completion-list
template are indented by one function and cannot drift. `completion.rs`
now calls it too.
- `crate::settings::ClientSettings::inline_templates` — **new field**,
`Option<bool>` from `vfmt.inlineTemplates`. Nothing else reads it;
`Workspace::set_client_settings` does not treat it as a scope change, so
toggling it rebuilds no index.
- `vlog_refactor::Layout` — `{ base, step }`, rendered exactly as
`templates.rs` renders a body.
**Promised**
- `textDocument/inlineCompletion` (LSP 3.18, proposed in `lsp-types`),
advertised as `inlineCompletionProvider: true`. The result is
`{"items": [ { "insertText": {"kind": "snippet", "value": … },
"range": … } ]}` or `null`. The `range` is always empty and always at
the cursor: the item inserts, it never replaces, and the protocol
requires a range to begin and end on one line.
`the_wire_shape_is_what_the_client_reads` pins that JSON, so a future
`lsp-types` bump that changes `InlineCompletionItem` cannot silently
turn the snippet into plain text.
- Root `Cargo.toml`: `lsp-types` gains `features = ["proposed"]`. That
feature also adds `offset_encoding` fields to `ClientCapabilities`,
`InitializeResult` and `TextDocumentClientCapabilities` — all
`Option`, all `skip_serializing_if`, so nothing on the wire changes.
`main.rs`'s `InitializeResult` literal gained a `..Default::default()`
for it.
## Status / TODO
- [x] `crates/vfmt_server/src/inline.rs`: the data-driven trigger table,
detection over the token stream, the suppression check, the renderer
and the hand-rolled wire types
- [x] `if (` trigger (and `else if (`, which is the same two tokens)
- [x] `begin` trigger
- [x] Suppression: unclosed `(` for the paren trigger, `pairs.rs` says
"this opener never closed" for the scope trigger
- [x] `vfmt.inlineTemplates` in `settings.rs` and in the extension's
`package.json`
- [x] Capability in `main.rs`, dispatch in `server.rs`
- [x] VS Code opt-in: `client.registerFeatures(ProposedFeatures.createAll(client))`
- [x] `editors/nvim/README.md` note
- [x] Unit tests: triggers, negatives, indentation, the serialized shape
- [x] End-to-end test in `crates/vfmt_server/tests/e2e.rs`
- [x] `cargo fmt` / `cargo clippy --all-targets` / `cargo test` green
## Work log
**2026-08-25 — dev**
- Read `templates.rs`, `completion.rs`, `pairs.rs`, `settings.rs`, the
vendored `vscode-languageclient@9.0.1` and `lsp-types@0.97.0`'s
`inline_completion.rs` before writing anything.
- **Confirmed the protocol trap the lead flagged.** `lsp-types` 0.97's
`InlineCompletionItem` is the *old* 3.18 draft (`insert_text: String` +
`insert_text_format`), while `protocolConverter.js`'s
`asInlineCompletionItem` implements the *new* one: a string `insertText`
becomes plain text and only `insertText.value` becomes a
`SnippetString`. So the response types are hand-rolled serde structs in
`inline.rs` and only `InlineCompletionParams` / `InlineCompletionOptions`
come from `lsp-types`. `the_wire_shape_is_what_the_client_reads` asserts
the exact JSON.
- **The trigger table is data.** One `Trigger` is a keyword, an optional
punctuation token that must follow it, which kind of "still unfinished"
check gates it, and a body in `templates.rs`'s `(steps, text)` form.
Adding `case` → `endcase` or `module` → `endmodule` later is one entry
and nothing else; only the two the round asked for ship.
- **Cursor contract: exactly at the last token's end.** Whitespace between
the trigger token and the cursor is not accepted, so `begin |` offers
nothing. It is the crisp "you just typed this" rule, and it keeps the
rendered body's first character from landing after stray spaces.
- **Suppression.** Two checks, one per trigger kind, and both ask the same
question: *is the token the user just typed ever given its counterpart?*
`Unclosed::Scope` asks `pairs::analyze` whether the very keyword just
typed is in `unmatched_open`. `Unclosed::Paren` runs the same shape of
stack over `(`/`)` and asks whether this `(` is ever popped.
**A running count was wrong** and was replaced before shipping: with
`if (` on one line and `x = f(1);` on the next, a `(` minus `)` total is
zero and the ghost would vanish, because the call's closer cancelled the
user's opener. `a_later_call_does_not_cancel_the_paren_just_typed` and
`a_paren_the_line_below_closes_still_counts_as_closed` pin both sides.
- **Rendering.** A local 10-line renderer rather than reaching into
`templates::Template`: the bodies here are this module's own const, only
the snippet spelling is ever needed (there is no plain-text negotiation
to fall back to), and `Template::render`'s second spelling and its
`Defaults` machinery would be dead weight. The layout itself *is*
shared — `completion::layout_at` — so the two features cannot indent
differently.
- Guard tests carried over from `templates.rs` in spirit: every trigger's
body, with its holes filled in, is planted in a module and must parse;
every `$` in every body must start a tabstop.
- `node editors/vscode/smoke.js` run and green against both the debug and
the release binary. It now asserts `inlineCompletionProvider` is
advertised, sends a real `textDocument/inlineCompletion` at the `begin`
of its already-existing "lost its `end`" buffer, and checks the
`{kind:"snippet"}` object and its value — the pre-publish check now
covers this feature end to end from a plain node client. The
extension's `registerFeatures` line itself is exercised only by review:
it needs a running VS Code.
- **`TODO.md` untouched** — no existing item covers this. The nearest
match, "Backlog (extract module, **inline**, …)", is the *inline
function* refactoring, not ghost text; the M1–M14 milestone list has no
entry to check off.
- Final: `cargo fmt --all -- --check` clean, `cargo clippy --all-targets`
zero warnings, `cargo test` 1607 passed / 0 failed across the
workspace.
## QA log
**2026-08-25 — QA**
**Verdict: pass, with one bug found and fixed, and one out-of-scope
performance finding filed separately.** Build/lint/test all clean; the wire
contract matches the vendored client exactly; the trigger heuristics hold up
under adversarial input except for one true-EOF edge case, fixed below.
**Build / lint / test**
- `cargo fmt --all -- --check`: clean.
- `cargo clippy --all-targets --workspace -- -D warnings`: zero warnings.
- `cargo test --workspace`: 1614 passed / 0 failed / 0 ignored-unexpectedly
(up from the dev's 1607 — this log's new tests). Full tail at the bottom.
- `node editors/vscode/smoke.js <path>`: OK against both a fresh debug and a
fresh release build. **Caveat, not a code defect:** running it with no
argument picks up whatever `vfmt-server` is on `$PATH` — on this machine an
Aug-24 build predating this feature, which fails with `capability missing:
inlineCompletionProvider`. Anyone re-running the dev's "smoke.js against
debug and release" claim should pass the binary path explicitly, the way
the dev's own work log implies they did.
**Wire contract (item 2)** — read
`editors/vscode/node_modules/vscode-languageclient/lib/common/protocolConverter.js:1039`
(`asInlineCompletionItem`) directly:
- `typeof item.insertText === 'string'` → plain text; the object arm →
`new code.SnippetString(item.insertText.value)`. Confirmed the server's
`SnippetValue.kind` field is *never actually read* by this code path — only
`typeof insertText` decides — so `kind` documents intent rather than being
load-bearing, which is exactly what `inline.rs:89-93`'s comment already
says. Not a bug, just confirming the claim.
- `item.filterText` and `item.command` are read only if truthy; `InlineItem`
sends neither, so both branches are skipped — no crash, matches
`the_wire_shape_is_what_the_client_reads`'s pinned JSON.
- `ProposedFeatures` is exported end-to-end:
`lib/common/client.js:1591` defines it and gates `createAll` to exactly
`[new InlineCompletionItemFeature(_client)]`; `lib/common/api.js:27`
re-exports `client.js`; `lib/node/main.js:34` re-exports `common/api.js`.
So `require('vscode-languageclient/node').ProposedFeatures` in
`extension.js` really does resolve to it.
- `lib/common/inlineCompletion.js:16-19`: `fillClientCapabilities` sets
`textDocument.inlineCompletion.dynamicRegistration = true` — matches the
`initialize` request body the new e2e test sends.
- `lib/common/features.js:230-235`: `getRegistrationOptions` accepts a bare
boolean capability (`Is.boolean(capability) && capability === true`), so
`main.rs`'s `inline_completion_provider: Some(OneOf::Left(true))` registers
correctly without an options object — verified this is the same pattern
`call_hierarchy_provider` already uses.
- `extension.js:79` (`registerFeatures`) runs before `:126` (`start()`) —
correct order; features must register before initialize.
**Trigger-logic attacks (item 3)** — everything on the requested list was
tried; results:
- `if (` / `begin` in a line comment, a block comment, inside a string: all
declined (dev's own tests, verified still passing).
- `my_if (`: declined (identifier, not `Keyword`).
- `if (` / `begin` with text after the cursor on the line: declined.
- `if(` **no space**: added `no_space_between_the_keyword_and_the_paren_still_triggers`
(`inline.rs`) — triggers correctly; token spans carry no inter-token
whitespace so this was never actually at risk, but it was untested.
- `else if (`: offers the same block (dev's test).
- Nested `begin`s, only the innermost unmatched: dev's
`a_begin_that_already_has_its_end_offers_nothing` covers both directions.
- Every `begin`/`end` balanced: offers nothing (implied by the same test;
the matched inner `begin` gets nothing).
- `begin` mid-line with code after: declined
(`a_line_with_anything_after_the_cursor_never_triggers`).
- Cursor one char before/after an unclosed `begin`'s end: the `span.end ==
offset` equality check in `triggered` makes this structurally impossible to
get wrong — a token not ending exactly at the cursor is never `last`.
`whitespace_between_the_keyword_and_the_cursor_never_triggers` covers the
"one char after" case directly.
- **CRLF line endings**: untested by the dev. Added
`crlf_line_endings_still_trigger_and_indent_correctly` — both triggers fire
correctly; `rest_of_line_is_blank` splits on `\n` alone, so the `\r` rides
along in the tail slice, and `char::is_whitespace('\r')` is `true`, so it
reads as "nothing after the cursor" by luck of that being true rather than
by a check that means to handle it. Passes, but fragile enough that a
future change narrowing that whitespace check should re-run this test.
- **Position past end of line**: untested by the dev. Added
`a_position_past_the_end_of_its_line_clamps_rather_than_panics` —
`convert.rs`'s existing clamp handles it; no panic, and it clamps to
exactly the trigger position here.
- **Empty file, position (0,0)**: untested by the dev. Added
`an_empty_file_at_zero_zero_offers_nothing_and_does_not_panic`.
- **Huge deeply-nested file** (the TODO.md §1 history item): this module
itself never walks the parse tree (`triggered`/`unfinished` are flat loops
over `doc.tokens`), so no stack overflow is possible here regardless of
nesting depth — confirmed by `parse_source_tolerant` benchmarking as
effectively linear (`MAX_NESTING_DEPTH = 64` in `vlog_parser::parser`
bounds the tree walk; the lexer that builds `doc.tokens` is a flat loop,
never recursive). **But this surfaced a real quadratic-time hazard one hop
away — see Finding 2 below**, which is not a defect in this feature's own
code and is out of this feature's file list, so it is filed rather than
fixed here.
- **Multi-byte UTF-8 on the trigger line**: dev's
`a_multibyte_line_puts_the_range_where_the_cursor_really_is` covers a
multi-byte character *before* the trigger line; `convert.rs` (shared,
exhaustively tested independently — astral/surrogate cases included) is
the only UTF-16 conversion path either `completion.rs` or `inline.rs` uses,
confirmed by reading `inline.rs:130` (`doc.positions().offset(position)`).
**Finding 1 (fixed directly) — true-end-of-file trigger silently declined.**
`crates/vfmt_server/src/inline.rs:159` (before fix):
`doc.tokens.iter().rposition(|token| token.span.end <= offset)`. `tokenize`
(`vlog_parser::lexer::tokenize`) appends a zero-width `Eof` sentinel token
whose span starts *and* ends at `text.len()`. When the buffer's very last
byte is the trigger's own last character — e.g. a brand new file where the
user's first keystrokes are literally `... always_comb begin` with no
trailing newline yet — that `Eof` token shares the trigger token's
`span.end`, and `rposition` (searching back-to-front) hits the `Eof` first.
`triggered` then compares `TokenKind::Eof` against `TokenKind::Keyword` and
declines, exactly the moment the ghost text is most wanted.
Repro (pre-fix): `inline_completions` on `"module top;\n always_comb
begin"` (nothing after `begin`) returned `None`; the identical text with a
trailing `"\nendmodule\n"` returned `Some(..)`. Same for `if (` at true EOF.
This is small, unambiguous, and entirely inside the feature's own file, so I
fixed it directly rather than filing it: `triggered` now skips `Eof` tokens
when scanning for `last` (`inline.rs:158-166`). Added
`a_trigger_at_the_true_end_of_file_still_offers_a_ghost` to pin it. Full
suite re-run clean after the fix (fmt/clippy/`cargo test --workspace`).
**Finding 2 (filed, not fixed — out of scope for this feature) — `pairs::analyze`
is O(depth²) in nesting depth, and this feature is a new caller that hits it
per keystroke.** `crates/vfmt_server/src/pairs.rs:157`:
`let depth = stack.iter().filter(|f| is_rainbow(f.rule.open)).count() as u32;`
runs once per opener *push*, scanning the whole current stack every time. For
`n` consecutively nested rainbow openers (`begin`/`fork`) with none closed,
total work is `1+2+...+n = O(n²)`. The comment right above it (`pairs.rs:153-156`)
states the assumption this breaks: "a dozen frames deep at worst on the whole
corpus."
Measured directly (debug build, `analyze` alone, text = `n` consecutive
`begin\n` lines): depth 1000 → 19ms, 2000 → 49ms, 4000 → 155ms, 8000 →
619ms — the ~4× growth per doubling is the quadratic signature. Through the
full `inline_completions` path at depth 50,000 this measured **24 seconds**
for one request (isolated with `Instant` timers around `asking()` vs
`inline_completions()`; the document-setup half was 63ms, all 24s was inside
`inline_completions`, i.e. inside the `Unclosed::Scope` gate's call to
`pairs::analyze`).
This bug predates this feature and lives entirely in `pairs.rs`, which is not
on this feature's file list (`crates/vfmt_server/src/pairs.rs` — CLAUDE.md
scope rule), so I have not touched it; `git diff --stat` confirms it is
untouched by this change. What *is* this feature's business: `inline.rs`'s
`Unclosed::Scope` gate (`inline.rs:190-198`) is a **new caller** of
`pairs::analyze` that runs it fresh on every `textDocument/inlineCompletion`
request — i.e., potentially every keystroke — where the existing callers
(`documentHighlight`, the missing-closer diagnostic, `vfmt/scopePairs`) fire
on click, on save/open, and on hover respectively, all far less frequently.
So this feature doesn't introduce the bug but does meaningfully raise its
real-world exposure. Filed as a background task (see below) rather than
fixed, since the fix belongs in `pairs.rs` and is a design choice (a running
counter instead of a scan, most likely) outside this feature's scope.
`inline.rs`'s own regression test for deep nesting
(`a_deeply_nested_file_neither_crashes_nor_misses_the_trigger`) uses depth
3,000 rather than 50,000 to stay fast while still exercising the same code
path; its comment cross-references this log entry rather than re-deriving
the finding.
**Indentation (item 4)** — all pass, dev's tests plus nothing new needed:
tabs preserved verbatim as `base` (`a_tab_indented_line_keeps_its_own_tabs`),
configured step honored (`the_indent_step_is_the_one_the_client_asked_for`),
ghost `end` aligns with the trigger line's own leading whitespace by
construction (`layout_at` reads it from the buffer, not from a config
value).
**Setting (item 5)** — unit-level was already covered
(`the_setting_turns_the_whole_feature_off`), but every other `vfmt.*`
setting's e2e coverage in `tests/e2e.rs` goes over the wire via
`workspace/didChangeConfiguration`
(`pushed_settings_reach_the_formatter_and_can_change_mid_session`,
`a_pushed_exclude_rebuilds_the_index_mid_session`), and this one didn't have
that. Added `the_inline_templates_setting_is_honoured_over_the_wire` to
`tests/e2e.rs`: default-on with nothing pushed, `false` suppresses mid-session
with no restart, `true` turns it back on — all over real
`workspace/didChangeConfiguration` notifications against a spawned server.
`package.json`'s `vfmt.inlineTemplates` (default `true`) and `settings.rs`'s
`vfmt.get("inlineTemplates")` spell the same key.
**Capability / registration (item 6)** — see wire-contract section above;
all confirmed by reading the vendored client source, not just by running the
tests.
**Scope check (item 7)** — `git diff --stat` / `git status --porcelain`
against the stated file list: exact match
(`Cargo.toml`, `completion.rs`, `main.rs`, `server.rs`, `settings.rs`,
`tests/e2e.rs`, `editors/nvim/README.md`, `editors/vscode/{extension.js,
package.json, smoke.js}`, new `crates/vfmt_server/src/inline.rs`, new
`docs/features/inline-templates/`). `crates/vlog_formatter/` and
`verify.rs` untouched — confirmed by their absence from the diff. (An
unrelated `.DS_Store` sits untracked in the repo root; not this feature's
concern.)
**No `unwrap`/`expect`/`panic!` in new non-test library code (item 8)** —
checked every line of `inline.rs` above its `#[cfg(test)]` boundary and the
`+` lines of every other diffed file: none found.
**What I changed**
- Fixed directly: `crates/vfmt_server/src/inline.rs` — `triggered` now
excludes the lexer's `Eof` sentinel from the "last token ending at the
cursor" scan (Finding 1).
- Tests added, all in `crates/vfmt_server/src/inline.rs` unless noted:
`a_trigger_at_the_true_end_of_file_still_offers_a_ghost`,
`a_deeply_nested_file_neither_crashes_nor_misses_the_trigger`,
`an_empty_file_at_zero_zero_offers_nothing_and_does_not_panic`,
`a_position_past_the_end_of_its_line_clamps_rather_than_panics`,
`crlf_line_endings_still_trigger_and_indent_correctly`,
`no_space_between_the_keyword_and_the_paren_still_triggers`, and
`the_inline_templates_setting_is_honoured_over_the_wire` in
`crates/vfmt_server/tests/e2e.rs`.
- Filed, not fixed (out of scope): a `spawn_task` chip for Finding 2
(`pairs.rs:157`'s O(depth²) scan).
- Nothing else touched. No commit, no push.
**Final test-suite tail** (after the fix, `cargo test --workspace`):
```
test result: ok. 527 passed; 0 failed; 4 ignored; 0 measured; 0 filtered out; finished in 2.04s
...
test result: ok. 20 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out; finished in 3.29s
```
1614 passed / 0 failed across the workspace (up from the dev's 1607: +6
`inline.rs` tests, +1 `e2e.rs` test). `cargo fmt --all -- --check` and
`cargo clippy --all-targets --workspace -- -D warnings` both clean.
`node editors/vscode/smoke.js <debug-binary>` and `<release-binary>` both
OK.
## Review
**2026-08-25 — lead.** Approved and committed.
- Read `inline.rs` in full plus every other diff. The two deliberate choices —
the data-driven trigger table and the hand-rolled `{"kind": "snippet"}`
response types — are right, and the wire shape is pinned three times
(unit, e2e, smoke), which is what protects it from a future `lsp-types` bump.
- The dev's deviation from the brief (a paren *stack* instead of a running
count for the `if (` gate) is correct and is pinned in both directions
(`a_later_call_does_not_cancel_the_paren_just_typed` and its mirror).
- QA's Eof-sentinel find was real and the fix is minimal and tested.
- The `pairs::analyze` O(depth²) exposure QA filed stays out of this change —
`pairs.rs` is another feature's file — and is tracked as its own task.
- Gates re-run by the lead: fmt clean, clippy clean, full workspace suite
green, `smoke.js` exercised by QA against debug and release.