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]>
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: theInlineCompletionClientCapabilitiesthe protocol defines carries onlydynamicRegistration. Every item is therefore sent asinsertText: { "kind": "snippet", "value": … }, the 3.18StringValueshape, which is the only spellingvscode-languageclientturns into a workingSnippetString. 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.rsmakes, 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 (
`ifdefarms, 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 typedif (orbeginat 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 … endis a statement inside a procedural block and a conditional generate construct at module scope, and a barebegin … endis a block in either. Adding the gate would only cost correct suggestions in the places the heuristic misreads. vfmt.inlineTemplatesunset means on. Every othervfmt.*setting is "no opinion until a client says otherwise"; this one's absence resolves totrue, which is what the VS Code default declares.- The indent step is
vfmt.indent, falling back to 2 — exactly what the template tier ofcompletion.rsuses. The server does not readvfmt.tomlfor this (it does not read it for completion either).
Handshakes
Consumed
vlog_parser::token::{Token, TokenKind}— the lexed buffer onDocument.tokens. Keyword identity iskind == Keyword && text == …, somy_if (,// if (and"if ("cannot trigger: an identifier isIdent, a comment is trivia and never a token, and a string literal is oneStringtoken.crate::pairs::analyze— the scope matcher. Thebegintrigger fires only whenanalyzereports thisbegin(matched by its own span) inunmatched_open. That is stricter and more honest than a global count:always_comb begin/ freshly typedbegin/endleaves the newbeginmatched by the existingend, and no ghost appears.crate::completion::layout_at— new, exported for this module. It is the body of what used to becompletion.rs's privatelayout, taken by offset instead of byWord, so the ghost body and the completion-list template are indented by one function and cannot drift.completion.rsnow calls it too.crate::settings::ClientSettings::inline_templates— new field,Option<bool>fromvfmt.inlineTemplates. Nothing else reads it;Workspace::set_client_settingsdoes not treat it as a scope change, so toggling it rebuilds no index.vlog_refactor::Layout—{ base, step }, rendered exactly astemplates.rsrenders a body.
Promised
textDocument/inlineCompletion(LSP 3.18, proposed inlsp-types), advertised asinlineCompletionProvider: true. The result is{"items": [ { "insertText": {"kind": "snippet", "value": … }, "range": … } ]}ornull. Therangeis 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_readspins that JSON, so a futurelsp-typesbump that changesInlineCompletionItemcannot silently turn the snippet into plain text.- Root
Cargo.toml:lsp-typesgainsfeatures = ["proposed"]. That feature also addsoffset_encodingfields toClientCapabilities,InitializeResultandTextDocumentClientCapabilities— allOption, allskip_serializing_if, so nothing on the wire changes.main.rs'sInitializeResultliteral gained a..Default::default()for it.
Status / TODO
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 typesif (trigger (andelse if (, which is the same two tokens)begintrigger- Suppression: unclosed
(for the paren trigger,pairs.rssays "this opener never closed" for the scope trigger vfmt.inlineTemplatesinsettings.rsand in the extension'spackage.json- Capability in
main.rs, dispatch inserver.rs - VS Code opt-in:
client.registerFeatures(ProposedFeatures.createAll(client)) editors/nvim/README.mdnote- Unit tests: triggers, negatives, indentation, the serialized shape
- End-to-end test in
crates/vfmt_server/tests/e2e.rs cargo fmt/cargo clippy --all-targets/cargo testgreen
Work log
2026-08-25 — dev
- Read
templates.rs,completion.rs,pairs.rs,settings.rs, the vendored[email protected]and[email protected]'sinline_completion.rsbefore writing anything. - Confirmed the protocol trap the lead flagged.
lsp-types0.97'sInlineCompletionItemis the old 3.18 draft (insert_text: String+insert_text_format), whileprotocolConverter.js'sasInlineCompletionItemimplements the new one: a stringinsertTextbecomes plain text and onlyinsertText.valuebecomes aSnippetString. So the response types are hand-rolled serde structs ininline.rsand onlyInlineCompletionParams/InlineCompletionOptionscome fromlsp-types.the_wire_shape_is_what_the_client_readsasserts the exact JSON. - The trigger table is data. One
Triggeris a keyword, an optional punctuation token that must follow it, which kind of "still unfinished" check gates it, and a body intemplates.rs's(steps, text)form. Addingcase→endcaseormodule→endmodulelater 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::Scopeaskspairs::analyzewhether the very keyword just typed is inunmatched_open.Unclosed::Parenruns the same shape of stack over(/)and asks whether this(is ever popped. A running count was wrong and was replaced before shipping: withif (on one line andx = 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_typedanda_paren_the_line_below_closes_still_counts_as_closedpin 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), andTemplate::render's second spelling and itsDefaultsmachinery 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.rsin 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.jsrun and green against both the debug and the release binary. It now assertsinlineCompletionProvideris advertised, sends a realtextDocument/inlineCompletionat thebeginof its already-existing "lost itsend" 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'sregisterFeaturesline itself is exercised only by review: it needs a running VS Code.TODO.mduntouched — 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 -- --checkclean,cargo clippy --all-targetszero warnings,cargo test1607 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 whatevervfmt-serveris on$PATH— on this machine an Aug-24 build predating this feature, which fails withcapability 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'sSnippetValue.kindfield is never actually read by this code path — onlytypeof insertTextdecides — sokinddocuments intent rather than being load-bearing, which is exactly whatinline.rs:89-93's comment already says. Not a bug, just confirming the claim.item.filterTextanditem.commandare read only if truthy;InlineItemsends neither, so both branches are skipped — no crash, matchesthe_wire_shape_is_what_the_client_reads's pinned JSON.ProposedFeaturesis exported end-to-end:lib/common/client.js:1591defines it and gatescreateAllto exactly[new InlineCompletionItemFeature(_client)];lib/common/api.js:27re-exportsclient.js;lib/node/main.js:34re-exportscommon/api.js. Sorequire('vscode-languageclient/node').ProposedFeaturesinextension.jsreally does resolve to it.lib/common/inlineCompletion.js:16-19:fillClientCapabilitiessetstextDocument.inlineCompletion.dynamicRegistration = true— matches theinitializerequest body the new e2e test sends.lib/common/features.js:230-235:getRegistrationOptionsaccepts a bare boolean capability (Is.boolean(capability) && capability === true), somain.rs'sinline_completion_provider: Some(OneOf::Left(true))registers correctly without an options object — verified this is the same patterncall_hierarchy_provideralready 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 (/beginin a line comment, a block comment, inside a string: all declined (dev's own tests, verified still passing).my_if (: declined (identifier, notKeyword).if (/beginwith text after the cursor on the line: declined.if(no space: addedno_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
begins, only the innermost unmatched: dev'sa_begin_that_already_has_its_end_offers_nothingcovers both directions. - Every
begin/endbalanced: offers nothing (implied by the same test; the matched innerbegingets nothing). beginmid-line with code after: declined (a_line_with_anything_after_the_cursor_never_triggers).- Cursor one char before/after an unclosed
begin's end: thespan.end == offsetequality check intriggeredmakes this structurally impossible to get wrong — a token not ending exactly at the cursor is neverlast.whitespace_between_the_keyword_and_the_cursor_never_triggerscovers 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_blanksplits on\nalone, so the\rrides along in the tail slice, andchar::is_whitespace('\r')istrue, 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/unfinishedare flat loops overdoc.tokens), so no stack overflow is possible here regardless of nesting depth — confirmed byparse_source_tolerantbenchmarking as effectively linear (MAX_NESTING_DEPTH = 64invlog_parser::parserbounds the tree walk; the lexer that buildsdoc.tokensis 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_iscovers 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 eithercompletion.rsorinline.rsuses, confirmed by readinginline.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—triggerednow excludes the lexer'sEofsentinel from the "last token ending at the cursor" scan (Finding 1). - Tests added, all in
crates/vfmt_server/src/inline.rsunless 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, andthe_inline_templates_setting_is_honoured_over_the_wireincrates/vfmt_server/tests/e2e.rs. - Filed, not fixed (out of scope): a
spawn_taskchip 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.rsin 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 futurelsp-typesbump. - 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_typedand its mirror). - QA's Eof-sentinel find was real and the fix is minimal and tested.
- The
pairs::analyzeO(depth²) exposure QA filed stays out of this change —pairs.rsis 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.jsexercised by QA against debug and release.