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 lucisv-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.
Round 2 (2026-08-25) fixed the indentation of the accepted text — the body is now indented relative to the trigger line, because the editor supplies the absolute part — and widened the table from two triggers to the dozen constructs an RTL designer opens all day. See The triggers below.
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. - The snippet is indented relative to the trigger line, and the editor
supplies the rest. One
\tper indent step, nobase— see The indentation contract below for the VS Code source this is read off, and for what it costs. Consequence worth naming twice:lucisv.indentdoes not decide the width of an accepted ghost snippet. The editor's owneditor.tabSize/editor.insertSpacesdo, because the editor rewrites the leading whitespace of every inserted line whatever the server sent.lucisv.inlineTemplates's setting description says so. - 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 most 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. The triggers that really do belong at one position only —module,generate,always,always_ff— are gated hard enough by their own keyword: an unmatchedmodulekeyword at statement position is a buffer that does not compile either way, and the ghost is the least of it. - The dialect is the file extension, resolved by
templates::dialect(doc.path)— the same rule and the same Verilog-by-default answer for a pathless buffer that the completion tier documents. Two triggers use it:for (picks the SystemVerilog or the Verilog loop header, andalways_ff @(is refused outright in a.vbuffer, whose compiler would reject the keyword. casex (is offered here althoughtemplates.rsrefuses to list it. The popup's reason for leavingcasexout is that an item nobody uses is noise in a list. Ghost text is not a list: it only ever appears once the user has typedcasex (and committed to the construct, so there is no noise to make and refusing to finish it would just be unhelpful.always @(answers with two items,always_ff @(with one. The response is a list and VS Code cycles it withAlt+]/Alt+[; order is offer priority, clocked first, becausealways @(is overwhelmingly a flop. Everything else answers with exactly one item, and that shape is pinned so a future trigger cannot quietly turn a single offer into a menu.lucisv.inlineTemplatesunset means on. Every otherlucisv.*setting is "no opinion until a client says otherwise"; this one's absence resolves totrue, which is what the VS Code default declares.
The triggers
( and @( in the Typed column are token sequences, not text: if( and
if ( are the same two tokens, and a // if ( is not a token at all.
| Typed | Dialect | Gate | Offered |
|---|---|---|---|
if ( |
both | paren | ${1:cond}) begin / $0 / end |
while ( |
both | paren | ${1:cond}) begin / $0 / end |
for ( |
SV | paren | int ${1:i} = 0; $1 < ${2:N}; $1++) begin / $0 / end |
for ( |
Verilog | paren | ${1:i} = 0; $1 < ${2:N}; $1 = $1 + 1) begin / $0 / end |
case ( |
both | paren + scope | ${1:sel}) / ${2:value}: $0; / default: ; / endcase |
casez ( |
both | paren + scope | as case |
casex ( |
both | paren + scope | as case |
always_ff @( |
SV | paren | posedge ${1:clk}) begin / $0 / end |
always @( |
both | paren | posedge ${1:clk}) begin / $0 / end, then *) begin / $0 / end |
begin |
both | scope | (nothing) / $0 / end |
fork |
both | scope | (nothing) / $0 / join |
generate |
both | scope | (nothing) / $0 / endgenerate |
module |
both | scope | ${1:name}; / $0 / endmodule |
Fourteen bodies over thirteen triggers. The bodies are the popup templates'
with the text the user has already typed cut off the front, so the two tiers
cannot offer different shapes for the same construct — for even keeps the
popup's dialect split.
Two details worth naming. module's body starts with a space and writes a
name: module alone is not a parseable header, and no placeholder can be
put in front of text the user already typed, so the body supplies
${1:name}; and the parse test proves it. The case arm keeps the
popup's $0 — the brief's sketch wrote ${2:value}: ; — because a
tabstop the user lands on is worth more than one they have to go find, and
because it is what templates.rs already writes.
Deliberately absent: function/task. Their headers need a name the
user has not typed yet, in a position no placeholder can reach without
editing backwards over the keyword, so no accepted text parses. If a clean
shape turns up it can be one more row.
The indentation contract
The 0.6.0 bug, and the reason the bodies here are spelled differently from
templates.rs's.
VS Code inserts an accepted inline completion by calling
SnippetController2.insert(snippet, { undoStopBefore: false })
(inlineCompletionsModel.ts's accept). It passes no adjustWhitespace,
and snippetSession.ts's _defaultOptions sets it to true.
SnippetSession.adjustWhitespace then walks the snippet's text markers and
does two things:
lines[0] = model.normalizeIndentation(lines[0]); // the snippet start
…
for (let i = 1; i < lines.length; i++) {
lines[i] = model.normalizeIndentation(lineLeadingWhitespace + lines[i]);
}
lineLeadingWhitespace is getLeadingWhitespace(line, 0, position.column - 1)
— the insertion line's own indentation. So every line after the first gets
the trigger line's indentation prepended, and the whole leading run is then
re-spelled by TextModel.normalizeIndentation in the editor's
tabSize/insertSpaces.
A body that had already baked that indentation in — which is what Layout's
base is — therefore came out at twice it. if ( inside a block indented
four spaces wrote its body at twelve and its end at eight, one level right
of the if it closes. That is the user's report, exactly.
The fix is to send only what the editor cannot know: one \t per indent
step, and nothing else. normalizeIndentation counts a \t as one tab
stop and re-emits the run in the user's own spelling, so \t is the one
character that means "one more level, however you write levels". The end
carries no \t at all and lands level with its opener.
The preview is the one thing this makes slightly worse, knowingly.
provideInlineCompletions.ts builds the grey text from snippet.toString()
and ghostTextView.ts renders those lines verbatim — no
adjustWhitespace runs before the user presses Tab — so the ghost body is
drawn one tab from column zero rather than at its final column. Correctness
of the accepted text wins: the preview is a hint, the buffer is the product.
The completion popup has the same trap and a different escape hatch —
see docs/features/completion-templates/README.md's The indentation
contract.
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.— no longer consumed, as of 2026-08-25. It was exported for this module so that ghost text and the completion list could not indent the same body differently; ghost text now emits relative indentation and has no layout at all, socrate::completion::layout_atlayout_atis private tocompletion.rsagain. Nothing else consumed it, and the compiler confirmed it.— same, for the same reason. This module no longer names the type.vlog_refactor::Layoutcrate::templates::{dialect, Dialect}— new, the file-extension rule the completion tier already uses, read for thefor (split and thealways_ff @(refusal. Nothing intemplates.rschanged for this.crate::settings::ClientSettings::inline_templates— new field,Option<bool>fromlucisv.inlineTemplates. Nothing else reads it;Workspace::set_client_settingsdoes not treat it as a scope change, so toggling it rebuilds no index.ClientSettings::indentis no longer read here (see The indentation contract).
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.- The snippet's whitespace is the client's to finish. Every line after
the first is
\t-per-step with no absolute component; a client that inserts an inline completion verbatim, without prepending the insertion line's indentation, will produce a flat body. That is the LSP 3.18 inline-completion contract as VS Code implements it and there is no field to negotiate it, unlikecompletionItem.insertTextMode. Recorded here so a future non-VS-Code client's ticket lands on this paragraph. - Request to
completion.rs(made and applied, 2026-08-25): the popup's multi-line items now sendinsertTextMode: asIs. See the QA/Review note in the work log — the change is one field on two item builders and is documented incompletion-templates' README. - 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/lucisv_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 lucisv.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/lucisv_server/tests/e2e.rs cargo fmt/cargo clippy --all-targets/cargo testgreen
Round 2 — 2026-08-25
- Bug:
begin/endmisaligned after accepting. Bodies are emitted relative (\tper step, nobase); the VS Code source this is read off is quoted in The indentation contract. - The same trap in the completion popup, fixed the other way it allows:
insertTextMode: asIson the template and module-skeleton items. layout_atun-exported;Layoutno longer named byinline.rs.- Trigger table generalised: opener is a token sequence, a trigger may be dialect-gated, a trigger may offer several bodies, and the gate can ask both questions.
- New triggers:
while (,for ((both dialects),case (/casez (/casex (,always @((two items),always_ff @((SV),fork,generate,module. - Hygiene tests generalised over the new table: every accepted body parses at its own position, every body is scope-balanced, every gate is derived from the body rather than restated, every hole is a tabstop, every trigger word is a keyword.
- Wire pins updated:
inline.rsunit tests,tests/e2e.rs(including a new multi-item round trip and the popup'sinsertTextMode),editors/vscode/smoke.js. lucisv.inlineTemplates's setting description names the new triggers and says the editor's indent settings, notlucisv.indent, size the result.- Not done, deliberately: no
function/tasktriggers — see The triggers.
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.
2026-08-25 — dev, round 2
One bug report from real VS Code use ("the begin/end are not aligned — the
end lands deeper than its opener") and one feature request (more triggers).
The bug: read the client's source before writing a line. The lead's
diagnosis was right and is now verified against microsoft/vscode main
rather than assumed. Everything quoted here I read directly:
src/vs/editor/contrib/snippet/browser/snippetSession.ts—static adjustWhitespace(model, position, adjustIndentation, snippet, filter?).lineLeadingWhitespace = getLeadingWhitespace(line, 0, position.column - 1); the snippet's first line is onlymodel.normalizeIndentation(lines[0])(no prepend, becausesnippet.offset(marker) === 0), a text marker that starts right after a line break gets the prepend too, andfor (let i = 1; i < lines.length; i++) lines[i] = model.normalizeIndentation(lineLeadingWhitespace + lines[i]). In the same file,_defaultOptionsis{ overwriteBefore: 0, overwriteAfter: 0, adjustWhitespace: true, clipboardText: undefined, overtypingCapturer: undefined }—adjustWhitespacedefaults totrue.src/vs/editor/contrib/inlineCompletions/browser/model/inlineCompletionsModel.ts— the accept path isSnippetController2.get(editor)?.insert(action.snippetInfo.snippet, { undoStopBefore: false }). NoadjustWhitespaceis passed, so the defaulttrueapplies and there is no LSP-side field that could switch it off:InlineCompletionItemhas noinsertTextMode, andvscode-languageclient'sasInlineCompletionItemreads onlyinsertText(andfilterText/commandif truthy).src/vs/editor/contrib/inlineCompletions/browser/controller/commands.tsis only the action layer (controller.model.get()?.accept(controller.editor)).src/vs/editor/contrib/suggest/browser/suggestController.ts— the popup path issnippetController.insert(insertText, { …, adjustWhitespace: !(item.completion.insertTextRules! & CompletionItemInsertTextRule.KeepWhitespace), … }). Same adjustment, but with an opt-out, and the opt-out is reachable from LSP:protocolConverter.js:342-346(vendored, 9.0.1) setsresult.keepWhitespace = truewheninsertTextMode === InsertTextMode.asIs,extHostLanguageFeatures.ts's_convertCompletionItemturns that intoCompletionItemInsertTextRule.KeepWhitespace, andcompletion.js:59shows the client advertisinginsertTextModeSupport.valueSet: [asIs, adjustIndentation], so the field is negotiated and honoured..../model/provideInlineCompletions.ts— the preview text issnippet.toString()(tabstops removed, defaults kept) with no adjustment, and.../view/ghostText/ghostTextView.tsrenders those lines verbatim, expanding\tat the editor'stabSize.
So the popup was double-indenting too, silently, since 0.4.0 — nobody had reported it because the popup's templates are usually accepted at shallow indentation where twice a small number still looks plausible.
Two different fixes, because the two paths offer different escapes.
- Inline has no field, so the text has to change:
rendernow emits one\tper indent step and nobaseat all, and no longer takes aLayout.normalizeIndentationre-spells the leading run in the user's owntabSize/insertSpaces, so\tis exactly "one more level, however you write levels". Deviation from the brief's sketch, recorded: the brief said "keep the absolute layout for the plain-text fallback" — there is no plain-text fallback on this path (an inline completion has nosnippetSupportto negotiate), so nothing was kept. - Popup keeps its absolute layout and sends
insertTextMode: asIsinstead. Deviation from the brief's expected shape, deliberately. The brief expected relative bodies there too, butasIsis strictly better on that path: it fixes the snippet and the plain-text spelling with one field, it leavesTemplate::render's single renderer for both spellings intact (the_two_spellings_of_a_body_are_the_same_textstill holds), it keepslucisv.indentmeaningful for the popup, and it is the protocol saying what we mean — "this text is already positioned" — rather than a guess about what the client will do. The same field went on the module-instantiation skeleton (completion.rs'sitem), which is laid out by the sameLayoutand had the identical latent bug; flagged for the lead because that skeleton belongs torefactor-instantiate, though the code is incompletion.rs. completion::layout_atis private again: this module was its only other caller.
Consequence, documented in three places (Assumptions here, the
lucisv.inlineTemplates setting description, the module doc comment):
lucisv.indent no longer sizes an accepted ghost snippet. The editor does.
That is more correct — it matches whatever the user's tab settings are — but
it is a visible behaviour change. The preview is now drawn one tab from
column zero instead of at its final column, since no adjustment runs before
Tab; correctness of the accepted text wins, and it is written down rather
than discovered.
The trigger table grew four capabilities, all data. opener is a token
sequence (always @( needs @ then (); dialect: Option<Dialect> gates
a body to .sv or to .v via templates::dialect; bodies is a slice, so
one trigger can answer with a list; and Unclosed gained ParenAndScope for
a body that writes both a ) and a closer for the user's own keyword.
Gates, one per construct, each documented in Assumptions. The paren gate
is the existing stack (a_later_call_does_not_cancel_the_paren_just_typed
still pins it). The scope gate is pairs::analyze saying this keyword's own
span is in unmatched_open, which is why case ( typed above an already
closed case still offers — that case really is unclosed — while case (
typed above a bare endcase does not. Both are pinned
(a_case_that_already_has_its_endcase_offers_nothing). pairs.rs already
knows disable fork; and wait fork; open nothing, so the fork trigger
inherits that for free; there is a test.
Hygiene tests were generalised rather than duplicated. every() walks
every body of every trigger. planted maps a keyword to the position its
construct is legal at (module at file scope, generate/always/always_ff
at item position, everything else at statement position) with statement
position as the default, so a future trigger either parses there or fails
loudly. accepted() models what VS Code writes — prepend the base, widen each
\t to one step — and every_accepted_ghost_parses feeds that, filled in,
to the parser: the test now checks the text the user really ends up with
rather than the text the server sends. Two tests are new and derived rather
than restated: every_accepted_ghost_is_scope_balanced runs pairs::analyze
over what the user typed plus what Tab writes, and every_gate_is_the_one_the_body_needs
works out from each body whether it closes a scope it did not open, and
asserts the gate matches.
Not added, as instructed: no function/task triggers. Their accepted
text cannot parse without a name in a position no placeholder reaches, and no
clean shape turned up. Reasoning is in The triggers so the next person does
not re-derive it.
No new popup templates. The brief allowed adding generate and a module
declaration to templates.rs for parity; not taken. Both are already covered
by the static VS Code snippets (genfor, module, modulep) which
completion-templates' Reconciliation deliberately keeps because a file
template is worth having before the server starts, and adding server
templates that collide with them would undo that ruling. Ghost text does not
collide: it fires on a keyword the user has finished typing, not on a prefix
in a list.
Gates: cargo fmt --all -- --check clean; cargo clippy --all-targets --workspace zero warnings; cargo test --workspace 1633 passed / 0 failed /
4 ignored (up from 1614); node editors/vscode/smoke.js target/debug/lucisv-server
→ smoke: OK; node --check editors/vscode/smoke.js and a JSON.parse of
package.json both clean. No commit, no push.
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 whateverlucisv-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/lucisv_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/lucisv_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/lucisv_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, lucisv/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 lucisv.*
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 lucisv.inlineTemplates (default true) and settings.rs's
lucisv.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/lucisv_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/lucisv_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/lucisv_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/lucisv_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.
2026-08-25 — QA, round 2
Verdict: pass. No corruption risk (verify.rs and vlog_formatter/ are
untouched — confirmed by their absence from git diff --stat), no defect in
the shipped code. Everything below is either a confirmation with a
independent re-derivation, or a small hardening test added because the round
asked for a wider net than the dev's own suite cast. No fix was needed.
Gates
cargo fmt --all -- --check: clean (after formatting my own additions — see What I changed).cargo clippy --all-targets --workspace: zero warnings.cargo test --workspace: 1644 passed / 0 failed / 4 ignored (up from the round-2 dev's 1633 — my 11 new tests, all ininline.rs; full tail below).cargo build -p lucisv_server && node editors/vscode/smoke.js target/debug/lucisv-server:smoke: OK. Ran with the debug binary's explicit path, not a barelucisv-server, for the reason round 1's QA log already flagged (a stale$PATHbinary predating this feature answerscapability missing).node --check editors/vscode/smoke.jsand aJSON.parseofeditors/vscode/package.json: both clean.
Item 2 — simulating VS Code's insertion end to end. This is the item the
round exists for, so it got the most independent work: a second, from-source
re-implementation of TextModel.normalizeIndentation/
normalizeIndentationFromWhitespace and SnippetSession.adjustWhitespace
(normalize_indentation_from_whitespace, normalize_indentation,
accepted_faithful — crates/lucisv_server/src/inline.rs:1108-1177), built
straight from the quoted VS Code source rather than from the dev's accepted()
shortcut, so a divergence in the shortcut would have somewhere independent to
show up.
the_accepted_helper_matches_vscodes_own_algorithm_for_a_self_consistent_buffer(inline.rs:1179) cross-checksaccepted()againstaccepted_faithful()for every trigger's every body, at depths 0/1/2/5, in spaces-at-2, spaces-at-4 and tabs. All agree. This is not a coincidence worth leaving unexplained:accepted()'s shortcut (prependbaseverbatim, re-spell only the\ts the body added) is provably equal to the real column-counting algorithm exactly whenbaseis already spelled as a whole number of the editor's own indent unit — the ordinary case, and the only one the dev's suite or mine exercises. A buffer whose on-disk indentation uses a different character or width than the editor's currenttabSize/insertSpaces(a tab-indented file opened underinsertSpaces: true, say) would make VS Code re-spell the trigger line's own leading run too, not just the inserted\ts — but that is a fact aboutnormalizeIndentationapplied to pre-existing text the server never wrote and cannot control, not something this feature's fix could get right or wrong. Noted here rather than filed, because there is no code in this feature's scope to act on it.every_bodys_first_line_is_stable_under_normalization(inline.rs:1206) — a narrower, permanent finding.accepted()'s line-0 handling (inline.rs'saccepted,out.push(line.to_string())forindex == 0— no normalization at all) is a shortcut of its own: the realadjustWhitespacenormalizes line 0 too (lines[0] = model.normalizeIndentation(lines[0])). It is correct today only because every body's first line has either no leading whitespace or exactly one leading space (themoduletrigger's" ${1:name};"), and a single space is a fixed point ofnormalizeIndentationat everyindent_sizeVS Code allows (1 space rounds to 0 tabs + 1 space remainder regardless oftabSize). This test pins that fixed-point property directly, at four configs, so a future body that picked up two or more leading spaces on its first line would fail loudly here rather than silently making every other test'saccepted()calls wrong in a way nothing else would catch.every_bodys_closer_lands_level_with_the_trigger_and_its_interior_one_step_in(inline.rs:1232) is the user's exact complaint, checked generically: for every trigger's every body, at depths 0/1/2/5, in two-space, four-space and tab indentation, every line's accepted indentation matches the table's own(level, text)metadata, and the closer (every body's last line) is asserted to be level 0 — never a step deeper than its opener. All pass.
Net: the fix is correct, and the two round-1-style tests above turn "I looked at a few cases and it seemed right" into something that would fail on its own if the table or the renderer regressed.
Item 3 — attacking the new triggers. Everything on the requested list, tried live against the built server via the unit-test harness (not just re-reading the dev's own tests):
| Attack | Result |
|---|---|
casez ( in a .v file |
offered — case/casez/casex are dialect-None (casez_triggers_in_a_verilog_file_too, inline.rs:1273) |
for ( in .v, .sv, and a pathless (untitled:) buffer |
.sv and .v were the dev's own test; pathless added (a_for_loop_in_a_pathless_buffer_gets_the_verilog_body, inline.rs:1281) — resolves to the Verilog body, matching templates::dialect's documented default |
always @( |
exactly two items, posedge first (dev's test, re-verified) |
always_ff @( in .sv vs .v |
one item / none (dev's test, re-verified) |
always @ ( — a space between @ and ( |
still two items — tokens carry no inter-token whitespace, so the opener-sequence match sees @ then ( regardless (always_at_space_paren_still_offers_both_items, inline.rs:1305); pins the opposite spacing from the dev's tight always@( test |
module mid-file, above an existing closed module |
offers — the new module's own span is what pairs::analyze reports unmatched, not a global count (module_mid_file_above_an_existing_closed_module_still_offers, inline.rs:1317) |
case ( above an already-closed case, and directly in front of a bare endcase |
both the dev's own test (a_case_that_already_has_its_endcase_offers_nothing) — re-verified, no change needed |
generate inside a module with a balanced generate/endgenerate pair elsewhere |
offers — the earlier, closed pair does not cancel the new one's own openness (generate_offers_even_when_an_earlier_generate_is_balanced, inline.rs:1328) |
fork in both dialects |
offers in both (fork_offers_in_both_dialects, inline.rs:1337) — fork is dialect-None, as it should be |
casex ( whose paren closes two lines down |
declined — the paren half of Unclosed::ParenAndScope alone is enough (a_casex_whose_paren_is_closed_two_lines_down_offers_nothing, inline.rs:1344), same rule a_paren_the_line_below_closes_still_counts_as_closed already pins for if ( |
if ( then, on the next line, always @( — nested unclosed parens |
each gate sees only its own paren: both still offer, if ( alone and always @( with its usual two items (nested_unclosed_parens_each_see_their_own_gate, inline.rs:1362) — paren_is_closed is a stack keyed by the exact span passed in, not a count, so neither construct's ( can be mistaken for the other's |
No attack found a false offer or a false decline. All ten new tests pass and are now permanent.
Item 4 — the insertTextMode popup change. Verified the wire value
against the lsp-types 0.97.0 source directly:
InsertTextMode::AS_IS = InsertTextMode(1),
ADJUST_INDENTATION = InsertTextMode(2) — matching LSP's own asIs = 1.
Both tests/e2e.rs pins (:1258 template item, :1625 module skeleton)
assert insertTextMode == 1, correctly. Confirmed insert_text_mode is set
on exactly the two multi-line item builders
(grep -n "insert_text_mode" crates/lucisv_server/src/completion.rs → two
hits) and that Items::simple — the keyword/word/index tiers' single-line
items — builds with ..Default::default(), leaving it None; no leak.
Client capability path (insertTextModeSupport in the vendored
completion.js) traced end to end. Full detail, including the constant's
provenance and the flagged brief typo (the QA brief's own parenthetical said
"asIs (2)", which is actually AdjustIndentation — checked against source
rather than assumed, and the shipped code uses 1 correctly), is logged in
docs/features/completion-templates/README.md's matching 2026-08-25 QA
entry, since the code lives in that feature's file.
Item 5 — regression. Full cargo test --workspace green (above) exercises
every round-1 test unchanged: suppression negatives, the true-EOF fix, CRLF,
UTF-16 positions, the setting off-switch
(the_setting_turns_the_whole_feature_off), and deep nesting
(a_deeply_nested_file_neither_crashes_nor_misses_the_trigger, depth 3,000).
That last one's own comment already records that pairs::analyze's O(depth²)
scan — round 1's Finding 2 — was fixed and pinned linear in a separate,
already-committed change (83eb908, outside this diff); re-confirmed here
only that the comment matches the current state (it does) and that the fix
commit is not part of this round's uncommitted diff (it is not — git log
shows it landed before round 2 started).
Item 6 — scope check. git diff --stat against the claimed file list:
exact match — crates/lucisv_server/src/{inline.rs,completion.rs},
crates/lucisv_server/tests/e2e.rs, editors/vscode/{smoke.js,package.json},
and the two feature READMEs. templates.rs is untouched (absent from the
diff), confirming the dev's "no new popup templates" claim structurally, not
just by reading the work log. No unwrap()/expect()/panic! in
non-test code: checked every + line of completion.rs's diff and every
line of inline.rs above its #[cfg(test)] boundary — none found. Layout
removal from inline.rs left no dead code: grep -n Layout crates/lucisv_server/src/inline.rs — zero hits outside doc comments;
layout_at is fn (private) in completion.rs, called only from within
that same file (completion.rs:211 and :293, both inside
completion.rs itself), matching the "no second caller left" claim —
inline.rs no longer names it at all. docs/features/completion-templates/README.md's own
The indentation contract section documents the layout_at handshake
change on its side; no stale mention of a shared layout_at remained in
either README.
What I changed
- No fixes — nothing broken was found.
- Tests added, all in
crates/lucisv_server/src/inline.rs:the_accepted_helper_matches_vscodes_own_algorithm_for_a_self_consistent_buffer,every_bodys_first_line_is_stable_under_normalization,every_bodys_closer_lands_level_with_the_trigger_and_its_interior_one_step_in,casez_triggers_in_a_verilog_file_too,a_for_loop_in_a_pathless_buffer_gets_the_verilog_body,always_at_space_paren_still_offers_both_items,module_mid_file_above_an_existing_closed_module_still_offers,generate_offers_even_when_an_earlier_generate_is_balanced,fork_offers_in_both_dialects,a_casex_whose_paren_is_closed_two_lines_down_offers_nothing,nested_unclosed_parens_each_see_their_own_gate. Plus the two helper functions (normalize_indentation_from_whitespace,normalize_indentation) andaccepted_faithfulthe first three tests are built on. - No commit, no push.
Final test-suite tail (cargo test --workspace, summed across every
test result: line rather than trusted from one):
test result: ok. 557 passed; 0 failed; 4 ignored; 0 measured; 0 filtered out; finished in 2.13s
Running tests/e2e.rs (target/debug/deps/e2e-...)
test result: ok. 29 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out; finished in 3.27s
1644 passed / 0 failed / 4 ignored across the workspace (1633 + my 11).
cargo fmt --all -- --check and cargo clippy --all-targets --workspace
both clean. node editors/vscode/smoke.js target/debug/lucisv-server →
smoke: 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.
2026-08-25 — lead, round 2. Approved and committed.
- The misalignment root cause is proven, not assumed: dev quoted VS Code's
SnippetSession.adjustWhitespaceand the inline-accept path (noadjustWhitespaceopt-out exists for inline completions), and QA rebuilt the normalization from the same source as an independent model — both agree at every trigger, depth, and tab/space config, and the closer-lands-level property the user reported broken is now pinned directly (every_bodys_closer_lands_level_with_the_trigger_...). - The asymmetric fix is right: relative
\tbodies where the protocol has no opt-out (inline),insertTextMode: asIswhere it does (popup), each documented as the sibling of the other.lucisv.indentno longer sizing ghost snippets is the correct trade and is stated in the setting text. - Trigger-table review: all twelve designer constructs check out; the two
case-arm and case-gate deviations from the brief are both improvements
and both pinned.
function/taskcorrectly declined (no parseable accepted text). The first-line-normalization stability pin QA added closes the one latent hazard I could find in the accepted() shortcut. - Gates re-run by the lead before commit. Ships as 0.7.0.