Expose vfmt.toml settings in VS Code: vfmt.lineLength, vfmt.indent, vfmt.exclude

All three vfmt.toml keys, pushed over workspace/didChangeConfiguration
(initial push verified against the real vscode-languageclient 9.0.1).
Precedence: vfmt.toml > vfmt.* settings > editor tabSize > built-in
default — a checked-in config stays authoritative so format-on-save never
diverges from CI. Invalid values are ignored, never clamped or coerced;
exclude is appended to the config's excludes and re-indexes the workspace
on change. Untitled buffers and toml-less projects gain an editor-set
line length, previously impossible over LSP.

Co-Authored-By: Claude Fable 5 <[email protected]>
This commit is contained in:
lucioandClaude Fable 5 committed 2026-08-24 03:15:54 -07:00
1 parent aa26e5e427
commit 9a3a92cabb
11 files changed
+1180 -61

No files matched your search

+223 -37
View File
@@ -13,6 +13,7 @@ use lsp_types::{FormattingOptions, Range, TextEdit};
use vfmt_core::config::{Discovery, FileConfig};
use vlog_formatter::{format_range, format_source, Config, LineRanges};
use crate::settings::ClientSettings;
use crate::state::Document;
/// Indent widths a client may ask for. The same 1..8 range `vfmt.toml`'s own
@@ -32,19 +33,31 @@ pub struct Settings {
/// Resolve the settings governing a buffer.
///
/// Precedence is **`vfmt.toml` > the client's tab size > the built-in
/// default**, which is *not* the CLI's flag-beats-config order, and
/// deliberately so: a CLI flag is typed on purpose for one run, while
/// `FormattingOptions::tab_size` is sent on every request whether or not the
/// user ever chose it (it is the editor's own default, or its guess from the
/// file). Letting an editor default silently beat a checked-in `vfmt.toml`
/// would make format-on-save disagree with CI's `vfmt --check` — the exact
/// divergence lifting the config into `vfmt_core` exists to remove. Where the
/// config is silent the tab size still wins over the built-in default, so a
/// project with no `vfmt.toml` behaves as it did before.
pub fn settings_for(doc: &Document, options: &FormattingOptions) -> Settings {
/// Precedence, highest first:
///
/// 1. **`vfmt.toml`** — a checked-in config is the project speaking, and it
/// must stay authoritative or format-on-save would disagree with CI's
/// `vfmt --check`. That divergence is the exact thing lifting the config
/// into `vfmt_core` exists to remove.
/// 2. **The client's `vfmt.*` settings** (`settings.rs`) — typed on purpose
/// into an editor's settings UI, so more deliberate than a tab size, but
/// it is one user's editor and the repository outranks it.
/// 3. **`FormattingOptions::tab_size`** — sent on every request whether or
/// not the user ever chose it; it is the editor's own default, or its
/// guess from the file, so it is the weakest thing that is still a signal.
/// This is *not* the CLI's flag-beats-config order, and deliberately so.
/// 4. **The built-in default.**
///
/// Each rung applies only where every rung above it is silent, so a project
/// with no `vfmt.toml` and no `vfmt.*` settings behaves exactly as it did
/// before either existed.
pub fn settings_for(
doc: &Document,
client: &ClientSettings,
options: &FormattingOptions,
) -> Settings {
let (file, problem) = discover(doc.path.as_deref());
Settings { config: config_from(&file, options), problem }
Settings { config: config_from(&file, client, options), problem }
}
/// Format a buffer.
@@ -95,13 +108,14 @@ pub fn range_formatting(
/// spaces where a tab was.
///
/// A `textDocument/codeAction` request carries no `FormattingOptions`, so there
/// is no client `tabSize` to consider here — the precedence is just
/// `vfmt.toml` > the built-in default. A broken config is silent on this path:
/// the formatting path is where the user is told about it, and warning from a
/// is no client `tabSize` to consider here — the precedence is the same ladder
/// `settings_for` documents with rung 3 missing: `vfmt.toml` > `vfmt.indent` >
/// the built-in default. A broken config is silent on this path: the
/// formatting path is where the user is told about it, and warning from a
/// lightbulb the editor requests on every cursor move would be noise.
pub fn indent_width(path: Option<&Path>) -> usize {
pub fn indent_width(path: Option<&Path>, client: &ClientSettings) -> usize {
let (file, _problem) = discover(path);
file.indent.unwrap_or(Config::default().indent_width)
file.indent.or(client.indent).unwrap_or(Config::default().indent_width)
}
/// The config file governing `path`, by the CLI's own discovery rule, or the
@@ -119,19 +133,27 @@ fn discover(path: Option<&Path>) -> (FileConfig, Option<String>) {
}
}
/// Fold the config file and the client's tab options into formatter settings,
/// in the precedence `settings_for` documents.
/// Fold the config file, the pushed `vfmt.*` settings and the client's tab
/// options into formatter settings, in the precedence `settings_for`
/// documents. Written weakest-first, so the last writer wins.
///
/// The client's `tab_size` is taken only when the request is sane: a client
/// asking for hard tabs, or for a 40-space indent, is asking for something
/// vfmt does not do, and silently honoring half of it is worse than ignoring
/// it. `max_width` is never taken from the client — the protocol has no
/// line-length option, so it comes from `vfmt.toml` or not at all.
fn config_from(file: &FileConfig, options: &FormattingOptions) -> Config {
/// it. `vfmt.lineLength` has no `FormattingOptions` analog at all — the
/// protocol carries no line-length option — so before it existed there was no
/// way to set a width from an editor without a `vfmt.toml`.
fn config_from(file: &FileConfig, client: &ClientSettings, options: &FormattingOptions) -> Config {
let mut config = Config::default();
if options.insert_spaces && INDENT_RANGE.contains(&options.tab_size) {
config.indent_width = options.tab_size as usize;
}
if let Some(indent) = client.indent {
config.indent_width = indent;
}
if let Some(line_length) = client.line_length {
config.max_width = line_length;
}
if let Some(indent) = file.indent {
config.indent_width = indent;
}
@@ -144,6 +166,7 @@ fn config_from(file: &FileConfig, options: &FormattingOptions) -> Config {
#[cfg(test)]
mod tests {
use super::*;
use crate::settings::ClientSettings;
use crate::state::Workspace;
use lsp_types::{Position, Uri};
use std::path::PathBuf;
@@ -161,18 +184,42 @@ mod tests {
FormattingOptions { tab_size, insert_spaces, ..Default::default() }
}
/// The settings a buffer with no config file on disk resolves to.
/// No `vfmt.*` settings pushed — what every test predating them assumes.
fn none() -> ClientSettings {
ClientSettings::default()
}
/// The settings a buffer resolves to, with nothing pushed by the client.
fn settings(ws: &Workspace, uri: &Uri, options: &FormattingOptions) -> Settings {
settings_for(ws.document(uri).expect("open"), options)
settings_with(ws, uri, &none(), options)
}
/// The settings a buffer resolves to against a given pushed configuration.
fn settings_with(
ws: &Workspace,
uri: &Uri,
client: &ClientSettings,
options: &FormattingOptions,
) -> Settings {
settings_for(ws.document(uri).expect("open"), client, options)
}
fn edit_of(
ws: &Workspace,
uri: &Uri,
options: &FormattingOptions,
) -> Result<Option<TextEdit>, String> {
edit_with(ws, uri, &none(), options)
}
fn edit_with(
ws: &Workspace,
uri: &Uri,
client: &ClientSettings,
options: &FormattingOptions,
) -> Result<Option<TextEdit>, String> {
let doc = ws.document(uri).expect("open");
formatting(doc, &settings_for(doc, options).config)
formatting(doc, &settings_for(doc, client, options).config)
}
/// A scratch directory holding a `vfmt.toml` and one source file, so
@@ -238,16 +285,32 @@ mod tests {
#[test]
fn hard_tabs_and_absurd_widths_fall_back_to_the_default() {
let none = FileConfig::default();
assert_eq!(config_from(&none, &options(4, false)).indent_width, 2, "hard tabs ignored");
assert_eq!(config_from(&none, &options(40, true)).indent_width, 2, "out of range ignored");
assert_eq!(config_from(&none, &options(0, true)).indent_width, 2, "zero ignored");
assert_eq!(config_from(&none, &options(8, true)).indent_width, 8, "the top of the range");
let nothing = FileConfig::default();
assert_eq!(
config_from(&nothing, &none(), &options(4, false)).indent_width,
2,
"hard tabs ignored"
);
assert_eq!(
config_from(&nothing, &none(), &options(40, true)).indent_width,
2,
"out of range ignored"
);
assert_eq!(
config_from(&nothing, &none(), &options(0, true)).indent_width,
2,
"zero ignored"
);
assert_eq!(
config_from(&nothing, &none(), &options(8, true)).indent_width,
8,
"the top of the range"
);
}
#[test]
fn a_line_length_is_never_taken_from_the_client() {
let config = config_from(&FileConfig::default(), &options(4, true));
let config = config_from(&FileConfig::default(), &none(), &options(4, true));
assert_eq!(config.max_width, Config::default().max_width);
}
@@ -257,12 +320,12 @@ mod tests {
// unless the user changed it, and a checked-in `vfmt.toml` is always
// deliberate. See `settings_for`.
let file = FileConfig { line_length: Some(120), indent: Some(4), exclude: None };
let config = config_from(&file, &options(2, true));
let config = config_from(&file, &none(), &options(2, true));
assert_eq!(config.indent_width, 4, "vfmt.toml wins over tab_size");
assert_eq!(config.max_width, 120, "line-length has no client analog at all");
// Where the config is silent the tab size still beats the default.
let only_width = FileConfig { line_length: Some(120), indent: None, exclude: None };
assert_eq!(config_from(&only_width, &options(3, true)).indent_width, 3);
assert_eq!(config_from(&only_width, &none(), &options(3, true)).indent_width, 3);
}
#[test]
@@ -300,8 +363,12 @@ mod tests {
let tree = Tree::new("indent = 4\n");
let (ws, uri) = tree.document("module m;\n\twire a;\nendmodule\n");
let doc = ws.document(&uri).expect("open");
assert_eq!(indent_width(doc.path.as_deref()), 4);
assert_eq!(indent_width(None), Config::default().indent_width, "an untitled buffer");
assert_eq!(indent_width(doc.path.as_deref(), &none()), 4);
assert_eq!(
indent_width(None, &none()),
Config::default().indent_width,
"an untitled buffer"
);
}
#[test]
@@ -309,7 +376,7 @@ mod tests {
let tree = Tree::new("indent = 4\nbogus = 1\n");
let (ws, uri) = tree.document("module m;\n\twire a;\nendmodule\n");
let doc = ws.document(&uri).expect("open");
assert_eq!(indent_width(doc.path.as_deref()), Config::default().indent_width);
assert_eq!(indent_width(doc.path.as_deref(), &none()), Config::default().indent_width);
}
#[test]
@@ -322,6 +389,125 @@ mod tests {
assert_eq!(settings.config.indent_width, 4, "the tab size is all there is");
}
// ------------------------------------------------------------------
// the precedence ladder, one rung at a time
// ------------------------------------------------------------------
/// `vfmt.*` settings as a client would push them.
fn pushed(line_length: Option<usize>, indent: Option<usize>) -> ClientSettings {
ClientSettings { line_length, indent, exclude: Vec::new() }
}
#[test]
fn rung_1_a_config_file_beats_a_pushed_setting() {
// The whole reason the ladder is in this order: a checked-in
// `vfmt.toml` is the project speaking, and format-on-save must agree
// with what `vfmt --check` does in CI.
let tree = Tree::new("indent = 4\nline-length = 120\n");
let (ws, uri) = tree.document("module m;\nwire a;\nendmodule\n");
let client = pushed(Some(80), Some(8));
let settings = settings_with(&ws, &uri, &client, &options(2, true));
assert_eq!(settings.config.indent_width, 4, "vfmt.toml wins");
assert_eq!(settings.config.max_width, 120, "for line-length too");
let edit = edit_with(&ws, &uri, &client, &options(2, true)).expect("formats");
assert_eq!(edit.expect("changed").new_text, "module m;\n wire a;\nendmodule\n");
}
#[test]
fn rung_2_a_pushed_setting_beats_the_editors_tab_size() {
// `tabSize` arrives on every request whether the user chose it or
// not; `vfmt.indent` was typed on purpose.
let (ws, uri) = document("module m;\nwire a;\nendmodule\n");
let client = pushed(None, Some(4));
let settings = settings_with(&ws, &uri, &client, &options(2, true));
assert_eq!(settings.config.indent_width, 4);
let edit = edit_with(&ws, &uri, &client, &options(2, true)).expect("formats");
assert_eq!(edit.expect("changed").new_text, "module m;\n wire a;\nendmodule\n");
}
#[test]
fn rung_3_the_tab_size_still_beats_the_default_where_nothing_was_pushed() {
let (ws, uri) = document("module m;\nwire a;\nendmodule\n");
// Pushed settings that say nothing about indent leave rung 3 in charge.
let client = pushed(Some(120), None);
let settings = settings_with(&ws, &uri, &client, &options(3, true));
assert_eq!(settings.config.indent_width, 3, "the tab size");
assert_eq!(settings.config.max_width, 120, "and the pushed width");
}
#[test]
fn rung_4_the_default_applies_when_every_rung_above_is_silent() {
let (ws, uri) = document("module m;\nwire a;\nendmodule\n");
// Hard tabs, so even the tab size is not a usable signal.
let settings = settings_with(&ws, &uri, &none(), &options(4, false));
assert_eq!(settings.config.indent_width, Config::default().indent_width);
assert_eq!(settings.config.max_width, Config::default().max_width);
}
#[test]
fn each_key_climbs_the_ladder_independently() {
// A `vfmt.toml` naming only `indent` must not also claim the width:
// the pushed `lineLength` is still the best answer for that key.
let tree = Tree::new("indent = 4\n");
let (ws, uri) = tree.document("module m;\nwire a;\nendmodule\n");
let settings = settings_with(&ws, &uri, &pushed(Some(60), Some(8)), &options(2, true));
assert_eq!(settings.config.indent_width, 4, "config wins the key it names");
assert_eq!(settings.config.max_width, 60, "and is silent about the other");
}
#[test]
fn a_pushed_line_length_is_the_only_way_to_set_a_width_without_a_config() {
// The protocol has no line-length option at all, so before
// `vfmt.lineLength` a config-less project could not narrow its lines
// from the editor. This is the new capability, at the level that
// actually reflows text.
let long = "module m;\n assign a = bbbbbbbbbbbb + cccccccccccc + dddddddddddd + eeeeeeeeeeee;\nendmodule\n";
let (ws, uri) = document(long);
assert_eq!(edit_of(&ws, &uri, &options(2, true)).expect("formats"), None, "fits at 100");
let edit = edit_with(&ws, &uri, &pushed(Some(40), None), &options(2, true))
.expect("formats")
.expect("40 columns must reflow it");
assert!(edit.new_text.lines().count() > long.lines().count(), "{}", edit.new_text);
}
#[test]
fn an_untitled_buffer_honours_pushed_settings() {
// It has no directory to discover a `vfmt.toml` from, so rung 2 is the
// highest rung it has — and before this feature it had only `tabSize`.
let uri = Uri::from_str("untitled:Untitled-1").expect("uri");
let mut ws = Workspace::default();
ws.set_document(uri.clone(), "module m;\nwire a;\nendmodule\n".to_string());
let settings = settings_with(&ws, &uri, &pushed(Some(60), Some(4)), &options(2, true));
assert_eq!(settings.problem, None);
assert_eq!(settings.config.indent_width, 4, "pushed indent beats the tab size");
assert_eq!(settings.config.max_width, 60);
}
#[test]
fn a_lint_fix_climbs_the_same_ladder_without_rung_3() {
// A code action has no `tabSize`, so `vfmt.indent` is the only thing
// under a `vfmt.toml` here.
let tree = Tree::new("indent = 4\n");
let (ws, uri) = tree.document("module m;\n\twire a;\nendmodule\n");
let doc = ws.document(&uri).expect("open");
assert_eq!(indent_width(doc.path.as_deref(), &pushed(None, Some(8))), 4, "config wins");
assert_eq!(indent_width(None, &pushed(None, Some(8))), 8, "untitled: the pushed value");
assert_eq!(indent_width(None, &none()), Config::default().indent_width, "then default");
}
#[test]
fn a_broken_config_leaves_the_pushed_settings_in_charge() {
// Nothing from a broken `vfmt.toml` is used, so the next rung down is
// the one that answers — which is now the pushed settings, not the
// built-in default.
let tree = Tree::new("indent = 4\nbogus = 1\n");
let (ws, uri) = tree.document("module m;\nwire a;\nendmodule\n");
let settings = settings_with(&ws, &uri, &pushed(Some(60), Some(8)), &options(2, true));
assert!(settings.problem.is_some(), "the user is still told");
assert_eq!(settings.config.indent_width, 8);
assert_eq!(settings.config.max_width, 60);
}
/// Three items, one per line, so a range's reach is visible line by line.
const THREE: &str = "module m;\n wire a;\n wire b;\nendmodule\n";
@@ -335,7 +521,7 @@ mod tests {
fn ranged(text: &str, range: Range) -> Result<Option<TextEdit>, String> {
let (ws, uri) = document(text);
let doc = ws.document(&uri).expect("open");
range_formatting(doc, &settings_for(doc, &options(2, true)).config, range)
range_formatting(doc, &settings_for(doc, &none(), &options(2, true)).config, range)
}
#[test]
+1
View File
@@ -16,6 +16,7 @@ mod locate;
mod nav;
mod pairs;
mod server;
mod settings;
mod state;
mod symbols;
mod tokens;
+42 -17
View File
@@ -10,8 +10,8 @@ use std::error::Error;
use lsp_server::{Connection, ExtractError, Message, Notification, Request, RequestId, Response};
use lsp_types::notification::{
DidChangeTextDocument, DidCloseTextDocument, DidOpenTextDocument, DidSaveTextDocument,
LogMessage, Notification as _, PublishDiagnostics, ShowMessage,
DidChangeConfiguration, DidChangeTextDocument, DidCloseTextDocument, DidOpenTextDocument,
DidSaveTextDocument, LogMessage, Notification as _, PublishDiagnostics, ShowMessage,
};
use lsp_types::request::{
CodeActionRequest, DocumentHighlightRequest, DocumentSymbolRequest, Formatting, GotoDefinition,
@@ -19,19 +19,19 @@ use lsp_types::request::{
WorkspaceSymbolRequest,
};
use lsp_types::{
CodeActionParams, DidChangeTextDocumentParams, DidCloseTextDocumentParams,
DidOpenTextDocumentParams, DidSaveTextDocumentParams, DocumentFormattingParams,
DocumentHighlightParams, DocumentRangeFormattingParams, DocumentSymbolParams,
DocumentSymbolResponse, GotoDefinitionParams, GotoDefinitionResponse, HoverParams,
LogMessageParams, MessageType, Position, PublishDiagnosticsParams, ReferenceParams,
SemanticTokensParams, SemanticTokensResult, ShowMessageParams, Uri, WorkspaceSymbolParams,
WorkspaceSymbolResponse,
CodeActionParams, DidChangeConfigurationParams, DidChangeTextDocumentParams,
DidCloseTextDocumentParams, DidOpenTextDocumentParams, DidSaveTextDocumentParams,
DocumentFormattingParams, DocumentHighlightParams, DocumentRangeFormattingParams,
DocumentSymbolParams, DocumentSymbolResponse, GotoDefinitionParams, GotoDefinitionResponse,
HoverParams, LogMessageParams, MessageType, Position, PublishDiagnosticsParams,
ReferenceParams, SemanticTokensParams, SemanticTokensResult, ShowMessageParams, Uri,
WorkspaceSymbolParams, WorkspaceSymbolResponse,
};
use serde::de::DeserializeOwned;
use serde_json::Value;
use crate::state::Workspace;
use crate::{code_action, diagnostics, format, hover, nav, pairs, symbols, tokens};
use crate::{code_action, diagnostics, format, hover, nav, pairs, settings, symbols, tokens};
/// Everything the server owns.
pub struct Server {
@@ -147,7 +147,10 @@ impl Server {
// A code-action request carries no `tabSize`, so the
// width a `no-tabs` fix writes comes from the buffer's
// own `vfmt.toml` or from the built-in default.
let tab_width = format::indent_width(doc.path.as_deref());
let tab_width = format::indent_width(
doc.path.as_deref(),
self.workspace.client_settings(),
);
to_value(code_action::code_actions(
&uri,
doc,
@@ -187,7 +190,7 @@ impl Server {
fn formatting(&mut self, params: DocumentFormattingParams) -> Result<Value, Failure> {
let uri = params.text_document.uri;
let Some(doc) = self.workspace.document(&uri) else { return Ok(Value::Null) };
let settings = format::settings_for(doc, &params.options);
let settings = format::settings_for(doc, self.workspace.client_settings(), &params.options);
let result = format::formatting(doc, &settings.config);
// A broken `vfmt.toml` is a warning, not a failure: the CLI exits 2 on
// one, but an editor that refuses to format because of a typo in a
@@ -206,7 +209,7 @@ impl Server {
) -> Result<Value, Failure> {
let uri = params.text_document.uri;
let Some(doc) = self.workspace.document(&uri) else { return Ok(Value::Null) };
let settings = format::settings_for(doc, &params.options);
let settings = format::settings_for(doc, self.workspace.client_settings(), &params.options);
let result = format::range_formatting(doc, &settings.config, params.range);
self.warn_about_config(&uri, settings.problem);
self.edits(result)
@@ -273,11 +276,23 @@ impl Server {
if let Some(text) = p.text {
self.set_document(p.text_document.uri.clone(), text);
}
// The index is rebuilt on save and nowhere else; the
// A save is one of the two things that rebuild the index;
// the other is a change to `vfmt.exclude` below. The
// staleness window that opens is in the feature README.
self.workspace.rebuild_index();
for uri in self.workspace.open_uris() {
self.publish(&uri);
self.reindex();
}
}
// The `vfmt.*` settings, pushed at startup and on every change.
// Nothing here trusts the payload — `settings::from_payload`
// drops whatever it cannot use.
DidChangeConfiguration::METHOD => {
if let Ok(p) = extract::<DidChangeConfigurationParams>(notification) {
let pushed = settings::from_payload(&p.settings);
// Only `exclude` changes which files exist as far as this
// server is concerned; the other two are read afresh by
// the next formatting request and need no invalidation.
if self.workspace.set_client_settings(pushed) {
self.reindex();
}
}
}
@@ -298,6 +313,16 @@ impl Server {
// outgoing
// ------------------------------------------------------------------
/// Rescan the workspace and republish every open buffer against the new
/// index. Both callers changed what the index should contain — a save, or
/// a new `vfmt.exclude`.
fn reindex(&mut self) {
self.workspace.rebuild_index();
for uri in self.workspace.open_uris() {
self.publish(&uri);
}
}
/// Replace a buffer's text, re-arming its `vfmt.toml` warning: the user
/// has moved on, and a config problem is worth saying once more.
fn set_document(&mut self, uri: Uri, text: String) {
+193
View File
@@ -0,0 +1,193 @@
//! The `vfmt.*` settings a client pushes over `workspace/didChangeConfiguration`.
//!
//! These are the editor's copy of what `vfmt.toml` carries — the same three
//! keys, so a user with no config file in the tree can still say "indent 4"
//! from their editor's settings UI. They never *beat* a `vfmt.toml`: see the
//! precedence ladder in `format::settings_for` and
//! `docs/features/editor-settings/README.md`.
//!
//! Not to be confused with `format::Settings`, which is what one formatting
//! request resolved to after every rung of that ladder was applied.
use std::ops::RangeInclusive;
use serde_json::Value;
/// Accepted `line-length`, and accepted `indent`.
///
/// Duplicated from `vfmt_core::config`'s parser, which spells the same bounds
/// inline in `parse_entry` and exports no constant for them. A client's value
/// must be exactly as acceptable as the same value written in a `vfmt.toml`,
/// or the two front ends would disagree about what is valid;
/// `the_accepted_ranges_are_the_ones_vfmt_toml_accepts` asserts that against
/// the real parser rather than against a copied number.
const LINE_LENGTH_RANGE: RangeInclusive<u64> = 40..=400;
const INDENT_RANGE: RangeInclusive<u64> = 1..=8;
/// The `vfmt.*` settings in force, after validation. Every field is "no
/// opinion" until a client says otherwise, which is exactly what an unset
/// VS Code setting means.
#[derive(Debug, Default, Clone, PartialEq, Eq)]
pub struct ClientSettings {
/// `vfmt.lineLength`.
pub line_length: Option<usize>,
/// `vfmt.indent`.
pub indent: Option<usize>,
/// `vfmt.exclude`, appended to the config's excludes in the workspace scan.
pub exclude: Vec<String>,
}
/// Read the `vfmt` section out of a `workspace/didChangeConfiguration` payload.
///
/// **Nothing here trusts the client.** `package.json`'s JSON schema constrains
/// the settings UI, but the notification is just JSON on a socket, and other
/// editors (the Neovim setup in `editors/nvim/README.md` writes the same
/// section by hand) have no schema at all. A value of the wrong type, out of
/// range, or missing is dropped and leaves that rung of the ladder silent —
/// the same choice `format::config_from` already makes for an absurd
/// `tabSize`, for the same reason: silently honouring half of a nonsensical
/// request is worse than ignoring it.
pub fn from_payload(settings: &Value) -> ClientSettings {
// `{"settings": {"vfmt": {...}}}` — the shape
// `synchronize.configurationSection: 'vfmt'` produces. A payload without
// the section (including the `{"settings": null}` a client sends when it
// syncs no section at all) means "no opinion about anything".
let Some(vfmt) = settings.get("vfmt") else { return ClientSettings::default() };
ClientSettings {
line_length: bounded(vfmt.get("lineLength"), LINE_LENGTH_RANGE),
indent: bounded(vfmt.get("indent"), INDENT_RANGE),
exclude: strings(vfmt.get("exclude")),
}
}
/// A JSON integer inside `range`, or nothing.
///
/// `as_u64` rejects null, strings, booleans, negatives and fractions in one
/// step. A non-integral number cannot reach here from VS Code anyway —
/// JavaScript serializes `4.0` as `4` — so there is no "close enough" case to
/// forgive.
fn bounded(value: Option<&Value>, range: RangeInclusive<u64>) -> Option<usize> {
let number = value?.as_u64()?;
range.contains(&number).then_some(number as usize)
}
/// Every string in a JSON array, or an empty list for anything else. Entries
/// that are not strings are dropped rather than stringified: a number in an
/// exclude list is a mistake, and guessing what it meant would hide it.
fn strings(value: Option<&Value>) -> Vec<String> {
let Some(Value::Array(items)) = value else { return Vec::new() };
items.iter().filter_map(Value::as_str).map(str::to_string).collect()
}
#[cfg(test)]
mod tests {
use super::*;
use serde_json::json;
/// The settings a `didChangeConfiguration` payload resolves to.
fn settings(payload: Value) -> ClientSettings {
from_payload(&payload)
}
/// The payload shape `vscode-languageclient` actually sends for
/// `synchronize.configurationSection: 'vfmt'` — the whole section, with
/// every key present at its default. Verified against the real library in
/// `node_modules`; see the feature README's Handshakes.
fn vscode_payload(line_length: Value, indent: Value, exclude: Value) -> Value {
json!({
"vfmt": {
"serverPath": "vfmt-server",
"rainbowBeginEnd": true,
"lineLength": line_length,
"indent": indent,
"exclude": exclude
}
})
}
#[test]
fn the_default_vscode_payload_is_no_opinion_about_anything() {
// Every setting at its `package.json` default: nulls and an empty
// list, which must leave today's behaviour exactly unchanged.
let found = settings(vscode_payload(json!(null), json!(null), json!([])));
assert_eq!(found, ClientSettings::default());
}
#[test]
fn a_populated_payload_is_read_whole() {
let found = settings(vscode_payload(json!(120), json!(4), json!(["vendor", "*_gen.sv"])));
assert_eq!(found.line_length, Some(120));
assert_eq!(found.indent, Some(4));
assert_eq!(found.exclude, vec!["vendor".to_string(), "*_gen.sv".to_string()]);
}
#[test]
fn a_payload_without_our_section_says_nothing() {
assert_eq!(settings(json!({ "someOtherServer": { "indent": 4 } })), Default::default());
assert_eq!(settings(json!(null)), Default::default(), "the `settings: null` form");
assert_eq!(settings(json!({})), Default::default());
}
#[test]
fn a_missing_key_is_not_an_opinion() {
// A hand-written Neovim `settings` table names only what it cares
// about; the keys it leaves out must stay silent, not become 0.
let found = settings(json!({ "vfmt": { "indent": 4 } }));
assert_eq!(found.indent, Some(4));
assert_eq!(found.line_length, None);
assert!(found.exclude.is_empty());
}
#[test]
fn out_of_range_numbers_are_ignored() {
for bad in [json!(0), json!(9), json!(100), json!(-1)] {
let found = settings(json!({ "vfmt": { "indent": bad } }));
assert_eq!(found.indent, None, "indent {bad} must be ignored");
}
for bad in [json!(0), json!(39), json!(401), json!(-40)] {
let found = settings(json!({ "vfmt": { "lineLength": bad } }));
assert_eq!(found.line_length, None, "lineLength {bad} must be ignored");
}
}
#[test]
fn the_range_edges_are_accepted() {
let found = settings(json!({ "vfmt": { "indent": 1, "lineLength": 40 } }));
assert_eq!((found.indent, found.line_length), (Some(1), Some(40)));
let found = settings(json!({ "vfmt": { "indent": 8, "lineLength": 400 } }));
assert_eq!((found.indent, found.line_length), (Some(8), Some(400)));
}
#[test]
fn wrong_types_are_ignored_rather_than_coerced() {
for bad in [json!("4"), json!(true), json!([4]), json!({ "n": 4 }), json!(4.5)] {
let found = settings(json!({ "vfmt": { "indent": bad, "lineLength": bad } }));
assert_eq!(found.indent, None, "indent {bad} must be ignored");
assert_eq!(found.line_length, None, "lineLength {bad} must be ignored");
}
}
#[test]
fn an_exclude_that_is_not_a_list_of_strings_contributes_nothing() {
assert!(settings(json!({ "vfmt": { "exclude": "vendor" } })).exclude.is_empty());
assert!(settings(json!({ "vfmt": { "exclude": 3 } })).exclude.is_empty());
assert!(settings(json!({ "vfmt": { "exclude": null } })).exclude.is_empty());
// A mixed array keeps the strings and drops the rest.
let found = settings(json!({ "vfmt": { "exclude": ["ok", 3, null, "fine"] } }));
assert_eq!(found.exclude, vec!["ok".to_string(), "fine".to_string()]);
}
#[test]
fn the_accepted_ranges_are_the_ones_vfmt_toml_accepts() {
// The bounds above are copied from `vfmt_core::config`, which exports
// no constant for them. Rather than trust the copy, ask the real
// parser: every edge this module accepts must parse, and every value
// it rejects must be rejected there too. If `vfmt.toml` ever widens a
// range, this fails and says so.
let ok = |text: &str| vfmt_core::config::parse(text).is_ok();
assert!(ok("indent = 1") && ok("indent = 8"), "the indent edges");
assert!(!ok("indent = 0") && !ok("indent = 9"), "just outside indent");
assert!(ok("line-length = 40") && ok("line-length = 400"), "the line-length edges");
assert!(!ok("line-length = 39") && !ok("line-length = 401"), "just outside line-length");
}
}
+104 -1
View File
@@ -18,6 +18,7 @@ use vfmt_core::config::Discovery;
use vfmt_core::walk::collect_files;
use crate::convert::Positions;
use crate::settings::ClientSettings;
use crate::uri::uri_to_path;
/// How many `workspace/symbol` hits are returned. Each one costs a file read
@@ -85,6 +86,8 @@ pub struct Workspace {
docs: HashMap<Uri, Document>,
roots: Vec<PathBuf>,
index: WorkspaceIndex,
/// The last `vfmt.*` settings a client pushed. Default until it does.
client: ClientSettings,
}
impl Workspace {
@@ -98,6 +101,24 @@ impl Workspace {
&self.index
}
/// The `vfmt.*` settings in force, for the resolution points in
/// `format.rs` to fold in.
pub fn client_settings(&self) -> &ClientSettings {
&self.client
}
/// Adopt the settings a client pushed.
///
/// Returns `true` when the caller must rebuild the index: `exclude` is the
/// only one of the three that changes *which files exist* as far as this
/// server is concerned. `lineLength` and `indent` are read afresh by every
/// formatting request, so they need no invalidation at all.
pub fn set_client_settings(&mut self, settings: ClientSettings) -> bool {
let rescan = self.client.exclude != settings.exclude;
self.client = settings;
rescan
}
pub fn document(&self, uri: &Uri) -> Option<&Document> {
self.docs.get(uri)
}
@@ -166,7 +187,13 @@ impl Workspace {
// index that excludes nothing is a far better failure than a
// server that comes up empty. The error is reported when the user
// formats a file in this tree (`format::settings_for`).
let exclude = discovery.for_dir(root).unwrap_or_default().exclude.unwrap_or_default();
let mut exclude =
discovery.for_dir(root).unwrap_or_default().exclude.unwrap_or_default();
// The client's `vfmt.exclude` is *appended*, never substituted —
// the CLI appends a config's excludes to `--exclude` the same way,
// and a setting that silently dropped a checked-in exclude would
// put vendored code back in the index for one user only.
exclude.extend(self.client.exclude.iter().cloned());
// `.gitignore` is always honoured: it is the CLI's default, and an
// editor has no `--no-gitignore` to type. An unreadable root is
// simply not indexed, exactly as before this walk was shared.
@@ -322,6 +349,82 @@ mod tests {
assert_eq!(ws.index().member("kept", "K").len(), 1);
}
/// `vfmt.exclude` as a client would push it.
fn excluding(patterns: &[&str]) -> ClientSettings {
ClientSettings {
exclude: patterns.iter().map(|p| p.to_string()).collect(),
..Default::default()
}
}
#[test]
fn a_pushed_exclude_hides_files_from_the_index() {
let tree = Tree::new("clientexclude");
tree.package("kept.sv", "kept");
tree.package("scratch/wip.sv", "scratch_pkg");
let mut ws = Workspace::default();
ws.open_roots(vec![tree.path.clone()]);
assert_eq!(ws.index().member("scratch_pkg", "K").len(), 1, "premise: indexed at first");
assert!(ws.set_client_settings(excluding(&["scratch"])), "an exclude change rescans");
ws.rebuild_index();
assert_eq!(ws.index().member("kept", "K").len(), 1, "an unmatched file stays");
assert_eq!(ws.index().member("scratch_pkg", "K").len(), 0, "the excluded one is gone");
}
#[test]
fn a_pushed_exclude_is_appended_to_the_configs_and_does_not_replace_it() {
// The failure this guards: a user setting `vfmt.exclude` in their
// editor and thereby putting the project's vendored code — which the
// checked-in `vfmt.toml` excludes — back into the index for them only.
let tree = Tree::new("bothexcludes");
tree.write("vfmt.toml", "exclude = [\"vendor\"]\n");
tree.package("kept.sv", "kept");
tree.package("vendor/ip.sv", "vendor_pkg");
tree.package("scratch/wip.sv", "scratch_pkg");
let mut ws = Workspace::default();
ws.set_client_settings(excluding(&["scratch"]));
ws.open_roots(vec![tree.path.clone()]);
assert_eq!(ws.index().member("kept", "K").len(), 1, "an unmatched file stays");
assert_eq!(ws.index().member("vendor_pkg", "K").len(), 0, "the config's exclude holds");
assert_eq!(ws.index().member("scratch_pkg", "K").len(), 0, "and the pushed one applies");
}
#[test]
fn only_an_exclude_change_asks_for_a_rescan() {
// `lineLength` and `indent` are read afresh by every formatting
// request, so re-walking the workspace for them would be pure cost.
let mut ws = Workspace::default();
assert!(!ws.set_client_settings(ClientSettings::default()), "nothing changed");
assert!(
!ws.set_client_settings(ClientSettings {
line_length: Some(120),
indent: Some(4),
exclude: Vec::new()
}),
"widths do not move files"
);
assert!(ws.set_client_settings(excluding(&["a"])), "a new exclude does");
assert!(!ws.set_client_settings(excluding(&["a"])), "the same one again does not");
assert!(ws.set_client_settings(excluding(&["a", "b"])), "an added pattern does");
assert!(ws.set_client_settings(ClientSettings::default()), "and so does clearing it");
}
#[test]
fn the_pushed_settings_are_readable_where_formatting_needs_them() {
let mut ws = Workspace::default();
assert_eq!(ws.client_settings(), &ClientSettings::default(), "default until pushed");
ws.set_client_settings(ClientSettings {
line_length: Some(120),
indent: Some(4),
exclude: Vec::new(),
});
assert_eq!(ws.client_settings().indent, Some(4));
assert_eq!(ws.client_settings().line_length, Some(120));
}
#[test]
fn the_scan_takes_only_source_extensions() {
let tree = Tree::new("extensions");
+133
View File
@@ -611,3 +611,136 @@ fn scope_highlights_and_the_missing_end_warning_round_trip_over_the_wire() {
let _ = std::fs::remove_dir_all(&dir);
}
/// One unindented item, so the indent the server chose is visible in the edit.
const UNINDENTED: &str = "module settings_me;\nwire a;\nendmodule\n";
#[test]
fn pushed_settings_reach_the_formatter_and_can_change_mid_session() {
let dir = temp_dir("settings");
let file = dir.join("settings_me.sv");
std::fs::write(&file, UNINDENTED).expect("write");
let root = format!("file://{}", dir.display());
let uri = format!("file://{}", file.display());
// Every format asks for a 2-space tab, so anything else in the answer came
// from the pushed settings.
let format = |id: u32| {
frame(&format!(
r#"{{"jsonrpc":"2.0","id":{id},"method":"textDocument/formatting","params":{{"textDocument":{{"uri":"{uri}"}},"options":{{"tabSize":2,"insertSpaces":true}}}}}}"#
))
};
let push = |indent: &str| {
frame(&format!(
r#"{{"jsonrpc":"2.0","method":"workspace/didChangeConfiguration","params":{{"settings":{{"vfmt":{{"serverPath":"vfmt-server","rainbowBeginEnd":true,"lineLength":null,"indent":{indent},"exclude":[]}}}}}}}}"#
))
};
let session = [
frame(&format!(
r#"{{"jsonrpc":"2.0","id":1,"method":"initialize","params":{{"processId":null,"rootUri":"{root}","capabilities":{{}}}}}}"#
)),
frame(r#"{"jsonrpc":"2.0","method":"initialized","params":{}}"#),
frame(&format!(
r#"{{"jsonrpc":"2.0","method":"textDocument/didOpen","params":{{"textDocument":{{"uri":"{uri}","languageId":"systemverilog","version":1,"text":{}}}}}}}"#,
serde_json::to_string(UNINDENTED).expect("json")
)),
// Nothing pushed yet: the editor's tab size is the best signal there is.
format(2),
// The initial push a client makes on startup.
push("4"),
format(3),
// The user changes their mind mid-session — no restart, no reload.
push("8"),
format(4),
// And clears the setting again, handing the tab size back.
push("null"),
format(5),
// A payload that is nonsense must be ignored, not honoured by halves.
frame(r#"{"jsonrpc":"2.0","method":"workspace/didChangeConfiguration","params":{"settings":{"vfmt":{"indent":"four","lineLength":9999}}}}"#),
format(6),
frame(r#"{"jsonrpc":"2.0","id":9,"method":"shutdown","params":null}"#),
frame(r#"{"jsonrpc":"2.0","method":"exit","params":null}"#),
]
.concat();
let messages = talk(&session);
assert_eq!(new_text(&messages, 2), "module settings_me;\n wire a;\nendmodule\n", "tab size");
assert_eq!(new_text(&messages, 3), "module settings_me;\n wire a;\nendmodule\n", "pushed 4");
assert_eq!(
new_text(&messages, 4),
"module settings_me;\n wire a;\nendmodule\n",
"a mid-session change takes effect on the next request, with no restart"
);
assert_eq!(
new_text(&messages, 5),
"module settings_me;\n wire a;\nendmodule\n",
"clearing the setting hands the tab size back"
);
assert_eq!(
new_text(&messages, 6),
"module settings_me;\n wire a;\nendmodule\n",
"a wrong-typed indent and an out-of-range width are both ignored"
);
let _ = std::fs::remove_dir_all(&dir);
}
#[test]
fn a_pushed_exclude_rebuilds_the_index_mid_session() {
// The one link a unit test cannot check: that the notification handler
// actually re-scans. `state.rs` proves the scan honours `exclude` and that
// a change asks for a rescan; only the wire shows that `server.rs` asks.
let dir = temp_dir("exclude");
std::fs::create_dir_all(dir.join("scratch")).expect("subdir");
std::fs::write(dir.join("kept.sv"), "package kept_pkg;\n localparam K = 1;\nendpackage\n")
.expect("write");
std::fs::write(
dir.join("scratch/wip.sv"),
"package scratch_pkg;\n localparam K = 1;\nendpackage\n",
)
.expect("write");
let root = format!("file://{}", dir.display());
let query = |id: u32, name: &str| {
frame(&format!(
r#"{{"jsonrpc":"2.0","id":{id},"method":"workspace/symbol","params":{{"query":"{name}"}}}}"#
))
};
let exclude = |patterns: &str| {
frame(&format!(
r#"{{"jsonrpc":"2.0","method":"workspace/didChangeConfiguration","params":{{"settings":{{"vfmt":{{"exclude":{patterns}}}}}}}}}"#
))
};
let session = [
frame(&format!(
r#"{{"jsonrpc":"2.0","id":1,"method":"initialize","params":{{"processId":null,"rootUri":"{root}","capabilities":{{}}}}}}"#
)),
frame(r#"{"jsonrpc":"2.0","method":"initialized","params":{}}"#),
query(2, "scratch_pkg"),
exclude(r#"["scratch"]"#),
query(3, "scratch_pkg"),
query(4, "kept_pkg"),
// Clearing it puts the file back — the rescan runs in both directions.
exclude("[]"),
query(5, "scratch_pkg"),
frame(r#"{"jsonrpc":"2.0","id":9,"method":"shutdown","params":null}"#),
frame(r#"{"jsonrpc":"2.0","method":"exit","params":null}"#),
]
.concat();
let messages = talk(&session);
let hits = |id: u32| -> usize {
let response = messages
.iter()
.find(|m| m["id"] == id)
.unwrap_or_else(|| panic!("no response {id} in {messages:#?}"));
response["result"].as_array().map_or(0, |a| a.len())
};
assert_eq!(hits(2), 1, "premise: indexed before the push");
assert_eq!(hits(3), 0, "the pushed exclude took it out of the index");
assert_eq!(hits(4), 1, "and left the file it does not match alone");
assert_eq!(hits(5), 1, "clearing the setting puts it back");
let _ = std::fs::remove_dir_all(&dir);
}
+396
View File
@@ -0,0 +1,396 @@
# editor-settings
## Goal
Expose the three keys `vfmt.toml` supports — `line-length`, `indent`,
`exclude` — as VS Code settings (`vfmt.lineLength`, `vfmt.indent`,
`vfmt.exclude`), for the users who asked for them: people with no config file
checked into the tree, who until now could set the indent only by accident
(VS Code's `tabSize` leaked in through `FormattingOptions`) and could not set
a line length **at all**, because LSP carries no line-length option. The
settings are transported by `workspace/didChangeConfiguration`, validated at
the server, and folded in one rung below a `vfmt.toml` — which stays
authoritative, so a project that checks one in keeps exactly one source of
truth and format-on-save cannot drift from CI's `vfmt --check`.
## Assumptions
- **`vfmt.toml` has exactly three keys, and that is the whole surface.**
`vfmt_core::config::parse_entry` accepts `line-length`, `indent` and
`exclude` and rejects everything else by name. Rule selection
(`--select`/`--ignore`) has no config key yet, so there is nothing to expose
for the linter; when it grows one, it grows a setting here in the same shape.
- **A repository outranks an editor.** The precedence decision (below) is the
one thing in this feature that is a judgement call rather than mechanics. It
extends the reasoning `format::settings_for` already carried for `tabSize`:
the further a setting is from the code it governs, the less it should win.
- **Nothing the client sends is trusted.** `package.json`'s JSON schema bounds
the settings UI, but the notification is JSON on a socket and other editors
have no schema at all — the Neovim setup in `editors/nvim/README.md` writes
the same section by hand. Out-of-range, wrong-typed and missing values are
all dropped, leaving that rung silent. Same philosophy as the existing
`tabSize` guard: honouring half of a nonsensical request is worse than
ignoring it.
- **The accepted ranges must match `vfmt.toml`'s.** A value has to be exactly
as acceptable from the settings UI as it is in a config file, or the two
front ends would disagree about what is valid. `vfmt_core` exports no
constant for its bounds, so `settings.rs` copies them **and**
`the_accepted_ranges_are_the_ones_vfmt_toml_accepts` checks the copy against
the real parser (`vfmt_core::config::parse`) rather than against another
hard-coded number. If a range ever widens in `vfmt_core`, that test fails.
- **Only `exclude` can invalidate anything.** `lineLength` and `indent` are
read afresh by every formatting request, so a change to them needs no cache
work at all. `exclude` changes which files exist as far as the workspace
index is concerned, so it — and only it — triggers a rescan.
- **A non-integral number cannot arrive from VS Code.** JavaScript serializes
`4.0` as `4`, so `serde_json`'s `as_u64` rejecting fractions costs nothing
real; there is no "close enough" case worth forgiving.
- **The `vfmt.exclude` patterns are matched by the same engine as the
config's.** They are appended to the same `Vec<String>` that reaches
`vfmt_core::walk::collect_files`, so the glob syntax, the trailing-component
matching and the `.gitignore` interaction are whatever the CLI already does.
An empty-string pattern is harmless (`walk::matches` returns false for one),
so it is not filtered out.
## Handshakes
### The precedence ladder (the contract this feature is)
Highest first. Each rung applies only where every rung above it is silent, and
**each key climbs independently** — a `vfmt.toml` naming only `indent` leaves
`vfmt.lineLength` in charge of the width.
| # | Source | Why here |
|---|---|---|
| 1 | `vfmt.toml` | The project speaking. Must stay authoritative or format-on-save disagrees with `vfmt --check` in CI — the divergence that lifting the config into `vfmt_core` exists to remove. |
| 2 | `vfmt.lineLength` / `vfmt.indent` | Typed on purpose into a settings UI, so more deliberate than a tab size — but it is one user's editor, and the repository outranks it. |
| 3 | `FormattingOptions::tab_size` | Sent on every request whether or not the user ever chose it (it is the editor's default, or its guess from the file). The weakest thing that is still a signal. |
| 4 | Built-in defaults | indent 2, width 100. |
Two paths use a shortened ladder, and both are unchanged in spirit:
- `format::indent_width` (the `no-tabs` quick fix) has **no rung 3** — a
`textDocument/codeAction` request carries no `FormattingOptions`.
- Rung 1 is absent for an `untitled:` buffer, which has no directory to
discover a config from. Such a buffer therefore honours rung 2 now, where
before it had only the tab size.
A **broken** `vfmt.toml` contributes nothing at all (as before), so rung 2 is
what answers under it — the user still gets the warning, and still gets their
settings.
### The wire shape
Consumed: `workspace/didChangeConfiguration`, whose `settings` field carries
```json
{ "settings": { "vfmt": { "lineLength": 120, "indent": 4, "exclude": ["vendor"] } } }
```
`settings.rs::from_payload` reads `settings.vfmt` and nothing else. A payload
without that section — including the `{"settings": null}` form — means "no
opinion about anything" and resets every key. Keys may be absent, `null`, or
garbage; each is dropped independently.
**Verified against the real client library, not assumed** (the plan required
this): `[email protected]`,
`node_modules/vscode-languageclient/lib/common/configuration.js`. Its
`SyncConfigurationFeature.initialize()` registers when
`clientOptions.synchronize.configurationSection` is set, and `register()` ends
with an unconditional `this.onDidChangeConfiguration(section, undefined)` —
with `event === undefined` the `affectsConfiguration` filter is skipped, so
**the notification is sent immediately at startup** as well as on every later
change. No `initializationOptions` fallback is needed, and none was added.
`extractSettingsInformation(['vfmt'])` calls
`workspace.getConfiguration(undefined).get('vfmt')`, which returns the whole
section with every key at its effective value — so the server sees
`serverPath` and `rainbowBeginEnd` in the payload too, and ignores them.
Other editors: anything that can send `workspace/didChangeConfiguration` with
that `settings` shape works. Neovim's `vim.lsp.config` sends its `settings`
table verbatim, so `settings = { vfmt = { indent = 4 } }` is the whole setup.
### Within the server
- **Consumed from `vfmt_core`:** `config::parse` (in a test, to pin the
ranges), `config::FileConfig`, `walk::collect_files`'s `exclude` parameter.
- **Promised to `state.rs`:** `Workspace::client_settings()` and
`set_client_settings()`, the latter returning `true` exactly when the caller
must `rebuild_index()`.
- **Promised to `server.rs`:** `settings::from_payload`. The
`DidChangeConfiguration` arm is the only caller.
- **Changed signatures** (all callers updated in the same change):
`format::settings_for(doc, client, options)`,
`format::indent_width(path, client)`, and the private
`format::config_from(file, client, options)`.
**Request to the lead (outside this feature's scope, unchanged from M2/M3):**
`docs/features/vfmt-server/README.md` and `TODO.md` §6 still understate the
server (`documentHighlight`, the missing-closer diagnostics, `vfmt/scopePairs`,
and now these settings). Separately,
`docs/features/editor-packaging/README.md`'s *What was deliberately left out*
table has a row reading "Settings beyond `serverPath` — formatter options
belong in `vfmt.toml`, one source of truth", which this feature supersedes: the
one-source-of-truth rule is now enforced by *precedence* rather than by absence.
`editors/vscode/README.md` said the same thing and was updated here, because
this feature owns that file's settings table.
## Status / TODO
- [x] `settings.rs`: `ClientSettings`, `from_payload`, validation.
- [x] `Workspace` stores them; `set_client_settings` reports whether a rescan
is needed.
- [x] Folded into `settings_for` / `config_from` / `indent_width`.
- [x] `exclude` appended to the workspace scan's excludes; a change rebuilds
the index and republishes.
- [x] `extension.js` `synchronize.configurationSection: 'vfmt'`; initial-push
behaviour verified against the library source.
- [x] Three settings in `package.json` with schema bounds.
- [x] `editors/vscode/README.md` settings table and precedence ladder.
- [x] Tests: precedence per rung, invalid values, exclude append, mid-session
change (e2e), untitled buffers, `smoke.js`.
- [ ] Not done, deliberately: no per-language or per-folder override
(`[verilog]`-scoped settings). VS Code resolves those per resource, and
the server holds one workspace-wide `ClientSettings`; a `vfmt.toml` is
the per-directory mechanism and it already works.
- [ ] Not done, deliberately: no `workspace/configuration` *pull*. The push
arrives at startup and on every change, which is all that is needed;
pulling would add a request per document to answer the same question.
- [ ] Not done, deliberately: no setting for lint rule selection — there is no
`vfmt.toml` key for it yet, and inventing one here would put the editor
ahead of the CLI.
## Work log
### 2026-08-24 — M4: `vfmt.toml`'s three keys as VS Code settings
**The thing that had to be checked first.** The plan said to verify, not
assume, whether `[email protected]`'s `synchronize` emits an initial
push — because if it did not, the settings would only reach the server after
the user edited them, and the whole feature would look broken on a fresh
window. Read `lib/common/configuration.js` in `node_modules`: `initialize()`
registers the section, and `register()` unconditionally calls
`onDidChangeConfiguration(section, undefined)`, whose `undefined` event skips
the `affectsConfiguration` filter and sends the notification straight away.
**It does push at startup**, so no `initializationOptions` fallback was added.
The finding, with file and function names, is in Handshakes so the next person
does not have to re-derive it.
**Server.** New `settings.rs` — `ClientSettings` plus `from_payload`, which is
all the validation. `Workspace` gained the field, a getter, and
`set_client_settings` returning "you must rescan", which is true only for
`exclude`. `format.rs` grew one rung in the ladder, written weakest-first so
the last writer wins and the code reads in the same order as the doc comment.
`server.rs` gained the `DidChangeConfiguration` arm and a small `reindex()`
helper, since rebuild-and-republish now has two callers (a save, and a new
`exclude`); the comment on the save path saying the index is rebuilt "on save
and nowhere else" was true before this change and is now corrected rather than
left to rot.
**Two decisions worth recording.**
1. *Settings sit below `vfmt.toml`, not above.* This is the opposite of the
CLI's flag-beats-config order, and it is the same call `settings_for`
already made for `tabSize`, for the same reason: a CLI flag is typed for one
run, while an editor setting persists silently and belongs to one machine.
If a `vfmt.lineLength` of 80 could override a project's `line-length = 120`,
every save would reflow files that CI then rejects. Pinned by
`rung_1_a_config_file_beats_a_pushed_setting`.
2. *Ranges are checked against the real config parser.* Copying `40..=400` and
`1..=8` into `settings.rs` is a duplication hazard —`vfmt_core` exports no
constant, and CLAUDE.md says not to reach into another module for this
feature's convenience. Rather than leave the copy unguarded, the test asks
`vfmt_core::config::parse` whether each edge is accepted. That is strictly
better than a shared constant would have been: it tests the behaviour, not
the number.
**Tests.** 190 unit (was 177) and 9 e2e (was 7) in this crate:
- `format.rs` — one test per rung of the ladder, plus each-key-independence, a
broken config falling through to rung 2, the untitled buffer, the quick-fix
path's shortened ladder, and the capability that did not exist before:
`a_pushed_line_length_is_the_only_way_to_set_a_width_without_a_config`
asserts the text actually reflows, not just that a number was stored.
- `settings.rs` — the exact VS Code payload shape at its defaults (must be "no
opinion"), out-of-range numbers, wrong types, a non-array `exclude`, a mixed
array, a payload with no `vfmt` section, `settings: null`, and the range
cross-check above.
- `state.rs` — a pushed `exclude` hiding a file from the index; **appended, not
substituted**, so a user's setting cannot put the project's vendored code
back in the index for them alone; and that only an `exclude` change asks for
a rescan.
- `tests/e2e.rs` — `pushed_settings_reach_the_formatter_and_can_change_mid_session`
drives five formats over one session: tab size → pushed 4 → pushed 8 → back
to null → a garbage payload, asserting the emitted text each time. This is
the mid-session requirement and the ignore-invalid requirement in one place.
`a_pushed_exclude_rebuilds_the_index_mid_session` covers the one link no unit
test can reach — that the *notification handler* re-scans — by watching
`workspace/symbol` hits appear and disappear as the setting is pushed and
cleared. It was written after a hand-driven session proved the path worked;
the check is worth keeping, because a `set_client_settings` that returned
`false` for `exclude` would break this silently and nothing else would notice.
- `smoke.js` — pushes `indent: 4` in the real payload shape while asking for
`tabSize: 2`, and asserts the returned edit is 4-space indented.
Mutation-checked: changing the pushed value to `null` fails the assertion
with the 2-space output, so it is live rather than vacuous.
**Deviations from the plan.** None on substance. Two notes: (a) the plan
allowed the mid-session test to be a unit test "if the harness does not support
notifications" — it does, so it is an e2e; (b) the plan's conditional
`initializationOptions` fallback was not implemented, because the verification
it was conditioned on came back negative-for-need (the library does push).
**Verification.** `cargo fmt --all` clean, `cargo clippy --all-targets` clean,
`cargo test --workspace` green, `node smoke.js` against a freshly built
`target/debug/vfmt-server` OK, `npx @vscode/vsce ls` still accepts the
manifest, `node --check` on both JS files.
## QA log
### 2026-08-24 — round 3, Sonnet QA (M4)
Scope: the uncommitted working tree only (`git diff`/`status` vs HEAD;
everything through `aa26e5e` already QA'd). Verified `settings.rs`,
`format.rs`, `state.rs`, `server.rs`, `main.rs`, `tests/e2e.rs`, `extension.js`,
`package.json`, `smoke.js`, `editors/vscode/README.md`, and this README.
**1. Precedence ladder.** Read every rung's test in `format.rs` (`rung_1`..
`rung_4`, `each_key_climbs_the_ladder_independently`,
`a_broken_config_leaves_the_pushed_settings_in_charge`,
`an_untitled_buffer_honours_pushed_settings`). Every mixed case the charter
named is present and passes: toml-names-indent-only + settings-names-lineLength-
only (`each_key_climbs_the_ladder_independently`); settings-indent vs. differing
tabSize (`rung_2_a_pushed_setting_beats_the_editors_tab_size`); a broken
`vfmt.toml` falls through to the pushed settings (rung 2), not straight to
default — pinned by `format.rs:499` and **documented**, not just tested: the
Handshakes section states it explicitly ("A broken `vfmt.toml` contributes
nothing at all... so rung 2 is what answers under it"). No undocumented hole
found.
**2. Validation hostility.** Every value the charter listed (indent 0, 9, -1,
400.5-equivalent via 4.5, "4" string; lineLength 39, 401, 39.9-equivalent;
exclude as a string, exclude with non-string entries; `settings: null`; missing
`vfmt` section; extra unknown keys) is covered in `settings.rs`'s unit tests.
Went further and hand-drove the **built binary** (not just unit tests) with a
script sending all of the above plus `indent: 400.5`, `lineLength: 39.9`,
`exclude: [1,2,3]`, a `params` with no `settings` key at all, and a payload
mixing valid siblings (`indent: 4, lineLength: 120`) with an unknown nested key
and a dirty `exclude` array — the server processed the whole session, kept the
valid siblings (final format came back 4-space indented, confirming
`lineLength`/`indent` both survived alongside the garbage), and answered
`shutdown` cleanly. No panics anywhere in the pipeline (deserialization included,
not just `from_payload`).
**3. exclude append + re-index + republish.** `state.rs` unit tests
(`a_pushed_exclude_is_appended_to_the_configs_and_does_not_replace_it`,
`only_an_exclude_change_asks_for_a_rescan`) correctly prove append-not-replace
and the "only exclude triggers rescan" contract.
**Finding (non-blocking, test-coverage gap):**
`crates/vfmt_server/tests/e2e.rs:690-746`
(`a_pushed_exclude_rebuilds_the_index_mid_session`) opens **no document** — it
only drives `workspace/symbol` queries before/after the exclude push. That
proves the *scan* half of `reindex()` (`server.rs:319-324`) ran, but nothing in
this test, or anywhere else in the diff, asserts the *republish* half: that
`self.publish(&uri)` actually fires a new `textDocument/publishDiagnostics` for
an **open** buffer when an exclude-triggered rebuild — as opposed to a
`didSave`-triggered one — happens. The dev's own work-log entry is honest about
this ("covers... that the notification handler re-scans"); it does not claim
the republish is covered, and it isn't.
Traced the actual runtime impact: `diagnostics::all()` (`diagnostics.rs:26-31`)
composes parse diagnostics, missing-end diagnostics and lint diagnostics — none
of which read `doc.external` or the workspace index. Only `hover.rs:106` and
`nav.rs:16` consume `doc.external`. So today a republish after an exclude
change is content-identical to the previous publish for any open buffer whose
own text didn't change; the only observable proof available to a test is that
a *second* `publishDiagnostics` notification for that uri was sent at all (or,
more usefully, that a `goto-definition`/hover result for an open buffer changes
after the exclude flips a file in or out of the index — that would exercise
`doc.external` and be a stronger test than diagnostics republish). This
`reindex()` helper and its two callers are not new logic invented for this
gap — the rebuild+republish loop already existed for `didSave` before this
diff and had (and still has) no e2e assertion of its own either, so this is not
a regression this feature introduced, just a required test from the plan
("`exclude`... change triggers re-index + republish... e2e") that is not
actually closed. Suggested fix for the dev: extend
`a_pushed_exclude_rebuilds_the_index_mid_session` (or add a sibling test) that
opens a buffer referencing a symbol in the file being excluded/un-excluded and
asserts a `goto-definition` (or a second `publishDiagnostics`) reflects the
change, so the republish half has a real assertion rather than an implicit one.
**4. The real client library claim.** Read
`editors/vscode/node_modules/vscode-languageclient/lib/common/configuration.js`
directly (installed version confirmed `9.0.1` via `node_modules/vscode-
languageclient/package.json`). `SyncConfigurationFeature.initialize()` (line
109) registers when `clientOptions.synchronize.configurationSection` is set;
`register()` (line 121-128) ends with an unconditional
`this.onDidChangeConfiguration(data.registerOptions.section, undefined)` —
the `event === undefined` case skips the `affectsConfiguration` filter, so the
notification is sent immediately. Confirmed: the dev's claim is accurate, and
so is the wire shape claim — `extractSettingsInformation(['vfmt'])`
(line 174-207) calls `workspace.getConfiguration(undefined).get('vfmt')` and
wraps it under `result.vfmt`, i.e. exactly `{settings: {vfmt: {...every
declared key at its effective value...}}}`, matching `settings.rs`'s
`vscode_payload()` test helper and the README's documented shape.
`extension.js`'s `synchronize: { configurationSection: 'vfmt' }` and
`package.json`'s three new properties are all spelled `vfmt.lineLength` /
`vfmt.indent` / `vfmt.exclude` — the prefix matches. No mismatch found.
**5. smoke.js.** Built fresh with `cargo build -p vfmt_server`, ran
`node smoke.js ../../target/debug/vfmt-server` — OK. Mutation-checked the
pushed-indent assertion: changed `indent: 4` to `indent: 2` in the
`didChangeConfiguration` push, reran — got a clean `FAIL` reporting the
2-space (tabSize) output instead of 4-space, confirming the assertion is live;
restored the edit and reran — `OK` again, and `md5sum` before/after the
round-trip matched byte-for-byte (`a33792c93538b89b8d64debe117f2ab1`).
**6. Untitled buffers.** `format.rs`'s
`an_untitled_buffer_honours_pushed_settings` pins both `vfmt.indent` and
`vfmt.lineLength` applying with no path and no toml. Confirmed.
**7. Invariants.**
- `cargo test --workspace`: all green, including `vfmt_server`'s 190 unit + 9
e2e (matches the work log's claimed counts).
- `cargo fmt --all -- --check`: clean.
- `cargo clippy --all-targets`: clean (touched `settings.rs` to force a
recheck rather than trust a stale cache; still clean).
- `node --check` on both `extension.js` and `smoke.js`: OK. `package.json`
parses as JSON.
- `git diff --stat HEAD -- crates/vlog_formatter crates/vlog_parser crates/verify`:
empty — nothing under those paths touched.
- No `unwrap()`/`expect()`/`panic!` in the non-test portions of `settings.rs`,
`format.rs`, `state.rs`, `server.rs` (grepped each file up to its
`#[cfg(test)]` marker).
- package.json schema bounds (`minimum`/`maximum` 40/400 and 1/8) cross-checked
against `settings.rs`'s `LINE_LENGTH_RANGE`/`INDENT_RANGE` and against
`vfmt_core::config::parse_entry` (`crates/vfmt_core/src/config.rs:56-57`,
which is the real source of truth) — all three agree.
- Cross-checked the "exclude append mirrors the CLI" claim in Assumptions
against `crates/vfmt/src/args.rs:103-107` (`exclude_with`) — the CLI does
extend its own `--exclude` with the config's, same append-not-replace
pattern. Accurate.
**Verdict: PASS.** One finding, non-blocking (test-coverage gap in the
exclude-republish e2e path, item 3 above) — the underlying behavior was
independently verified by code reading to be correct and shares its
implementation with the already-shipped `didSave` path, so this is a request
to close a documented required test, not a functional defect.
## Review
### 2026-08-24 — lead review of M4 (after QA round 3)
Read `settings.rs` in full plus the `format.rs`, `server.rs`, `state.rs`
and `extension.js` diffs. Approved and committed. Notes:
- Settings-below-`vfmt.toml` is the right call and the rewritten
`settings_for` ladder doc states it well; the
`the_accepted_ranges_are_the_ones_vfmt_toml_accepts` test (asking the
real parser about the copied bounds) is a pattern worth reusing.
- QA's non-blocking finding stands: the exclude e2e proves the rescan but
not the republish half of `reindex()`. Functionally moot today (nothing
in `diagnostics::all` reads the index), so accepted as-is; the next
round touching `e2e.rs` should close it per QA's suggested fix.
- `extractSettingsInformation` sending the whole `vfmt` section (so the
server sees and ignores `serverPath`/`rainbowBeginEnd`) is correctly
mirrored in the tests' payload shape rather than an idealized one.
+19 -6
View File
@@ -74,13 +74,26 @@ if it ever happens.
|---|---|---|
| `vfmt.serverPath` | `"vfmt-server"` | Path to the executable. A bare name is looked up on `PATH`; an absolute path is used as given. |
| `vfmt.rainbowBeginEnd` | `true` | Colour each nesting level of `begin`/`end` and `fork`/`join` differently. Takes effect immediately — no reload. |
| `vfmt.lineLength` | unset | Maximum line width, same as `line-length` in a `vfmt.toml`. 40–400. |
| `vfmt.indent` | unset | Indent width in spaces, same as `indent` in a `vfmt.toml`. 1–8. |
| `vfmt.exclude` | `[]` | Extra patterns to keep out of the workspace index, same as `exclude` in a `vfmt.toml`. **Added to** the project's excludes, never replacing them. |
That is the whole list, deliberately. Formatter options (line length, indent)
belong in a `vfmt.toml`, not in editor settings — one source of truth for the
CLI and the editor. The server discovers `vfmt.toml` for each file exactly as
the CLI does; when it names a setting, it wins over VS Code's tab size (an
editor default is not a deliberate override). Without a config, VS Code's tab
size governs the indent and the line length is the built-in 100.
The last three mirror the three keys `vfmt.toml` supports, for people with no
config file in the tree. **A `vfmt.toml` always wins over them**, so a project
that checks one in keeps one source of truth and format-on-save cannot drift
from CI's `vfmt --check`. Full precedence, highest first:
1. `vfmt.toml`, discovered per file exactly as the CLI discovers it.
2. `vfmt.lineLength` / `vfmt.indent` — typed on purpose, but one user's editor.
3. VS Code's tab size — sent on every request whether or not you chose it, so
the weakest thing that is still a signal. (`vfmt.lineLength` has no analog
here at all: LSP carries no line-length option.)
4. The built-in defaults: indent 2, width 100.
Each rung applies only where the ones above it say nothing, so a `vfmt.toml`
naming only `indent` still lets `vfmt.lineLength` choose the width. Changes
take effect on the next format — no reload — and out-of-range or wrong-typed
values are ignored rather than half-honoured.
## Rainbow begin/end
+6
View File
@@ -53,6 +53,12 @@ function activate(context) {
// everything single-file (docs/features/vfmt-server/README.md).
const clientOptions = {
documentSelector: LANGUAGES.map((language) => ({ language })),
// Push the whole `vfmt` section to the server as
// `workspace/didChangeConfiguration` — once when the client initializes
// and again on every change. The server reads `vfmt.lineLength`,
// `vfmt.indent` and `vfmt.exclude` from it and ignores the rest
// (docs/features/editor-settings/README.md).
synchronize: { configurationSection: 'vfmt' },
};
client = new LanguageClient('vfmt', 'vfmt', serverOptions, clientOptions);
+28
View File
@@ -69,6 +69,34 @@
"type": "boolean",
"default": true,
"description": "Colour each nesting level of begin/end and fork/join a different colour, using the theme's bracket-pair colours. Takes effect immediately."
},
"vfmt.lineLength": {
"type": [
"number",
"null"
],
"default": null,
"minimum": 40,
"maximum": 400,
"markdownDescription": "Maximum line width, the same as `line-length` in a `vfmt.toml`. A `vfmt.toml` in the project wins over this; leave it unset to use the built-in 100."
},
"vfmt.indent": {
"type": [
"number",
"null"
],
"default": null,
"minimum": 1,
"maximum": 8,
"markdownDescription": "Indent width in spaces, the same as `indent` in a `vfmt.toml`. A `vfmt.toml` in the project wins over this; leave it unset to use the editor's tab size."
},
"vfmt.exclude": {
"type": "array",
"items": {
"type": "string"
},
"default": [],
"markdownDescription": "Extra path patterns to keep out of the workspace index, the same as `exclude` in a `vfmt.toml`. These are **added to** the project's own excludes, never replacing them."
}
}
}
+35
View File
@@ -82,6 +82,25 @@ server.stdin.end(
params: { textDocument: { uri, languageId: 'systemverilog', version: 1, text: SOURCE } },
}),
frame({ jsonrpc: '2.0', id: 3, method: 'vfmt/scopePairs', params: { textDocument: { uri } } }),
// The settings push, in exactly the shape `synchronize.configurationSection:
// 'vfmt'` produces — the whole section, defaults included.
frame({
jsonrpc: '2.0',
method: 'workspace/didChangeConfiguration',
params: {
settings: {
vfmt: { serverPath: 'vfmt-server', rainbowBeginEnd: true, lineLength: null, indent: 4, exclude: [] },
},
},
}),
// Formatting asks for a 2-space tab: the pushed `indent` must win, which
// is rung 2 of the precedence ladder beating rung 3, over the wire.
frame({
jsonrpc: '2.0',
id: 4,
method: 'textDocument/formatting',
params: { textDocument: { uri }, options: { tabSize: 2, insertSpaces: true } },
}),
frame({ jsonrpc: '2.0', id: 2, method: 'shutdown', params: null }),
frame({ jsonrpc: '2.0', method: 'exit', params: null }),
]),
@@ -135,6 +154,22 @@ server.on('close', (code) => {
}
}
// The settings the extension pushes actually reach the formatter.
const formatting = messages.find((m) => m.id === 4);
if (!formatting) fail('no textDocument/formatting response');
if (formatting.error) fail(`formatting failed: ${JSON.stringify(formatting.error)}`);
const edits = formatting.result;
if (!Array.isArray(edits) || edits.length !== 1) {
fail(`expected one edit re-indenting the buffer, got ${JSON.stringify(edits)}`);
}
const indented = edits[0].newText;
if (!indented.includes('\n wire a;')) {
fail(`pushed vfmt.indent=4 was not honoured over tabSize=2:\n${indented}`);
}
if (indented.includes('\n wire a;')) {
fail(`the editor tab size won over the pushed setting:\n${indented}`);
}
const shutdown = messages.find((m) => m.id === 2);
if (!shutdown) fail('no shutdown response');
if (shutdown.error) fail(`shutdown failed: ${JSON.stringify(shutdown.error)}`);