diff --git a/crates/vfmt_server/src/completion.rs b/crates/vfmt_server/src/completion.rs index 2bd2f5f..eddd5ba 100644 --- a/crates/vfmt_server/src/completion.rs +++ b/crates/vfmt_server/src/completion.rs @@ -27,7 +27,8 @@ use std::collections::HashSet; use lsp_types::{ CompletionItem, CompletionItemKind, CompletionList, CompletionResponse, CompletionTextEdit, - Documentation, InsertTextFormat, MarkupContent, MarkupKind, Position, Range, TextEdit, Uri, + Documentation, InsertTextFormat, InsertTextMode, MarkupContent, MarkupKind, Position, Range, + TextEdit, Uri, }; use vlog_parser::token::{Comment, Token, TokenKind}; use vlog_parser::{TextRange, KEYWORDS}; @@ -67,6 +68,25 @@ const TIER_TEMPLATE: char = '3'; const TIER_KEYWORD: char = '4'; const TIER_WORD: char = '5'; +/// What a multi-line item tells the client about its own whitespace. +/// +/// Every skeleton here is laid out at the *site's* indentation already: a +/// `Layout`'s `base` is the trigger line's leading whitespace, and every line +/// after the first carries it. An editor that "helpfully" indents the +/// insertion again would double it — VS Code's `SnippetSession.adjustWhitespace` +/// prepends the insertion line's own indentation to every line after the first, +/// and it is on by default (`SuggestController._insertSuggestion` passes +/// `adjustWhitespace: !(insertTextRules & KeepWhitespace)`). `asIs` is the +/// protocol's way of saying "the text is already positioned, do not touch it", +/// and `vscode-languageclient` turns it into exactly the `keepWhitespace` flag +/// that clears the rule. Single-line items neither need it nor are harmed by +/// it; only the two tiers that write more than one line send it. +/// +/// This is the sibling of the fix `inline.rs` had to make differently: an +/// inline completion has no such field, so its bodies are *relative* instead. +/// See `docs/features/inline-templates/README.md`, 2026-08-25. +const KEEP_MY_INDENTATION: InsertTextMode = InsertTextMode::AS_IS; + /// The scopes a module instantiation may be written directly inside. const ITEM_SCOPES: &[&str] = &["module", "macromodule", "interface", "program", "generate", "begin"]; @@ -299,10 +319,11 @@ fn offered(template: &Template, at_item: bool, at_statement: bool) -> bool { /// How generated text is indented at `offset`: the line's own indentation, and /// one step as `vfmt.indent` spells it. /// -/// Shared with `inline.rs`, which offers the same skeletons as ghost text: two -/// features that lay out the same body must not be able to indent it -/// differently. -pub fn layout_at(ws: &Workspace, doc: &Document, offset: u32) -> Layout { +/// Private again as of 2026-08-25. `inline.rs` used to share it, so that ghost +/// text and the completion list could not indent the same body differently; +/// ghost text now emits *relative* indentation and lets the editor place it +/// (see `inline.rs`'s `render`), so there is no second caller left. +fn layout_at(ws: &Workspace, doc: &Document, offset: u32) -> Layout { let step = " ".repeat(ws.client_settings().indent.unwrap_or(2)); Layout { base: line_indent(&doc.text, offset), step } } @@ -435,6 +456,7 @@ impl Items { true => InsertTextFormat::SNIPPET, false => InsertTextFormat::PLAIN_TEXT, }), + insert_text_mode: Some(KEEP_MY_INDENTATION), text_edit: Some(CompletionTextEdit::Edit(TextEdit { range: self.range, new_text: template.render(layout, snippets), @@ -587,6 +609,7 @@ fn item( true => InsertTextFormat::SNIPPET, false => InsertTextFormat::PLAIN_TEXT, }), + insert_text_mode: Some(KEEP_MY_INDENTATION), text_edit: Some(CompletionTextEdit::Edit(TextEdit { range: doc.positions().range(replacing), new_text, diff --git a/crates/vfmt_server/src/inline.rs b/crates/vfmt_server/src/inline.rs index 6f7b944..d46166d 100644 --- a/crates/vfmt_server/src/inline.rs +++ b/crates/vfmt_server/src/inline.rs @@ -6,24 +6,25 @@ //! the tabstops land the cursor inside the parens first and on the indented //! body line second. //! -//! Two things here are deliberate. The **triggers are data** — a keyword, the -//! punctuation that must follow it, the check that says the construct is still -//! unfinished, and a body in `templates.rs`'s `(steps, text)` form — so -//! `case`/`endcase` is one more entry and no more code. And the **response -//! types are hand-rolled**: `lsp_types`' `InlineCompletionItem` is the old 3.18 -//! draft (`insertText: String`), while the client in use implements the newer -//! one, where only `insertText: {"kind": "snippet", "value": …}` becomes a -//! snippet and a bare string is inserted as plain text — tabstops and all. See -//! `docs/features/inline-templates/README.md`. +//! Three things here are deliberate. The **triggers are data** — a keyword, the +//! punctuation that must follow it, the dialect it belongs to, the check that +//! says the construct is still unfinished, and one body per item in +//! `templates.rs`'s `(steps, text)` form. The **response types are +//! hand-rolled**: `lsp_types`' `InlineCompletionItem` is the old 3.18 draft +//! (`insertText: String`), while the client in use implements the newer one, +//! where only `insertText: {"kind": "snippet", "value": …}` becomes a snippet +//! and a bare string is inserted as plain text — tabstops and all. And the +//! bodies are **indented relative to the trigger line, one `\t` per step**, +//! because the editor prepends that line's own indentation when it inserts the +//! snippet; see `render`. See `docs/features/inline-templates/README.md`. use lsp_types::{Position, Range, Uri}; use vlog_parser::token::{Token, TokenKind}; use vlog_parser::TextRange; -use vlog_refactor::Layout; -use crate::completion::layout_at; use crate::pairs; use crate::state::{Document, Workspace}; +use crate::templates::{self, Dialect}; /// One line of a body: how many indent steps it sits in, and its text. The /// same shape `templates.rs` writes its skeletons in. @@ -31,18 +32,21 @@ type Line = (u8, &'static str); /// What must still be unfinished before a trigger offers anything. /// -/// Neither is a parse, and neither can see inside a `` `ifdef `` arm or a macro -/// body. Being wrong costs one grey suggestion the user ignores: nothing is -/// written to the buffer until Tab. +/// None of these is a parse, and none can see inside a `` `ifdef `` arm or a +/// macro body. Being wrong costs one grey suggestion the user ignores: nothing +/// is written to the buffer until Tab. #[derive(Clone, Copy)] enum Unclosed { - /// The `(` just typed has no `)` anywhere after it — counted over the - /// whole token stream. The snippet writes the `)`, so it may only be - /// offered when one is owed. + /// The `(` just typed is never closed. The snippet writes the `)`, so it + /// may only be offered when one is owed. Paren, /// `pairs::analyze` reports *this* keyword — matched by its own span, not /// by a global count — as an opener that never closed. Scope, + /// Both, for a body that writes a `)` *and* a scope closer: `case (` + /// finishes with `endcase`, so a `case` that already has one must not be + /// given a second. + ParenAndScope, } /// One inline template: what the user must have just typed, and what appears @@ -50,35 +54,141 @@ enum Unclosed { struct Trigger { /// The keyword that opens the construct. keyword: &'static str, - /// The punctuation that must follow the keyword, if any. `if (` needs the + /// The punctuation that must follow the keyword, in order. `if (` needs the /// open paren — it is what says the user has committed to the `if` rather - /// than to an identifier starting with those letters — and `begin` stands - /// alone. - opener: Option<&'static str>, + /// than to an identifier starting with those letters — `always @(` needs + /// both of its symbols, and `begin` stands alone. + opener: &'static [&'static str], + /// The dialect this body belongs to, when it is not legal in both. + dialect: Option, gate: Unclosed, - /// The skeleton, written exactly as a `templates.rs` body is: the first - /// line starts at the cursor and every later one is indented. - body: &'static [Line], + /// One skeleton per item offered, in the order the client cycles them. + /// Each is written exactly as a `templates.rs` body is: the first line + /// starts at the cursor and every later one is indented. + bodies: &'static [&'static [Line]], } +/// The opener of a construct whose header is parenthesised. +const PAREN: &[&str] = &["("]; + +/// The opener of an `always`-family block: the event-control `@(`. +const EVENT: &[&str] = &["@", "("]; + +/// What `case (`, `casez (` and `casex (` all finish with — the user has +/// already typed the keyword, so one body serves the three. +const CASE_BODY: &[Line] = + &[(0, "${1:sel})"), (1, "${2:value}: $0;"), (1, "default: ;"), (0, "endcase")]; + +/// The bodies of the keywords that stand alone. Everything each offers goes on +/// the lines *after* the word the user just typed, so the first line is empty. +const BEGIN_BODY: &[Line] = &[(0, ""), (1, "$0"), (0, "end")]; +const FORK_BODY: &[Line] = &[(0, ""), (1, "$0"), (0, "join")]; +const GENERATE_BODY: &[Line] = &[(0, ""), (1, "$0"), (0, "endgenerate")]; + /// Every construct that offers ghost text. /// -/// Deliberately two. `case`/`endcase` and `module`/`endmodule` fit the table -/// unchanged, and neither was asked for yet. +/// The order is the order `triggered` tries them, which only matters when two +/// entries could match the same tokens: the two `for` bodies are told apart by +/// their dialect, and nothing else overlaps. const TRIGGERS: &[Trigger] = &[ Trigger { keyword: "if", - opener: Some("("), + opener: PAREN, + dialect: None, gate: Unclosed::Paren, - body: &[(0, "${1:cond}) begin"), (1, "$0"), (0, "end")], + bodies: &[&[(0, "${1:cond}) begin"), (1, "$0"), (0, "end")]], + }, + Trigger { + keyword: "while", + opener: PAREN, + dialect: None, + gate: Unclosed::Paren, + bodies: &[&[(0, "${1:cond}) begin"), (1, "$0"), (0, "end")]], + }, + Trigger { + keyword: "for", + opener: PAREN, + dialect: Some(Dialect::SystemVerilog), + gate: Unclosed::Paren, + bodies: &[&[(0, "int ${1:i} = 0; $1 < ${2:N}; $1++) begin"), (1, "$0"), (0, "end")]], + }, + Trigger { + keyword: "for", + opener: PAREN, + dialect: Some(Dialect::Verilog), + gate: Unclosed::Paren, + bodies: &[&[(0, "${1:i} = 0; $1 < ${2:N}; $1 = $1 + 1) begin"), (1, "$0"), (0, "end")]], + }, + Trigger { + keyword: "case", + opener: PAREN, + dialect: None, + gate: Unclosed::ParenAndScope, + bodies: &[CASE_BODY], + }, + Trigger { + keyword: "casez", + opener: PAREN, + dialect: None, + gate: Unclosed::ParenAndScope, + bodies: &[CASE_BODY], + }, + Trigger { + keyword: "casex", + opener: PAREN, + dialect: None, + gate: Unclosed::ParenAndScope, + bodies: &[CASE_BODY], + }, + Trigger { + keyword: "always_ff", + opener: EVENT, + dialect: Some(Dialect::SystemVerilog), + gate: Unclosed::Paren, + bodies: &[&[(0, "posedge ${1:clk}) begin"), (1, "$0"), (0, "end")]], + }, + Trigger { + keyword: "always", + opener: EVENT, + dialect: None, + gate: Unclosed::Paren, + // Two items, clocked first: `always @(` is overwhelmingly a flop, and + // the client cycles to the second with one keystroke. + bodies: &[ + &[(0, "posedge ${1:clk}) begin"), (1, "$0"), (0, "end")], + &[(0, "*) begin"), (1, "$0"), (0, "end")], + ], }, Trigger { keyword: "begin", - opener: None, + opener: &[], + dialect: None, gate: Unclosed::Scope, - // The first line is empty: everything this offers goes on the lines - // *after* the `begin` the user just typed. - body: &[(0, ""), (1, "$0"), (0, "end")], + bodies: &[BEGIN_BODY], + }, + Trigger { + keyword: "fork", + opener: &[], + dialect: None, + gate: Unclosed::Scope, + bodies: &[FORK_BODY], + }, + Trigger { + keyword: "generate", + opener: &[], + dialect: None, + gate: Unclosed::Scope, + bodies: &[GENERATE_BODY], + }, + Trigger { + keyword: "module", + opener: &[], + dialect: None, + gate: Unclosed::Scope, + // The leading space and the `;` are what make the accepted text parse: + // a module header needs a name, and a placeholder cannot supply one + // after the fact. + bodies: &[&[(0, " ${1:name};"), (1, "$0"), (0, "endmodule")]], }, ]; @@ -135,19 +245,29 @@ pub fn inline_completions(ws: &Workspace, uri: &Uri, position: Position) -> Opti if !unfinished(doc, trigger, opened) { return None; } - let layout = layout_at(ws, doc, offset); let at = Range { start: position, end: position }; Some(InlineItems { - items: vec![InlineItem { - insert_text: SnippetValue { kind: "snippet", value: render(trigger.body, &layout) }, - range: at, - }], + items: trigger + .bodies + .iter() + .map(|body| InlineItem { + insert_text: SnippetValue { kind: "snippet", value: render(body) }, + range: at, + }) + .collect(), }) } -/// The trigger the tokens ending at `offset` spell, and the span of the one -/// token that must still be waiting for its counterpart: the `(` for a paren -/// gate, the keyword itself for a scope one. +/// The two tokens a gate can ask about: the keyword that opens the construct, +/// and the last token the user typed — the `(` whenever the trigger has one. +#[derive(Clone, Copy)] +struct Opened { + keyword: TextRange, + last: TextRange, +} + +/// The trigger the tokens ending at `offset` spell, and the spans its gate +/// needs. /// /// The cursor must sit *exactly* at the last token's end: that is the crisp /// "you just typed this" rule, and it is what keeps the body's first character @@ -155,7 +275,7 @@ pub fn inline_completions(ws: &Workspace, uri: &Uri, position: Position) -> Opti /// string safe without a single check of its own — a comment is lexer trivia /// and never a token, and `"if ("` is one `String` token whose text is not a /// keyword. -fn triggered(doc: &Document, offset: u32) -> Option<(&'static Trigger, TextRange)> { +fn triggered(doc: &Document, offset: u32) -> Option<(&'static Trigger, Opened)> { // `Eof` is a zero-width sentinel `tokenize` appends at `text.len()`, so // when the buffer's very last byte is the trigger's own last character — // no trailing newline, nothing typed after it yet — it shares the @@ -169,39 +289,41 @@ fn triggered(doc: &Document, offset: u32) -> Option<(&'static Trigger, TextRange if last.span.end != offset { return None; } + let dialect = templates::dialect(doc.path.as_deref()); for trigger in TRIGGERS { - let keyword = match trigger.opener { - None => last, - Some(punctuation) => { - if !last.is_sym(punctuation) { - continue; - } - let Some(before) = index.checked_sub(1).and_then(|i| doc.tokens.get(i)) else { - continue; - }; - before - } - }; + if matches!(trigger.dialect, Some(only) if only != dialect) { + continue; + } + let Some(at) = index.checked_sub(trigger.opener.len()) else { continue }; + let spelled = trigger + .opener + .iter() + .enumerate() + .all(|(i, sym)| doc.tokens.get(at + 1 + i).is_some_and(|t| t.is_sym(sym))); + if !spelled { + continue; + } + let Some(keyword) = doc.tokens.get(at) else { continue }; if keyword.kind == TokenKind::Keyword && keyword.text == trigger.keyword { - return Some(( - trigger, - match trigger.gate { - Unclosed::Paren => last.span, - Unclosed::Scope => keyword.span, - }, - )); + return Some((trigger, Opened { keyword: keyword.span, last: last.span })); } } None } -/// Whether the token at `opened` really is still waiting for its counterpart. -fn unfinished(doc: &Document, trigger: &Trigger, opened: TextRange) -> bool { +/// Whether the construct the user opened really is still waiting to be closed. +fn unfinished(doc: &Document, trigger: &Trigger, opened: Opened) -> bool { + let paren = || !paren_is_closed(&doc.tokens, opened.last); + let scope = || { + pairs::analyze(&doc.tokens).unmatched_open.iter().any(|open| open.span == opened.keyword) + }; match trigger.gate { - Unclosed::Paren => !paren_is_closed(&doc.tokens, opened), - Unclosed::Scope => { - pairs::analyze(&doc.tokens).unmatched_open.iter().any(|open| open.span == opened) - } + Unclosed::Paren => paren(), + Unclosed::Scope => scope(), + // The paren check first: it is a flat pass over the tokens, and + // skipping `pairs::analyze` when it already says no is what keeps this + // cheap on a keystroke. + Unclosed::ParenAndScope => paren() && scope(), } } @@ -233,20 +355,36 @@ fn rest_of_line_is_blank(text: &str, offset: u32) -> bool { line.chars().all(char::is_whitespace) } -/// A body laid out at `layout`, tabstops left where they are. +/// A body as a snippet: **relative** indentation, one `\t` per step, and no +/// trace of where in the file it is going. /// -/// The first line starts at the cursor, which the editor has already indented, -/// so only the lines after it carry `base`. There is no plain-text spelling -/// here — unlike a completion item, an inline completion has no -/// `snippetSupport` to negotiate. -fn render(body: &[Line], layout: &Layout) -> String { +/// This is not the layout `templates.rs` renders, and the difference is the +/// whole of the 0.6.0 misalignment bug. VS Code inserts an accepted inline +/// completion through `SnippetController2.insert`, whose `adjustWhitespace` +/// option defaults to `true`, and `SnippetSession.adjustWhitespace` then does +/// two things to the snippet text: it prepends the insertion line's own +/// leading whitespace to every line after the first, and it runs each result +/// through `TextModel.normalizeIndentation`, which rewrites the leading +/// whitespace run in the editor's own tabs-or-spaces. A body that had already +/// baked the line's indentation in came out at *twice* it, with the `end` two +/// levels left of the body instead of level with its opener. +/// +/// So the server says "one step in" and the editor says where and how wide: +/// `\t` is the one character `normalizeIndentation` re-spells as the user's +/// own `editor.tabSize`/`insertSpaces`. The consequence is that `vfmt.indent` +/// does **not** decide the width of an accepted snippet — the editor's +/// settings do, which is the more correct answer for text the editor is +/// writing. There is no plain-text spelling here: unlike a completion item, an +/// inline completion has no `snippetSupport` to negotiate. +fn render(body: &[Line]) -> String { let mut lines: Vec = Vec::with_capacity(body.len()); for (index, (level, text)) in body.iter().enumerate() { let mut line = String::new(); + // The first line starts at the cursor, which the editor has already + // indented and which `adjustWhitespace` leaves alone. if index > 0 { - line.push_str(&layout.base); for _ in 0..*level { - line.push_str(&layout.step); + line.push('\t'); } } line.push_str(text); @@ -261,12 +399,12 @@ mod tests { use crate::settings::ClientSettings; use crate::uri::path_to_uri; use std::path::PathBuf; + use std::str::FromStr; - /// A one-file workspace with `top.sv` open and the cursor at `needle`'s - /// end. No files on disk: nothing here reads the index. - fn asking(text: &str, needle: &str) -> (Workspace, Uri, Position) { - let path = PathBuf::from("/rtl/top.sv"); - let uri = path_to_uri(&path).expect("uri"); + /// A one-file workspace with `path` open and the cursor at `needle`'s end. + /// No files on disk: nothing here reads the index. + fn asking_in(path: &str, text: &str, needle: &str) -> (Workspace, Uri, Position) { + let uri = path_to_uri(&PathBuf::from(path)).expect("uri"); let mut ws = Workspace::default(); ws.set_document(uri.clone(), text.to_string()); let offset = (text.find(needle).expect("needle present") + needle.len()) as u32; @@ -274,12 +412,50 @@ mod tests { (ws, uri, position) } - /// The snippet offered at `needle`'s end, if any. + /// The same, in a SystemVerilog buffer. + fn asking(text: &str, needle: &str) -> (Workspace, Uri, Position) { + asking_in("/rtl/top.sv", text, needle) + } + + /// Every snippet offered at `needle`'s end, in order. + fn all_offered(text: &str, needle: &str) -> Vec { + offered_in("/rtl/top.sv", text, needle) + } + + /// Every snippet offered at `needle`'s end in a buffer called `path`. + fn offered_in(path: &str, text: &str, needle: &str) -> Vec { + let (ws, uri, position) = asking_in(path, text, needle); + match inline_completions(&ws, &uri, position) { + None => Vec::new(), + Some(items) => items.items.iter().map(|i| i.insert_text.value.clone()).collect(), + } + } + + /// The one snippet offered at `needle`'s end, if any. fn offered(text: &str, needle: &str) -> Option { - let (ws, uri, position) = asking(text, needle); - let items = inline_completions(&ws, &uri, position)?; - assert_eq!(items.items.len(), 1, "one ghost or none"); - Some(items.items[0].insert_text.value.clone()) + let mut items = all_offered(text, needle); + assert!(items.len() <= 1, "one ghost or none, got {items:?}"); + items.pop() + } + + /// `snippet` as VS Code really writes it into the buffer. + /// + /// `SnippetSession.adjustWhitespace` prepends the insertion line's own + /// leading whitespace — `base` — to every line after the first, then + /// `TextModel.normalizeIndentation` re-spells the whole leading run in the + /// editor's tabs-or-spaces, which is what turns each `\t` the server sent + /// into one `step`. + fn accepted(snippet: &str, base: &str, step: &str) -> String { + let mut out: Vec = Vec::new(); + for (index, line) in snippet.split('\n').enumerate() { + if index == 0 { + out.push(line.to_string()); + continue; + } + let steps = line.chars().take_while(|c| *c == '\t').count(); + out.push(format!("{base}{}{}", step.repeat(steps), &line[steps..])); + } + out.join("\n") } /// `snippet` with every hole filled in the way the editor would preselect @@ -289,22 +465,83 @@ mod tests { fn filled(snippet: &str) -> String { let mut out = String::new(); let mut rest = snippet; + let mut mirrors: Vec<(&str, &str)> = Vec::new(); while let Some(at) = rest.find('$') { out.push_str(&rest[..at]); rest = &rest[at + 1..]; if let Some(braced) = rest.strip_prefix('{') { let close = braced.find('}').expect("a hole is closed"); let hole = &braced[..close]; - out.push_str(hole.split_once(':').map_or("", |(_, default)| default)); + if let Some((number, default)) = hole.split_once(':') { + mirrors.push((number, default)); + out.push_str(default); + } rest = &braced[close + 1..]; continue; } - rest = rest.trim_start_matches(|c: char| c.is_ascii_digit()); + let digits = rest.len() - rest.trim_start_matches(|c: char| c.is_ascii_digit()).len(); + let number = &rest[..digits]; + // A bare `$n` repeats what `${n:…}` was given, the way the editor + // mirrors a placeholder; `$0` was never declared and is nothing. + if let Some((_, default)) = mirrors.iter().find(|(n, _)| *n == number) { + out.push_str(default); + } + rest = &rest[digits..]; } out.push_str(rest); out } + // ------------------------------------------------------------------ + // the emission contract: relative, not absolute + // ------------------------------------------------------------------ + + #[test] + fn a_snippet_is_indented_relative_to_the_trigger_line() { + // The 0.6.0 bug: the body used to carry the trigger line's own + // indentation, and VS Code prepends it *again* on insert, so the `end` + // landed a level deeper than the `begin` it closes. One `\t` per step + // and nothing else is what the editor can place correctly. + let text = "module top;\n always_comb begin\nendmodule\n"; + assert_eq!(offered(text, "always_comb begin").as_deref(), Some("\n\t$0\nend")); + } + + #[test] + fn the_editor_puts_the_end_level_with_its_opener() { + // What the user actually sees after Tab, with the two things VS Code + // does to the text modelled: the base prepended, one `\t` widened to + // the editor's indent. + let text = "module top;\n always_comb begin\nendmodule\n"; + let snippet = offered(text, "always_comb begin").expect("a ghost"); + assert_eq!(accepted(&snippet, " ", " "), "\n $0\n end"); + // ...at any depth, and in tabs as readily as in spaces. + assert_eq!(accepted(&snippet, "\t\t", "\t"), "\n\t\t\t$0\n\t\tend"); + } + + #[test] + fn the_line_indentation_never_reaches_the_snippet() { + // The same three lines however deep the trigger sits and however the + // buffer spells its indentation: the server has stopped having an + // opinion about either. + for line in ["always_comb begin", " always_comb begin", "\t\talways_comb begin"] { + let text = format!("module top;\n{line}\nendmodule\n"); + assert_eq!(offered(&text, "always_comb begin").as_deref(), Some("\n\t$0\nend")); + } + } + + #[test] + fn the_indent_setting_no_longer_reaches_a_snippet() { + // `vfmt.indent` still decides what the *formatter* writes and what the + // completion popup inserts; an accepted inline snippet is laid out by + // the editor's own tab settings, because the editor re-spells the + // leading whitespace on insert whatever the server sent. + let text = "module top;\n always_comb begin\nendmodule\n"; + let (mut ws, uri, position) = asking(text, "always_comb begin"); + ws.set_client_settings(ClientSettings { indent: Some(4), ..Default::default() }); + let items = inline_completions(&ws, &uri, position).expect("a ghost"); + assert_eq!(items.items[0].insert_text.value, "\n\t$0\nend"); + } + // ------------------------------------------------------------------ // the triggers // ------------------------------------------------------------------ @@ -314,8 +551,8 @@ mod tests { let text = "module top;\n always_comb begin\n if (\n end\nendmodule\n"; assert_eq!( offered(text, " if (").as_deref(), - Some("${1:cond}) begin\n $0\n end"), - "the site's own indentation, the condition first and the body last" + Some("${1:cond}) begin\n\t$0\nend"), + "the condition first and the body last" ); } @@ -329,33 +566,100 @@ module top; end endmodule "; - assert_eq!( - offered(text, "else if (").as_deref(), - Some("${1:cond}) begin\n $0\n end") - ); + assert_eq!(offered(text, "else if (").as_deref(), Some("${1:cond}) begin\n\t$0\nend")); } #[test] fn a_fresh_begin_offers_its_end() { let text = "module top;\n always_comb begin\nendmodule\n"; - assert_eq!(offered(text, "always_comb begin").as_deref(), Some("\n $0\n end")); + assert_eq!(offered(text, "always_comb begin").as_deref(), Some("\n\t$0\nend")); } #[test] - fn the_indent_step_is_the_one_the_client_asked_for() { - let text = "module top;\n always_comb begin\nendmodule\n"; - let (mut ws, uri, position) = asking(text, "always_comb begin"); - ws.set_client_settings(ClientSettings { indent: Some(4), ..Default::default() }); - let items = inline_completions(&ws, &uri, position).expect("a ghost"); - assert_eq!(items.items[0].insert_text.value, "\n $0\n end", "base 2 + step 4"); + fn a_while_offers_the_same_block_as_an_if() { + let text = "module top;\n initial begin\n while (\n end\nendmodule\n"; + assert_eq!(offered(text, "while (").as_deref(), Some("${1:cond}) begin\n\t$0\nend")); } #[test] - fn a_tab_indented_line_keeps_its_own_tabs() { - // `base` is the line's leading whitespace as written, not a rebuild of - // it: a buffer indented with tabs must not gain spaces from a ghost. - let text = "module top;\n\talways_comb begin\nendmodule\n"; - assert_eq!(offered(text, "always_comb begin").as_deref(), Some("\n\t $0\n\tend")); + fn a_for_loop_follows_the_buffers_dialect() { + // The same two bodies `templates.rs` offers in the popup, minus the + // `for (` the user has already typed. + let text = "module top;\n initial begin\n for (\n end\nendmodule\n"; + assert_eq!( + offered_in("/rtl/top.sv", text, "for ("), + vec!["int ${1:i} = 0; $1 < ${2:N}; $1++) begin\n\t$0\nend"], + "SystemVerilog declares the loop variable in the header" + ); + assert_eq!( + offered_in("/rtl/top.v", text, "for ("), + vec!["${1:i} = 0; $1 < ${2:N}; $1 = $1 + 1) begin\n\t$0\nend"], + "Verilog has no `++` and no local loop variable" + ); + } + + #[test] + fn every_case_flavour_offers_the_same_arms_and_an_endcase() { + for keyword in ["case", "casez", "casex"] { + let text = + format!("module top;\n always_comb begin\n {keyword} (\n end\nendmodule\n"); + assert_eq!( + offered(&text, &format!("{keyword} (")).as_deref(), + Some("${1:sel})\n\t${2:value}: $0;\n\tdefault: ;\nendcase"), + "{keyword}" + ); + } + } + + #[test] + fn casex_is_offered_here_although_the_popup_does_not_list_it() { + // `templates.rs` leaves `casex` out on purpose: it is the flavour most + // style guides warn against, and an unused entry is noise in a list. + // Ghost text is not a list — it only ever appears once the user has + // typed `casex (` and committed to it — so the noise argument does not + // apply and refusing to finish the construct would just be unhelpful. + let text = "module top;\n always_comb begin\n casex (\n end\nendmodule\n"; + assert!(offered(text, "casex (").is_some()); + } + + #[test] + fn an_always_at_offers_the_clocked_block_first_and_the_star_second() { + let text = "module top;\n always @(\nendmodule\n"; + assert_eq!( + all_offered(text, "always @("), + vec![ + "posedge ${1:clk}) begin\n\t$0\nend".to_string(), + "*) begin\n\t$0\nend".to_string(), + ], + "clocked first: `always @(` is overwhelmingly a flop" + ); + } + + #[test] + fn always_ff_is_systemverilog_only() { + let text = "module top;\n always_ff @(\nendmodule\n"; + assert_eq!( + offered_in("/rtl/top.sv", text, "always_ff @("), + vec!["posedge ${1:clk}) begin\n\t$0\nend"] + ); + assert!( + offered_in("/rtl/top.v", text, "always_ff @(").is_empty(), + "a `.v` compiler rejects `always_ff`" + ); + } + + #[test] + fn fork_generate_and_module_offer_their_own_closers() { + let text = "module top;\n initial begin\n fork\n end\nendmodule\n"; + assert_eq!(offered(text, " fork").as_deref(), Some("\n\t$0\njoin")); + + let text = "module top;\n generate\nendmodule\n"; + assert_eq!(offered(text, " generate").as_deref(), Some("\n\t$0\nendgenerate")); + + // A module needs a name before its `;`, so the body writes one — the + // leading space is deliberate, the user's cursor sits right after the + // `e` of `module`. + assert_eq!(offered("module", "module").as_deref(), Some(" ${1:name};\n\t$0\nendmodule")); } // ------------------------------------------------------------------ @@ -376,6 +680,7 @@ endmodule ), ("module top;\n initial $display(\"begin\");\nendmodule\n", "\"begin", "ditto"), ("module top;\n // begin\nendmodule\n", "// begin", "a commented begin"), + ("module top;\n // case (\nendmodule\n", "// case (", "a commented case"), ] { assert_eq!(offered(text, needle), None, "{what}: {text}"); } @@ -426,6 +731,50 @@ endmodule assert!(offered(text, "initial begin").is_some(), "this one lost its end"); } + #[test] + fn a_scope_keyword_that_already_has_its_closer_offers_nothing() { + // The same rule as `begin`, for the three keywords that joined it. + let text = "module top;\n initial begin\n fork\n join\n end\nendmodule\n"; + assert_eq!(offered(text, " fork"), None); + let text = "module top;\n generate\n endgenerate\nendmodule\n"; + assert_eq!(offered(text, " generate"), None); + let text = "module\nendmodule\n"; + assert_eq!(offered(text, "module"), None); + // `disable fork;` names a fork rather than opening one — `pairs.rs` + // knows, and the gate inherits that. + let text = "module top;\n initial begin\n disable fork\n end\nendmodule\n"; + assert_eq!(offered(text, "disable fork"), None); + } + + #[test] + fn a_case_that_already_has_its_endcase_offers_nothing() { + // Both halves of the `case (` gate matter. Here the `endcase` below is + // this `case`'s own, so a second one would leave the file unbalanced — + // even though the `(` really is unclosed. + let text = "\ +module top; + always_comb begin + case ( + endcase + end +endmodule +"; + assert_eq!(offered(text, " case ("), None, "the endcase is already there"); + // ...and when the `endcase` below belongs to a nested, complete `case`, + // the one just typed still owes its own. + let text = "\ +module top; + always_comb begin + case ( + case (b) + default: ; + endcase + end +endmodule +"; + assert!(offered(text, " case (").is_some(), "this case is genuinely unclosed"); + } + #[test] fn an_if_paren_that_is_already_closed_offers_nothing() { // A `)` further down the buffer is the one this `(` will pair with; @@ -447,10 +796,7 @@ module top; end endmodule "; - assert_eq!( - offered(text, " if (").as_deref(), - Some("${1:cond}) begin\n $0\n end") - ); + assert_eq!(offered(text, " if (").as_deref(), Some("${1:cond}) begin\n\t$0\nend")); } #[test] @@ -470,6 +816,18 @@ endmodule assert_eq!(offered(text, " if ("), None); } + #[test] + fn an_always_without_its_event_control_offers_nothing() { + // The opener is a *sequence*: both `@` and `(` must be there, in that + // order, or the user has not committed to an event-controlled block. + let text = "module top;\n always\nendmodule\n"; + assert_eq!(offered(text, " always"), None); + let text = "module top;\n always @\nendmodule\n"; + assert_eq!(offered(text, "always @"), None); + let text = "module top;\n always (\nendmodule\n"; + assert_eq!(offered(text, "always ("), None, "`(` alone is not `@(`"); + } + #[test] fn a_buffer_that_does_not_lex_is_declined() { let text = "module top;\n /* unterminated\n always_comb begin\n"; @@ -559,25 +917,22 @@ endmodule // Token spans carry no inter-token whitespace of their own, so `if(` // and `if (` must be indistinguishable to `triggered`. let text = "module top;\n always_comb begin\n if(\n end\nendmodule\n"; - assert_eq!( - offered(text, " if(").as_deref(), - Some("${1:cond}) begin\n $0\n end") - ); + assert_eq!(offered(text, " if(").as_deref(), Some("${1:cond}) begin\n\t$0\nend")); + // ...and the same for a two-symbol opener written tight. + let text = "module top;\n always@(\nendmodule\n"; + assert_eq!(all_offered(text, "always@(").len(), 2); } #[test] - fn crlf_line_endings_still_trigger_and_indent_correctly() { + fn crlf_line_endings_still_trigger() { // `rest_of_line_is_blank` splits on `\n` alone, so a CRLF file's `\r` // rides along in the slice — `char::is_whitespace('\r')` is `true`, // so it still reads as "nothing after the cursor". let text = "module top;\r\n always_comb begin\r\nendmodule\r\n"; - assert_eq!(offered(text, "always_comb begin").as_deref(), Some("\n $0\n end")); + assert_eq!(offered(text, "always_comb begin").as_deref(), Some("\n\t$0\nend")); let text = "module top;\r\n always_comb begin\r\n if (\r\n end\r\nendmodule\r\n"; - assert_eq!( - offered(text, " if (").as_deref(), - Some("${1:cond}) begin\n $0\n end") - ); + assert_eq!(offered(text, " if (").as_deref(), Some("${1:cond}) begin\n\t$0\nend")); } #[test] @@ -608,14 +963,43 @@ endmodule // the registry's own hygiene // ------------------------------------------------------------------ + /// Every body in the table, with the trigger it belongs to. + fn every() -> Vec<(&'static Trigger, &'static [Line])> { + TRIGGERS.iter().flat_map(|t| t.bodies.iter().map(move |body| (t, *body))).collect() + } + + /// What the user has typed by the time `trigger` fires. + fn typed(trigger: &Trigger) -> String { + let mut out = trigger.keyword.to_string(); + for symbol in trigger.opener { + out.push_str(symbol); + } + out + } + + /// `text` planted where its construct may legally be written. + /// + /// The default is statement position, so a trigger added without a thought + /// for this list either parses there — which is the common case — or fails + /// loudly. + fn planted(trigger: &Trigger, text: &str) -> String { + match trigger.keyword { + "module" => format!("{text}\n"), + "generate" | "always" | "always_ff" => { + format!("module vfmt_probe;\n {text}\nendmodule\n") + } + _ => format!("module vfmt_probe;\n always @(*) begin\n {text}\n end\nendmodule\n"), + } + } + #[test] fn every_hole_is_a_tabstop() { // The editor-snippets lesson: VS Code substitutes an unknown `$NAME` // with nothing and says nothing, so a system task written into a body // would vanish silently. None is written today; this is what stops one // being added unescaped. - for trigger in TRIGGERS { - for (_, line) in trigger.body { + for (trigger, body) in every() { + for (_, line) in body { let mut rest = *line; while let Some(at) = rest.find('$') { rest = &rest[at + 1..]; @@ -632,19 +1016,13 @@ endmodule #[test] fn every_accepted_ghost_parses() { - // What Tab really writes, planted where the trigger fires, handed to - // the parser. A body that did not parse would be a formatter that - // refuses the file the moment the user accepts a suggestion. - let layout = Layout { base: " ".into(), step: " ".into() }; - for trigger in TRIGGERS { - let typed = match trigger.opener { - Some(punctuation) => format!("{} {punctuation}", trigger.keyword), - None => trigger.keyword.to_string(), - }; - let text = filled(&render(trigger.body, &layout)); - let probe = format!( - "module vfmt_probe;\n always_comb begin\n {typed}{text}\n end\nendmodule\n" - ); + // What Tab really writes — the snippet as the *editor* lays it out, + // with every hole filled in — planted where the trigger fires and + // handed to the parser. A body that did not parse would be a formatter + // that refuses the file the moment the user accepts a suggestion. + for (trigger, body) in every() { + let text = filled(&accepted(&render(body), " ", " ")); + let probe = planted(trigger, &format!("{}{text}", typed(trigger))); let (_, diagnostics) = vlog_parser::parse_source_tolerant(&probe); assert!( diagnostics.is_empty(), @@ -667,6 +1045,330 @@ endmodule } } + #[test] + fn every_accepted_ghost_is_scope_balanced() { + // What the user typed plus what Tab writes closes exactly what it + // opens: no dangling `begin`, no orphan `endcase`. The same matcher + // the gates ask, run over the result rather than over the buffer. + for (trigger, body) in every() { + let text = format!("{}{}", typed(trigger), filled(&render(body))); + let tokens = vlog_parser::tokenize(&text).expect("a body lexes"); + let analysis = pairs::analyze(&tokens); + assert!( + analysis.unmatched_open.is_empty() && analysis.unmatched_close.is_empty(), + "`{}` does not balance:\n{text}", + trigger.keyword + ); + } + } + + #[test] + fn every_gate_is_the_one_the_body_needs() { + // The rule behind the three `Unclosed` variants, derived from the + // bodies rather than restated: a body that writes a closer for a scope + // it did not open — `end` after a bare `begin`, `endcase` after + // `case (` — is finishing the *user's* keyword, so the gate must ask + // whether that keyword is still open. A body whose own `begin` its + // `end` closes needs no such question. And a trigger whose opener ends + // in `(` writes the `)`, so it must ask about the paren. + for trigger in TRIGGERS { + let closes_the_users_keyword = trigger.bodies.iter().any(|body| { + let tokens = vlog_parser::tokenize(&filled(&render(body))).expect("a body lexes"); + !pairs::analyze(&tokens).unmatched_close.is_empty() + }); + let writes_a_closing_paren = trigger.opener.last() == Some(&"("); + let (scope, paren) = match trigger.gate { + Unclosed::Paren => (false, true), + Unclosed::Scope => (true, false), + Unclosed::ParenAndScope => (true, true), + }; + assert_eq!( + closes_the_users_keyword, scope, + "`{}`: the scope half of the gate does not match the body", + trigger.keyword + ); + assert_eq!( + writes_a_closing_paren, paren, + "`{}`: the paren half of the gate does not match the opener", + trigger.keyword + ); + } + } + + #[test] + fn every_trigger_offers_at_least_one_body() { + for trigger in TRIGGERS { + assert!(!trigger.bodies.is_empty(), "`{}` offers nothing", trigger.keyword); + } + } + + // ------------------------------------------------------------------ + // round 2 QA: `accepted()` cross-checked against VS Code's own algorithm + // ------------------------------------------------------------------ + // + // `accepted()` above is a shortcut: it prepends `base` verbatim and only + // re-spells the `\t`s the body added. The real + // `SnippetSession.adjustWhitespace` re-derives the *whole* leading run — + // base included — from column counts (`TextModel.normalizeIndentation`), + // and normalizes the snippet's first line too. The shortcut is exact only + // when the trigger line's own indentation is already spelled the way the + // editor is configured — the ordinary case, and the only one these two + // tests assume — but "ordinary" was itself an assumption worth checking + // rather than trusting, so it is checked here against a second, + // independent model built straight off the quoted source rather than off + // `accepted`'s shortcut. + + /// `TextModel.normalizeIndentationFromWhitespace`. `ws` is assumed to be + /// entirely leading whitespace: every `\t` counts as `indent_size` + /// columns, every other character as one, and the whole run is re-spelled + /// as tabs-then-spaces (`insert_spaces: false`) or all spaces (`true`). + fn normalize_indentation_from_whitespace( + ws: &str, + indent_size: usize, + insert_spaces: bool, + ) -> String { + let columns: usize = ws.chars().map(|c| if c == '\t' { indent_size } else { 1 }).sum(); + let mut out = String::new(); + let mut spaces = columns; + if !insert_spaces { + out.extend(std::iter::repeat_n('\t', columns / indent_size)); + spaces = columns % indent_size; + } + out.extend(std::iter::repeat_n(' ', spaces)); + out + } + + /// `TextModel.normalizeIndentation`: only the leading run of spaces and + /// tabs is touched; everything from the first other character on is left + /// alone. + fn normalize_indentation(line: &str, indent_size: usize, insert_spaces: bool) -> String { + let split = line.find(|c: char| c != ' ' && c != '\t').unwrap_or(line.len()); + let (ws, rest) = line.split_at(split); + format!("{}{rest}", normalize_indentation_from_whitespace(ws, indent_size, insert_spaces)) + } + + /// `snippet` as `SnippetSession.adjustWhitespace` really writes it, + /// modelled directly off the quoted source: the first line is normalized + /// *alone* — `lines[0] = model.normalizeIndentation(lines[0])`, no + /// prepend, because `snippet.offset(marker) === 0` — and every later line + /// gets the trigger line's own leading whitespace prepended before + /// normalizing: `model.normalizeIndentation(lineLeadingWhitespace + + /// lines[i])`. + fn accepted_faithful( + snippet: &str, + trigger_line_indent: &str, + indent_size: usize, + insert_spaces: bool, + ) -> String { + snippet + .split('\n') + .enumerate() + .map(|(i, line)| match i { + 0 => normalize_indentation(line, indent_size, insert_spaces), + _ => normalize_indentation( + &format!("{trigger_line_indent}{line}"), + indent_size, + insert_spaces, + ), + }) + .collect::>() + .join("\n") + } + + #[test] + fn the_accepted_helper_matches_vscodes_own_algorithm_for_a_self_consistent_buffer() { + // A buffer whose own indentation already matches the editor's current + // `tabSize`/`insertSpaces` — spaces at 2, spaces at 4, tabs — at + // several depths, for every trigger's every body. + for (indent_size, insert_spaces, unit) in + [(2usize, true, " ".repeat(2)), (4, true, " ".repeat(4)), (4, false, "\t".to_string())] + { + let step = if insert_spaces { unit.clone() } else { "\t".to_string() }; + for depth in [0usize, 1, 2, 5] { + let base = unit.repeat(depth); + for (trigger, body) in every() { + let snippet = render(body); + let shortcut = accepted(&snippet, &base, &step); + let faithful = accepted_faithful(&snippet, &base, indent_size, insert_spaces); + assert_eq!( + shortcut, faithful, + "`{}` at depth {depth}, indent_size {indent_size}, insert_spaces {insert_spaces}: \ + the shortcut `accepted()` every other test uses disagrees with VS Code's own \ + normalizeIndentation", + trigger.keyword + ); + } + } + } + } + + #[test] + fn every_bodys_first_line_is_stable_under_normalization() { + // `accepted()`'s line-0 shortcut (`out.push(line.to_string())`, no + // normalization at all) is only correct because every body's first + // line today has either no leading whitespace or exactly one leading + // space, and a single space normalizes to itself at every indent_size + // VS Code allows. A future body whose first line picked up two or + // more leading spaces (or a leading tab) would make the shortcut + // silently wrong, and nothing else in this file would notice, because + // `every_accepted_ghost_parses` and its siblings only ever call + // `accepted`, never `accepted_faithful`. + for (trigger, body) in every() { + let (_, first_line) = body[0]; + for (indent_size, insert_spaces) in [(2usize, true), (4, true), (4, false), (8, false)] + { + assert_eq!( + normalize_indentation(first_line, indent_size, insert_spaces), + first_line, + "`{}`'s first line {first_line:?} is not stable at indent_size {indent_size}, \ + insert_spaces {insert_spaces} — `accepted()`'s line-0 shortcut would now be wrong", + trigger.keyword + ); + } + } + } + + #[test] + fn every_bodys_closer_lands_level_with_the_trigger_and_its_interior_one_step_in() { + // The user's exact report: "the end lands deeper than its opener." + // Checked against the table's own `(level, text)` metadata rather + // than by re-deriving it, at several depths, in both indent styles, + // and for every trigger — not just the one construct the round-1 + // suite happened to cover. + let configs: &[(&str, &str)] = &[(" ", " "), (" ", " "), ("\t", "\t")]; + for (unit, step) in configs { + for depth in [0usize, 1, 2, 5] { + let base = unit.repeat(depth); + for (trigger, body) in every() { + let got = accepted(&render(body), &base, step); + let got_lines: Vec<&str> = got.split('\n').collect(); + assert_eq!(got_lines.len(), body.len(), "`{}`: line count", trigger.keyword); + for (i, (level, text)) in body.iter().enumerate() { + let expected = if i == 0 { + text.to_string() + } else { + format!("{base}{}{text}", step.repeat(*level as usize)) + }; + assert_eq!( + got_lines[i], expected, + "`{}`: line {i} at depth {depth}, base {unit:?}", + trigger.keyword + ); + } + // The closer is always the body's last line, and it must + // sit at level 0 — exactly the trigger line's own + // indentation, never a step deeper. + let (closer_level, _) = *body.last().expect("a body has a closer"); + assert_eq!(closer_level, 0, "`{}`: closer is not level 0", trigger.keyword); + } + } + } + } + + // ------------------------------------------------------------------ + // round 2 QA: attacking the new triggers + // ------------------------------------------------------------------ + + #[test] + fn casez_triggers_in_a_verilog_file_too() { + // `case`/`casez`/`casex` are `dialect: None` — a Verilog buffer gets + // the same ghost a SystemVerilog one does. + let text = "module top;\n always @(*) begin\n casez (\n end\nendmodule\n"; + assert!(!offered_in("/rtl/top.v", text, "casez (").is_empty()); + } + + #[test] + fn a_for_loop_in_a_pathless_buffer_gets_the_verilog_body() { + // `templates::dialect` resolves a pathless buffer to Verilog — the + // same default the completion tier documents — so an `untitled:` + // buffer (no path at all, unlike a `.v` or a `.sv` one) gets the loop + // with no local variable declaration and no `++`. + // + // `offered_in` goes through `path_to_uri`, which always mints a + // `file://` URI, so it cannot produce a genuinely pathless document — + // this builds the `untitled:` URI directly, the way `state.rs`'s own + // `an_untitled_buffer_has_no_path` does. + let uri = Uri::from_str("untitled:Untitled-1").expect("uri"); + let text = "module top;\n initial begin\n for (\n end\nendmodule\n"; + let mut ws = Workspace::default(); + ws.set_document(uri.clone(), text.to_string()); + let offset = (text.find("for (").expect("needle present") + "for (".len()) as u32; + let position = ws.document(&uri).expect("open").positions().position(offset); + let items = inline_completions(&ws, &uri, position).expect("a ghost"); + assert_eq!( + items.items.iter().map(|i| i.insert_text.value.clone()).collect::>(), + vec!["${1:i} = 0; $1 < ${2:N}; $1 = $1 + 1) begin\n\t$0\nend"] + ); + } + + #[test] + fn always_at_space_paren_still_offers_both_items() { + // The lexer does not tokenize whitespace, so `@` and `(` end up + // adjacent in `doc.tokens` whether or not the user left a space + // between them; the opener sequence match is on tokens, not text — + // the tight `always@(` is already pinned by + // `no_space_between_the_keyword_and_the_paren_still_triggers`, this + // pins the opposite spacing. + let text = "module top;\n always @ (\nendmodule\n"; + assert_eq!(all_offered(text, "always @ (").len(), 2); + } + + #[test] + fn module_mid_file_above_an_existing_closed_module_still_offers() { + // `pairs::analyze` reports the *new* `module`'s own span in + // `unmatched_open` — an earlier, already-closed module does not + // cancel it out, the same rule + // `a_case_that_already_has_its_endcase_offers_nothing` proves for + // `case`. + let text = "module first;\nendmodule\n\nmodule"; + assert!(offered(text, "\nmodule").is_some()); + } + + #[test] + fn generate_offers_even_when_an_earlier_generate_is_balanced() { + let text = "module top;\n generate\n endgenerate\n generate\nendmodule\n"; + assert!( + offered(text, "endgenerate\n generate").is_some(), + "the second generate is genuinely open" + ); + } + + #[test] + fn fork_offers_in_both_dialects() { + let text = "module top;\n initial begin\n fork\n end\nendmodule\n"; + assert!(!offered_in("/rtl/top.sv", text, " fork").is_empty()); + assert!(!offered_in("/rtl/top.v", text, " fork").is_empty()); + } + + #[test] + fn a_casex_whose_paren_is_closed_two_lines_down_offers_nothing() { + // Same rule `a_paren_the_line_below_closes_still_counts_as_closed` + // pins for `if (`, attacked on the trigger whose gate also asks about + // a scope: the paren half alone is enough to decline. + let text = "\ +module top; + always_comb begin + casex ( + sel) + 1: ; + endcase + end +endmodule +"; + assert_eq!(offered(text, "casex ("), None, "the `)` two lines down still closes the paren"); + } + + #[test] + fn nested_unclosed_parens_each_see_their_own_gate() { + // `if (` on one line and `always @(` on the next: two different + // unclosed parens. `paren_is_closed` is a stack keyed by the exact + // span passed in, so neither paren can be mistaken for the other's + // counterpart — both must still offer. + let text = "module top;\n if (\n always @(\nendmodule\n"; + assert!(offered(text, " if (").is_some()); + assert_eq!(all_offered(text, " always @(").len(), 2); + } + // ------------------------------------------------------------------ // the wire // ------------------------------------------------------------------ @@ -686,7 +1388,7 @@ endmodule serde_json::to_value(&items).expect("serializes"), serde_json::json!({ "items": [{ - "insertText": { "kind": "snippet", "value": "\n $0\n end" }, + "insertText": { "kind": "snippet", "value": "\n\t$0\nend" }, "range": { "start": { "line": 1, "character": 19 }, "end": { "line": 1, "character": 19 } @@ -696,6 +1398,37 @@ endmodule ); } + #[test] + fn a_multi_item_response_repeats_the_range_and_nothing_else() { + let text = "module top;\n always @(\nendmodule\n"; + let (ws, uri, position) = asking(text, "always @("); + let items = inline_completions(&ws, &uri, position).expect("two ghosts"); + assert_eq!( + serde_json::to_value(&items).expect("serializes"), + serde_json::json!({ + "items": [ + { + "insertText": { + "kind": "snippet", + "value": "posedge ${1:clk}) begin\n\t$0\nend" + }, + "range": { + "start": { "line": 1, "character": 11 }, + "end": { "line": 1, "character": 11 } + } + }, + { + "insertText": { "kind": "snippet", "value": "*) begin\n\t$0\nend" }, + "range": { + "start": { "line": 1, "character": 11 }, + "end": { "line": 1, "character": 11 } + } + } + ] + }) + ); + } + #[test] fn the_range_is_empty_and_at_the_cursor() { // The protocol requires a range to begin and end on one line, and this diff --git a/crates/vfmt_server/tests/e2e.rs b/crates/vfmt_server/tests/e2e.rs index 8834eeb..ae68042 100644 --- a/crates/vfmt_server/tests/e2e.rs +++ b/crates/vfmt_server/tests/e2e.rs @@ -1253,6 +1253,9 @@ fn completion_and_signature_help_round_trip_over_the_wire() { ); assert_eq!(item["textEdit"]["range"]["start"]["character"], 2, "the typed word is replaced"); assert_eq!(item["textEdit"]["range"]["end"]["character"], 8); + // The skeleton already carries the site's indentation on every line but + // the first, so the client is told to leave it alone (`InsertTextMode.asIs`). + assert_eq!(item["insertTextMode"], 1, "InsertTextMode.asIs: {item:#?}"); // `hint_s` also prefixes no keyword, but `clk` is in scope and the file's // own words are there, so the general tiers really did run. assert!( @@ -1344,8 +1347,9 @@ fn a_client_without_snippet_support_gets_the_skeleton_as_plain_text() { fn inline_templates_round_trip_over_the_wire() { let dir = temp_dir("inline"); // Line 1 ends in a `begin` with no `end`; line 2 is an `if (` with nothing - // after it, inside the block that begin opened. - let top = "module top;\n always_comb begin\n if (\nendmodule\n"; + // after it, inside the block that begin opened. Line 6 is an `always @(`, + // the one trigger that answers with more than one item. + let top = "module top;\n always_comb begin\n if (\nendmodule\n\nmodule two;\n always @(\nendmodule\n"; let path = dir.join("top.sv"); std::fs::write(&path, top).expect("write"); let root = format!("file://{}", dir.display()); @@ -1368,6 +1372,8 @@ fn inline_templates_round_trip_over_the_wire() { // Just after the `begin` on line 1, and just after the `(` on line 2. ask(2, 1, 19), ask(3, 2, 8), + // ...just after the `@(` on line 6, which answers with two items... + ask(5, 6, 11), // ...and in the middle of the `always_comb` keyword, where there is // nothing to offer at all. ask(4, 1, 8), @@ -1386,13 +1392,18 @@ fn inline_templates_round_trip_over_the_wire() { response["result"].clone() }; - // The `begin` trigger: a newline, an indented tabstop, and the `end` - // aligned with the line the `begin` sits on. + // The `begin` trigger: a newline, a tabstop one step in, and the `end` + // back at the trigger line's own level. The indentation is **relative** — + // one `\t` per step and no trace of the site — because the editor prepends + // the insertion line's own leading whitespace to every line after the + // first and re-spells the result in its own tabs-or-spaces. Sending the + // absolute layout, as 0.6.0 did, indented the whole body twice and left + // the `end` deeper than its `begin`. assert_eq!( items(2), serde_json::json!({ "items": [{ - "insertText": { "kind": "snippet", "value": "\n $0\n end" }, + "insertText": { "kind": "snippet", "value": "\n\t$0\nend" }, "range": { "start": { "line": 1, "character": 19 }, "end": { "line": 1, "character": 19 } @@ -1405,9 +1416,18 @@ fn inline_templates_round_trip_over_the_wire() { // The `if (` trigger, from inside the same block. let item = &items(3)["items"][0]; assert_eq!(item["insertText"]["kind"], "snippet"); - assert_eq!(item["insertText"]["value"], "${1:cond}) begin\n $0\n end"); + assert_eq!(item["insertText"]["value"], "${1:cond}) begin\n\t$0\nend"); assert_eq!(item["range"]["start"], item["range"]["end"], "an insertion, not a replacement"); + // `always @(` is the one trigger with a list: the clocked block first, the + // combinational one second, both at the same empty range. + let two = items(5); + let two = two["items"].as_array().expect("a list"); + assert_eq!(two.len(), 2, "{two:#?}"); + assert_eq!(two[0]["insertText"]["value"], "posedge ${1:clk}) begin\n\t$0\nend"); + assert_eq!(two[1]["insertText"]["value"], "*) begin\n\t$0\nend"); + assert_eq!(two[0]["range"], two[1]["range"], "both insert at the cursor"); + assert_eq!(items(4), serde_json::Value::Null, "nowhere near a trigger"); let _ = std::fs::remove_dir_all(&dir); @@ -1597,6 +1617,12 @@ fn a_template_completion_round_trips_over_the_wire() { template["textEdit"]["newText"], "if (${1:cond}) begin\n $0\n end", "{template:#?}" ); + // The body is laid out at the site's own indentation, so the client must + // be told not to indent it a second time: VS Code's suggest controller + // passes `adjustWhitespace: true` unless the item carries `asIs`, and its + // snippet session then prepends the insertion line's leading whitespace to + // every line after the first. `1` is `InsertTextMode.asIs`. + assert_eq!(template["insertTextMode"], 1, "InsertTextMode.asIs: {template:#?}"); // The replaced range is exactly the two letters typed. assert_eq!(template["textEdit"]["range"]["start"]["line"], 2); assert_eq!(template["textEdit"]["range"]["start"]["character"], 4); diff --git a/docs/features/completion-templates/README.md b/docs/features/completion-templates/README.md index 941422d..21d11b5 100644 --- a/docs/features/completion-templates/README.md +++ b/docs/features/completion-templates/README.md @@ -58,7 +58,9 @@ templates used to live. Those are gone; see *Reconciliation* below. added without an escape. - **`vfmt.indent` (default 2) is the indent step**, and the line's own leading whitespace is the base — the same `Layout` M4's skeletons use, resolved the - same way and with the same deviation from `vfmt.toml` recorded there. + same way and with the same deviation from `vfmt.toml` recorded there. Because + the base is baked in, the item must tell the client not to indent it again: + see *The indentation contract* below. - **A template is offered on prefix, not on fuzzy match.** The server filters with `starts_with_ignore_case` on the template's prefix exactly as the other tiers filter on a name, so `alw` finds every `always*` template and `wh` @@ -258,6 +260,49 @@ snippets)` — so they cannot drift, and `the_two_spellings_of_a_body_are_the_same_text` asserts that stripping the tabstops out of the snippet gives the plain text back. +## The indentation contract + +**Added 2026-08-25, fixing a bug that had been in the popup since 0.4.0 and +was found while fixing its twin in `inline-templates`.** + +Every multi-line body here already carries the site's indentation: `Layout`'s +`base` is the trigger line's leading whitespace and every line after the first +starts with it. VS Code then indents it *again*. `suggestController.ts`'s +`_insertSuggestion` calls + +```ts +snippetController.insert(insertText, { + …, + adjustWhitespace: !(item.completion.insertTextRules! & CompletionItemInsertTextRule.KeepWhitespace), + … +}); +``` + +and `SnippetSession.adjustWhitespace` prepends the insertion line's own +leading whitespace to every line after the first, then re-spells the run with +`TextModel.normalizeIndentation`. So `if` accepted four spaces in wrote its +body at twelve and its `end` at eight — one level right of the `if`. + +The escape hatch is LSP's `insertTextMode`. `asIs` says "the string is taken +as it is… the client will not apply any kind of adjustments". The vendored +`vscode-languageclient` 9.0.1 advertises support for it +(`completion.js:59`), turns it into `keepWhitespace: true` +(`protocolConverter.js:342-346`), and `extHostLanguageFeatures.ts` turns +*that* into the `KeepWhitespace` rule that clears `adjustWhitespace`. + +So `completion.rs` sends `insertTextMode: asIs` (the `KEEP_MY_INDENTATION` +constant) on the two item builders that write more than one line: the template +tier and the module-instantiation skeleton. Single-line items neither need it +nor are harmed by it, so they do not send it. It is the right answer for the +plain-text spelling as well — that text is absolutely positioned too — which +is why this path did **not** switch to relative indentation the way ghost text +had to. An inline completion has no `insertTextMode` field at all; see +`docs/features/inline-templates/README.md`'s *The indentation contract*. + +Pinned by `tests/e2e.rs` (`insertTextMode == 1` on both the template item and +the module skeleton), over the wire, beside the `newText` each already +asserted. + ## Reconciliation with the static VS Code snippets Nine snippets were deleted from `editors/vscode/snippets/*.json` because the @@ -391,6 +436,24 @@ in the feature READMEs that record what happened at those versions. `smoke: OK`; `npx --no-install @vscode/vsce ls` still lists both snippet files. No new dependency. +- **2026-08-25 (dev, inline-templates round 2)** — one field, one latent bug. + + While fixing the same double-indentation bug in ghost text I read + `suggestController.ts` and found the popup had it too: every multi-line item + this tier sends was being re-indented by the editor on accept, since 0.4.0. + Fixed with `insertTextMode: asIs` on `Items::template` and on `item` (the + module-instantiation skeleton), behind the `KEEP_MY_INDENTATION` constant so + the reasoning sits with the value. Full derivation and sources in *The + indentation contract* above; the inline half is in + `docs/features/inline-templates/README.md`. + + **Flagged for the lead:** the module-skeleton item belongs to + `refactor-instantiate`, not to this feature — the code is in + `completion.rs`, it is the identical bug, and leaving it broken beside the + fixed template item would have been the odd choice. `templates.rs` itself is + untouched: no body, no label, no gate, no renderer changed. Two `e2e.rs` + assertions added; nothing else. + ## QA log **2026-08-24 — QA agent.** @@ -599,6 +662,58 @@ The one finding (CHANGELOG miscount) was cosmetic, unambiguous, and fixed in place. No gate, attack, or reconciliation check turned up anything that needs dev rework. +**2026-08-25 — QA agent, round 2 (the `insertTextMode` popup fix).** + +This feature's only change in round 2 is the four-line diff in +*The indentation contract* above (`completion.rs`): `insert_text_mode: +Some(KEEP_MY_INDENTATION)` on `Items::template` +(`crates/vfmt_server/src/completion.rs:459`) and on `item`, the +module-instantiation skeleton (`:612`); `layout_at` +(`crates/vfmt_server/src/completion.rs:326-329`) re-privatized because +`inline.rs` no longer names it. `templates.rs` is untouched, confirmed by +`git diff --stat` (absent from the diff entirely). Full attack and gate +detail — the trigger-table work is this round's real surface — is in +`docs/features/inline-templates/README.md`'s 2026-08-25 round-2 QA entry; +this entry covers only what round 2 touched here. + +- **The wire value.** `crates/vfmt_server/src/completion.rs:156` in + `lsp-types` 0.97.0 (registry source, read directly): + `pub const AS_IS: InsertTextMode = InsertTextMode(1)`; + `ADJUST_INDENTATION = InsertTextMode(2)`. So `KEEP_MY_INDENTATION` is `1`, + matching LSP 3.17's `InsertTextMode` enum (`asIs = 1`). Both pins in + `tests/e2e.rs` assert `insertTextMode == 1` — the template item at + `crates/vfmt_server/tests/e2e.rs:1258` and the module skeleton at + `:1625` — and both are correct. (The QA brief itself floated "`asIs` (2)" + as a parenthetical; that would have been `AdjustIndentation`, not `AsIs` + — checked against the source rather than trusted, and the shipped code is + right.) +- **No leak onto single-line items.** `grep -n "insert_text_mode" + crates/vfmt_server/src/completion.rs` returns exactly the two call sites + above. `Items::simple` (`completion.rs:412-430`, the keyword/word/index + tiers' single-line items) builds its `CompletionItem` with + `..Default::default()`, which leaves `insert_text_mode: None` — confirmed + by reading the struct literal, not inferred. So plain keyword and word + items are unaffected, as required. +- **Client capability path.** `editors/vscode/node_modules/ + vscode-languageclient/lib/common/completion.js:59` advertises + `insertTextModeSupport.valueSet: [asIs, adjustIndentation]` as part of the + standard completion capabilities — no code in this repo has to opt into + it, unlike `inlineCompletion`'s proposed-feature registration. + `protocolConverter.js:342-346` turns `insertTextMode === asIs` into + `result.keepWhitespace = true`, which `extHostLanguageFeatures.ts` turns + into the `KeepWhitespace` insert-text rule `suggestController.ts` checks + before calling `adjustWhitespace`. Traced end to end; matches the Work + log's claim. +- **Gates, re-run independently:** `cargo fmt --all -- --check` clean; + `cargo clippy --all-targets --workspace` zero warnings; `cargo test + --workspace` 1644 passed / 0 failed / 4 ignored (up from the round-2 dev's + 1633 — 11 new tests, all in `inline.rs`, none in this feature's own + files); `node editors/vscode/smoke.js target/debug/vfmt-server` → + `smoke: OK`; `node --check` on `smoke.js` and a `JSON.parse` of + `package.json` both clean. + +No findings against this feature's own round-2 diff. No commit, no push. + ## Review **2026-08-24 — lead.** Reviewed after QA's ship verdict — second clean @@ -616,3 +731,12 @@ accepted. Lead post-review fix: the extension README's relative link to this doc broke `vsce package` (no repository URL to resolve it against) — demoted to plain-text path. M6 checked off in the umbrella plan and TODO.md §8; ships as 0.4.0. + +**2026-08-25 — lead review of the insertTextMode fix.** The popup's +skeletons were latently double-indented in VS Code since 0.4.0 — same +root cause as inline-templates round 2, different fix because the +completion protocol has the opt-out the inline one lacks: +`insertTextMode: asIs` (verified = 1 on the wire against lsp-types +source, by QA) on the two multi-line tiers only. `templates.rs` and the +plain-text fallback untouched, `vfmt.indent` still meaningful here. +Approved; ships as 0.7.0. diff --git a/docs/features/inline-templates/README.md b/docs/features/inline-templates/README.md index 43545f9..7181364 100644 --- a/docs/features/inline-templates/README.md +++ b/docs/features/inline-templates/README.md @@ -12,6 +12,11 @@ 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 @@ -32,20 +37,133 @@ already committed to the construct, so accepting one costs a single key. 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. +- **The snippet is indented relative to the trigger line, and the editor + supplies the rest.** One `\t` per indent step, no `base` — see *The + indentation contract* below for the VS Code source this is read off, and + for what it costs. Consequence worth naming twice: **`vfmt.indent` does + not decide the width of an accepted ghost snippet.** The editor's own + `editor.tabSize`/`editor.insertSpaces` do, because the editor rewrites + the leading whitespace of every inserted line whatever the server sent. + `vfmt.inlineTemplates`'s setting description says so. - **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 + in a completion list, and most 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. + 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 + unmatched `module` keyword 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, and `always_ff @(` is refused outright in a + `.v` buffer, whose compiler would reject the keyword. +- **`casex (` is offered here although `templates.rs` refuses to list it.** + The popup's reason for leaving `casex` out 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 typed `casex (` 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 with `Alt+]`/`Alt+[`; order is + offer priority, clocked first, because `always @(` 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. - **`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). + +## 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: + +```ts +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 @@ -61,17 +179,22 @@ already committed to the construct, so accepting one costs a single key. `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::completion::layout_at`~~ — **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, so `layout_at` is + private to `completion.rs` again. Nothing else consumed it, and the + compiler confirmed it. +- ~~`vlog_refactor::Layout`~~ — same, for the same reason. This module no + longer names the type. +- `crate::templates::{dialect, Dialect}` — **new**, the file-extension rule + the completion tier already uses, read for the `for (` split and the + `always_ff @(` refusal. Nothing in `templates.rs` changed for this. - `crate::settings::ClientSettings::inline_templates` — **new field**, `Option` 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. + toggling it rebuilds no index. `ClientSettings::indent` is **no longer + read here** (see *The indentation contract*). **Promised** @@ -84,6 +207,17 @@ already committed to the construct, so accepting one costs a single key. `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. +- **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, unlike `completionItem.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 send `insertTextMode: asIs`. See the QA/Review note in + the work log — the change is one field on two item builders and is + documented in `completion-templates`' README. - Root `Cargo.toml`: `lsp-types` gains `features = ["proposed"]`. That feature also adds `offset_encoding` fields to `ClientCapabilities`, `InitializeResult` and `TextDocumentClientCapabilities` — all @@ -109,6 +243,32 @@ already committed to the construct, so accepting one costs a single key. - [x] End-to-end test in `crates/vfmt_server/tests/e2e.rs` - [x] `cargo fmt` / `cargo clippy --all-targets` / `cargo test` green +### Round 2 — 2026-08-25 + +- [x] **Bug: `begin`/`end` misaligned after accepting.** Bodies are emitted + relative (`\t` per step, no `base`); the VS Code source this is read + off is quoted in *The indentation contract*. +- [x] The same trap in the completion popup, fixed the other way it allows: + `insertTextMode: asIs` on the template and module-skeleton items. +- [x] `layout_at` un-exported; `Layout` no longer named by `inline.rs`. +- [x] 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. +- [x] New triggers: `while (`, `for (` (both dialects), `case (`/`casez (`/ + `casex (`, `always @(` (two items), `always_ff @(` (SV), `fork`, + `generate`, `module`. +- [x] 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. +- [x] Wire pins updated: `inline.rs` unit tests, `tests/e2e.rs` (including a + new multi-item round trip and the popup's `insertTextMode`), + `editors/vscode/smoke.js`. +- [x] `vfmt.inlineTemplates`'s setting description names the new triggers and + says the editor's indent settings, not `vfmt.indent`, size the result. +- [ ] Not done, deliberately: no `function`/`task` triggers — see *The + triggers*. + ## Work log **2026-08-25 — dev** @@ -170,6 +330,137 @@ already committed to the construct, so accepting one costs a single key. zero warnings, `cargo test` 1607 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 only `model.normalizeIndentation(lines[0])` + (no prepend, because `snippet.offset(marker) === 0`), a text marker that + starts right after a line break gets the prepend too, and + `for (let i = 1; i < lines.length; i++) lines[i] = model.normalizeIndentation(lineLeadingWhitespace + lines[i])`. + In the same file, `_defaultOptions` is + `{ overwriteBefore: 0, overwriteAfter: 0, adjustWhitespace: true, clipboardText: undefined, overtypingCapturer: undefined }` + — **`adjustWhitespace` defaults to `true`.** +- `src/vs/editor/contrib/inlineCompletions/browser/model/inlineCompletionsModel.ts` + — the accept path is + `SnippetController2.get(editor)?.insert(action.snippetInfo.snippet, { undoStopBefore: false })`. + **No `adjustWhitespace` is passed**, so the default `true` applies and there + is no LSP-side field that could switch it off: `InlineCompletionItem` has no + `insertTextMode`, and `vscode-languageclient`'s `asInlineCompletionItem` + reads only `insertText` (and `filterText`/`command` if truthy). + `src/vs/editor/contrib/inlineCompletions/browser/controller/commands.ts` is + only the action layer (`controller.model.get()?.accept(controller.editor)`). +- `src/vs/editor/contrib/suggest/browser/suggestController.ts` — the popup + path is + `snippetController.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) sets + `result.keepWhitespace = true` when `insertTextMode === InsertTextMode.asIs`, + `extHostLanguageFeatures.ts`'s `_convertCompletionItem` turns that into + `CompletionItemInsertTextRule.KeepWhitespace`, and `completion.js:59` shows + the client advertising `insertTextModeSupport.valueSet: [asIs, adjustIndentation]`, + so the field is negotiated and honoured. +- `.../model/provideInlineCompletions.ts` — the **preview** text is + `snippet.toString()` (tabstops removed, defaults kept) with no adjustment, + and `.../view/ghostText/ghostTextView.ts` renders those lines verbatim, + expanding `\t` at the editor's `tabSize`. + +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: `render` now emits + one `\t` per indent step and no `base` at all, and no longer takes a + `Layout`. `normalizeIndentation` re-spells the leading run in the user's own + `tabSize`/`insertSpaces`, so `\t` is 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 no + `snippetSupport` to negotiate), so nothing was kept. +- **Popup** keeps its absolute layout and sends `insertTextMode: asIs` + instead. **Deviation from the brief's expected shape, deliberately.** The + brief expected relative bodies there too, but `asIs` is strictly better on + that path: it fixes the snippet *and* the plain-text spelling with one + field, it leaves `Template::render`'s single renderer for both spellings + intact (`the_two_spellings_of_a_body_are_the_same_text` still holds), it + keeps `vfmt.indent` meaningful 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`'s `item`), which is laid out by the same `Layout` + and had the identical latent bug; flagged for the lead because that skeleton + belongs to `refactor-instantiate`, though the code is in `completion.rs`. +- `completion::layout_at` is private again: this module was its only other + caller. + +**Consequence, documented in three places** (Assumptions here, the +`vfmt.inlineTemplates` setting description, the module doc comment): +`vfmt.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` 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/vfmt-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** @@ -403,6 +694,185 @@ test result: ok. 20 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out; fin `node editors/vscode/smoke.js ` and `` 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 in `inline.rs`; full tail + below). +- `cargo build -p vfmt_server && node editors/vscode/smoke.js + target/debug/vfmt-server`: `smoke: OK`. Ran with the debug binary's + explicit path, not a bare `vfmt-server`, for the reason round 1's QA log + already flagged (a stale `$PATH` binary predating this feature answers + `capability missing`). +- `node --check editors/vscode/smoke.js` and a `JSON.parse` of + `editors/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/vfmt_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-checks `accepted()` against `accepted_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 (prepend `base` verbatim, re-spell only + the `\t`s the body added) is provably equal to the real column-counting + algorithm exactly when `base` is 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 current + `tabSize`/`insertSpaces` (a tab-indented file opened under + `insertSpaces: true`, say) would make VS Code re-spell the trigger line's + own leading run too, not just the inserted `\t`s — but that is a fact about + `normalizeIndentation` applied 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`'s `accepted`, `out.push(line.to_string())` for `index == 0` + — no normalization at all) is a shortcut of its own: the real + `adjustWhitespace` normalizes 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 (the `module` trigger's `" ${1:name};"`), and a + single space is a fixed point of `normalizeIndentation` at every + `indent_size` VS Code allows (1 space rounds to 0 tabs + 1 space remainder + regardless of `tabSize`). 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's `accepted()` 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/vfmt_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/vfmt_server/src/{inline.rs,completion.rs}`, +`crates/vfmt_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/vfmt_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/vfmt_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`) + and `accepted_faithful` the 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/vfmt-server` → +`smoke: OK`. + ## Review **2026-08-25 — lead.** Approved and committed. @@ -420,3 +890,23 @@ OK. - Gates re-run by the lead: fmt clean, clippy clean, full workspace suite green, `smoke.js` exercised 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.adjustWhitespace` and the inline-accept path (no + `adjustWhitespace` opt-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 `\t` bodies where the protocol has + no opt-out (inline), `insertTextMode: asIs` where it does (popup), each + documented as the sibling of the other. `vfmt.indent` no 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`/`task` correctly 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. diff --git a/editors/vscode/package.json b/editors/vscode/package.json index e996bdb..616f12d 100644 --- a/editors/vscode/package.json +++ b/editors/vscode/package.json @@ -166,7 +166,7 @@ "vfmt.inlineTemplates": { "type": "boolean", "default": true, - "markdownDescription": "Show grey ghost text that finishes a block as you open it: `if (` suggests `) begin … end`, and a `begin` at the end of a line suggests its `end`. Tab accepts it as a snippet, so the cursor lands in the condition first and in the body second. Requires `editor.inlineSuggest.enabled`." + "markdownDescription": "Show grey ghost text that finishes a block as you open it: `if (` suggests `) begin … end`, a `case (` suggests its arms and `endcase`, and a `begin`, `fork`, `generate` or `module` at the end of a line suggests its closer. Tab accepts it as a snippet, so the cursor lands in the condition first and in the body second; where more than one shape fits (`always @(`), `Alt+]` cycles them. The accepted text is indented with the editor's own `editor.tabSize`/`editor.insertSpaces`, not with `#vfmt.indent#`. Requires `editor.inlineSuggest.enabled`." }, "vfmt.lineLength": { "type": [ diff --git a/editors/vscode/smoke.js b/editors/vscode/smoke.js index a5b42ea..2b9d71d 100644 --- a/editors/vscode/smoke.js +++ b/editors/vscode/smoke.js @@ -206,7 +206,12 @@ server.on('close', (code) => { if (!suggestion.insertText || suggestion.insertText.kind !== 'snippet') { fail(`insertText must be a {kind:"snippet"} object, got ${JSON.stringify(suggestion.insertText)}`); } - if (suggestion.insertText.value !== '\n $0\n end') { + // The body is indented *relative* to the trigger line — one tab per step, + // no trace of where in the file it goes — because VS Code's snippet session + // prepends the insertion line's own leading whitespace to every line after + // the first and re-spells the result in the editor's tabs-or-spaces. Sending + // the absolute layout, as 0.6.0 did, indented it twice. + if (suggestion.insertText.value !== '\n\t$0\nend') { fail(`unexpected ghost text: ${JSON.stringify(suggestion.insertText.value)}`); }