LSP §9b: willSaveWaitUntil — protocol-native format-on-save

textDocument/willSaveWaitUntil is advertised and served, gated on a new
lucisv.formatOnSave setting that defaults to off (a server that formats
uninvited fights the editor's own format-on-save and doubles up); the
decline is one comparison, before any buffer lookup. When on, the hook
is textDocument/formatting with a different trigger: the same engine,
the same all-or-nothing verified-output contract, settings resolved by
the new format::settings_without_editor_options — the ladder minus the
tabSize rung the protocol simply does not carry here, with the honest
consequence (save-format can differ from manual format without a
lucisv.toml) documented in the README, the VS Code setting description
and the nvim README. Every save reason formats; refusals are shown per
save, on purpose.

18 tests added across settings/format/server/e2e, including QA's
executable proofs of the tab-size gap and its lucisv.toml resolution, a
no-reindex/no-generation-bump guard for the new setting, and an
idempotency round-trip through a real didChange. QA also fixed the
stale 'not advertised' feature list in editors/nvim/README.md and
sharpened the config-warning dedup claim to what the code does (once
per buffer state) — reworded in the README, pinned by test.

docs/features/will-save-wait-until/README.md

Co-Authored-By: Claude Fable 5 <[email protected]>
This commit is contained in:
lucioandClaude Fable 5 committed 2026-08-26 12:21:00 -07:00
1 parent c2ea1a11f6
commit 80b9afdfe3
11 files changed
+939 -11

No files matched your search

+39
View File
@@ -60,6 +60,20 @@ pub fn settings_for(
Settings { config: config_from(&file, client, options), problem }
}
/// Resolve the settings governing a buffer for a request that carries no
/// `FormattingOptions`.
///
/// `textDocument/willSaveWaitUntil` has no options field at all — the protocol
/// simply does not carry one there. So the ladder `settings_for` documents
/// runs with rung 3 missing, which is the same thing `indent_width` does for a
/// lint fix: `lucisv.toml` > the pushed `lucisv.*` settings > the built-in
/// default. Spelled as hard tabs and a zero width because `config_from` takes
/// neither, so nothing is guessed on the user's behalf.
pub fn settings_without_editor_options(doc: &Document, client: &ClientSettings) -> Settings {
let none = FormattingOptions { tab_size: 0, insert_spaces: false, ..Default::default() };
settings_for(doc, client, &none)
}
/// Format a buffer.
///
/// `Ok(None)` means "nothing to do" — the buffer is already formatted, and an
@@ -495,6 +509,31 @@ mod tests {
assert_eq!(indent_width(None, &none()), Config::default().indent_width, "then default");
}
#[test]
fn a_request_without_options_climbs_the_same_ladder_without_rung_3() {
// What `willSaveWaitUntil` resolves to: the protocol sends no
// `FormattingOptions` with it, so the editor's tab size is simply not
// one of the inputs.
let tree = Tree::new("indent = 4\n");
let (ws, uri) = tree.document("module m;\nwire a;\nendmodule\n");
let doc = ws.document(&uri).expect("open");
let settings = settings_without_editor_options(doc, &pushed(None, Some(8)));
assert_eq!(settings.config.indent_width, 4, "the config still wins");
assert_eq!(settings.problem, None);
// With no config, the pushed setting is the highest rung there is.
let (ws, uri) = document("module m;\nwire a;\nendmodule\n");
let doc = ws.document(&uri).expect("open");
let settings = settings_without_editor_options(doc, &pushed(Some(60), Some(8)));
assert_eq!(settings.config.indent_width, 8);
assert_eq!(settings.config.max_width, 60);
// And with nothing pushed either, the built-in default — never a
// guess from an option that was not sent.
let settings = settings_without_editor_options(doc, &none());
assert_eq!(settings.config.indent_width, Config::default().indent_width);
assert_eq!(settings.config.max_width, Config::default().max_width);
}
#[test]
fn a_broken_config_leaves_the_pushed_settings_in_charge() {
// Nothing from a broken `lucisv.toml` is used, so the next rung down is
+18 -1
View File
@@ -95,8 +95,14 @@ fn capabilities() -> ServerCapabilities {
text_document_sync: Some(TextDocumentSyncCapability::Options(TextDocumentSyncOptions {
open_close: Some(true),
change: Some(TextDocumentSyncKind::INCREMENTAL),
// The plain `willSave` notification carries nothing this server
// can act on, so it is left unadvertised; `willSaveWaitUntil` is
// the format-on-save hook, for the editors that have no
// format-on-save of their own. It answers `null` unless
// `lucisv.formatOnSave` is on — see
// `docs/features/will-save-wait-until/README.md`.
will_save: None,
will_save_wait_until: None,
will_save_wait_until: Some(true),
save: Some(TextDocumentSyncSaveOptions::SaveOptions(SaveOptions {
include_text: Some(false),
})),
@@ -322,6 +328,17 @@ mod tests {
assert!(caps.diagnostic_provider.is_some());
}
#[test]
fn the_sync_options_ask_for_the_save_hook_and_not_the_notification() {
let Some(TextDocumentSyncCapability::Options(options)) = capabilities().text_document_sync
else {
panic!("the options form, not a bare kind");
};
assert_eq!(options.change, Some(TextDocumentSyncKind::INCREMENTAL));
assert_eq!(options.will_save_wait_until, Some(true), "the format-on-save hook is answered");
assert_eq!(options.will_save, None, "the plain notification has nothing for us");
}
#[test]
fn the_diagnostic_options_say_what_this_server_actually_does() {
let Some(DiagnosticServerCapabilities::Options(options)) =
+346 -5
View File
@@ -21,7 +21,7 @@ use lsp_types::request::{
FoldingRangeRequest, Formatting, GotoDefinition, HoverRequest, InlayHintRequest,
InlineCompletionRequest, PrepareRenameRequest, RangeFormatting, References, RegisterCapability,
Rename, Request as _, SelectionRangeRequest, SemanticTokensFullRequest, SignatureHelpRequest,
UnregisterCapability, WorkspaceDiagnosticRequest, WorkspaceSymbolRequest,
UnregisterCapability, WillSaveWaitUntil, WorkspaceDiagnosticRequest, WorkspaceSymbolRequest,
};
use lsp_types::{
ApplyWorkspaceEditParams, ApplyWorkspaceEditResponse, CallHierarchyIncomingCallsParams,
@@ -38,10 +38,10 @@ use lsp_types::{
RelatedFullDocumentDiagnosticReport, RelatedUnchangedDocumentDiagnosticReport, RenameParams,
SelectionRangeParams, SemanticTokensParams, SemanticTokensResult, ShowMessageParams,
SignatureHelpParams, TextDocumentPositionParams, UnchangedDocumentDiagnosticReport,
UnregistrationParams, Uri, WorkspaceDiagnosticParams, WorkspaceDiagnosticReport,
WorkspaceDiagnosticReportResult, WorkspaceDocumentDiagnosticReport, WorkspaceEdit,
WorkspaceFullDocumentDiagnosticReport, WorkspaceSymbolParams, WorkspaceSymbolResponse,
WorkspaceUnchangedDocumentDiagnosticReport,
UnregistrationParams, Uri, WillSaveTextDocumentParams, WorkspaceDiagnosticParams,
WorkspaceDiagnosticReport, WorkspaceDiagnosticReportResult, WorkspaceDocumentDiagnosticReport,
WorkspaceEdit, WorkspaceFullDocumentDiagnosticReport, WorkspaceSymbolParams,
WorkspaceSymbolResponse, WorkspaceUnchangedDocumentDiagnosticReport,
};
use serde::de::DeserializeOwned;
use serde_json::Value;
@@ -158,6 +158,10 @@ impl Server {
let result = match method.as_str() {
Formatting::METHOD => decode(request).and_then(|p| self.formatting(p)),
RangeFormatting::METHOD => decode(request).and_then(|p| self.range_formatting(p)),
// Format-on-save, protocol-native: the client asks before it
// writes, and applies whatever comes back. Opt-in, and the decline
// is the cheap path — see `will_save_wait_until`.
WillSaveWaitUntil::METHOD => decode(request).and_then(|p| self.will_save_wait_until(p)),
HoverRequest::METHOD => decode(request).and_then(|p: HoverParams| {
let at = p.text_document_position_params;
let (uri, position) = (at.text_document.uri, at.position);
@@ -427,6 +431,40 @@ impl Server {
self.edits(result)
}
/// `textDocument/willSaveWaitUntil` — format the buffer the client is
/// about to write, for the editors that have no format-on-save of their
/// own.
///
/// `null` unless `lucisv.formatOnSave` is on. A capable client sends this
/// before *every* save, so declining has to be the cheap path — and an
/// editor that already formats on save (VS Code's `editor.formatOnSave`,
/// which runs `textDocument/formatting`) would otherwise format twice.
///
/// When it is on, this is `textDocument/formatting` with a different
/// trigger: the same engine, the same settings ladder, the same
/// all-or-nothing contract — one whole-document edit built from verified
/// output, or no edit at all. The save's `reason` is not read: manual,
/// after-delay and focus-out are all saves, and the user asked for their
/// saves to be formatted. The text is the buffer the server holds, because
/// the request carries none and the client has not written yet.
fn will_save_wait_until(
&mut self,
params: WillSaveTextDocumentParams,
) -> Result<Value, Failure> {
if !self.workspace.client_settings().format_on_save {
return Ok(Value::Null);
}
let uri = params.text_document.uri;
let Some(doc) = self.workspace.document(&uri) else { return Ok(Value::Null) };
// No `FormattingOptions` on this request — the protocol carries none —
// so the ladder runs without its `tabSize` rung.
let settings =
format::settings_without_editor_options(doc, self.workspace.client_settings());
let result = format::formatting(doc, &settings.config);
self.warn_about_config(&uri, settings.problem);
self.edits(result)
}
/// Say once per change of a file that its `lucisv.toml` could not be read.
fn warn_about_config(&mut self, uri: &Uri, problem: Option<String>) {
if let Some(problem) = problem {
@@ -1967,4 +2005,307 @@ mod tests {
assert_eq!(published.len(), 1);
assert!(published[0].diagnostics.is_empty(), "{published:#?}");
}
// ------------------------------------------------------------------
// `textDocument/willSaveWaitUntil`
// ------------------------------------------------------------------
/// The `lucisv.formatOnSave` push a client makes, on or off.
fn format_on_save(on: bool) -> Value {
serde_json::json!({ "settings": { "lucisv": { "formatOnSave": on } } })
}
/// One `willSaveWaitUntil` for a buffer, for the reason given (1 = manual,
/// 2 = after delay, 3 = focus out).
fn will_save(session: &mut Session, uri: &Uri, reason: u8) -> Value {
session.result(
WillSaveWaitUntil::METHOD,
serde_json::json!({ "textDocument": { "uri": uri }, "reason": reason }),
)
}
/// What `textDocument/formatting` answers for the same buffer, asking for
/// the 2-space tab an editor defaults to — which is also the built-in
/// indent, so the two paths resolve to the same settings.
fn formatting_result(session: &mut Session, uri: &Uri) -> Value {
session.result(
Formatting::METHOD,
serde_json::json!({
"textDocument": { "uri": uri },
"options": { "tabSize": 2, "insertSpaces": true },
}),
)
}
#[test]
fn the_save_hook_declines_until_format_on_save_is_pushed() {
let tree = Tree::new("willsaveoff");
let mut session = Session::new(vec![tree.path.clone()], false);
let uri = session.open(&tree.path.join("m.sv"), "module m;\nwire a;\nendmodule\n");
// The default: a client that never pushed the setting is answered
// `null`, and told nothing at all.
assert_eq!(will_save(&mut session, &uri, 1), Value::Null, "off by default");
assert!(session.shown().is_empty(), "a decline is silent");
// Pushed on, mid-session, with no restart.
session.notify(DidChangeConfiguration::METHOD, format_on_save(true));
let edits = will_save(&mut session, &uri, 1);
assert_eq!(edits[0]["newText"], "module m;\n wire a;\nendmodule\n", "{edits:#?}");
// And off again: the hook goes back to declining.
session.notify(DidChangeConfiguration::METHOD, format_on_save(false));
assert_eq!(will_save(&mut session, &uri, 1), Value::Null, "turned back off");
}
#[test]
fn toggling_format_on_save_neither_rescans_nor_bumps_the_generation() {
// QA (2026-08-26): `lucisv.formatOnSave` is read afresh by every save,
// like `indent`/`lineLength` already are by every format — it must not
// cost a re-walk of the workspace, and (since a rescan is what bumps
// it) must not move the generation counter a pull-diagnostics client's
// `resultId` is stamped with either. `only_an_exclude_change_asks_for_a_rescan`
// (state.rs) pins the same thing one layer down; this pins it through
// the real notification handler.
let tree = Tree::new("willsavenoreindex");
tree.package("kept.sv", "kept_pkg");
let mut session = Session::new(vec![tree.path.clone()], false);
let before = session.server.generation;
session.notify(DidChangeConfiguration::METHOD, format_on_save(true));
assert_eq!(session.server.generation, before, "turning it on moved nothing");
session.notify(DidChangeConfiguration::METHOD, format_on_save(false));
assert_eq!(session.server.generation, before, "turning it off moved nothing either");
}
#[test]
fn the_save_hook_answers_exactly_what_the_formatting_request_answers() {
// The whole contract: this is `textDocument/formatting` with a
// different trigger, so the bytes must be identical — not merely
// equivalent.
let tree = Tree::new("willsavesame");
let mut session = Session::new(vec![tree.path.clone()], false);
let uri =
session.open(&tree.path.join("m.sv"), "module m;\nwire a;\n wire b;\nendmodule\n");
session.notify(DidChangeConfiguration::METHOD, format_on_save(true));
assert_eq!(will_save(&mut session, &uri, 1), formatting_result(&mut session, &uri));
}
#[test]
fn every_save_reason_is_a_save() {
// Manual, after-delay and focus-out all format: the user asked for
// their saves to be formatted, and all three write the file.
let tree = Tree::new("willsavereason");
let mut session = Session::new(vec![tree.path.clone()], false);
let uri = session.open(&tree.path.join("m.sv"), "module m;\nwire a;\nendmodule\n");
session.notify(DidChangeConfiguration::METHOD, format_on_save(true));
for reason in [1, 2, 3] {
let edits = will_save(&mut session, &uri, reason);
assert_eq!(
edits[0]["newText"], "module m;\n wire a;\nendmodule\n",
"reason {reason}: {edits:#?}"
);
}
}
#[test]
fn the_save_hook_answers_null_for_a_buffer_it_does_not_hold() {
// The request carries no text — the client has not written yet — so a
// buffer the server never saw is one it cannot format.
let tree = Tree::new("willsaveclosed");
let mut session = Session::new(vec![tree.path.clone()], false);
session.notify(DidChangeConfiguration::METHOD, format_on_save(true));
let uri = path_to_uri(&tree.path.join("never-opened.sv")).expect("uri");
assert_eq!(will_save(&mut session, &uri, 1), Value::Null);
assert!(session.shown().is_empty(), "and nothing is said about it");
}
#[test]
fn an_already_formatted_buffer_is_saved_with_no_edits() {
// The same `[]` the formatting request gives for `Ok(None)`: an edit
// that changes nothing still moves the cursor in some editors.
let tree = Tree::new("willsaveclean");
let mut session = Session::new(vec![tree.path.clone()], false);
let uri = session.open(&tree.path.join("m.sv"), "module m;\n wire a;\nendmodule\n");
session.notify(DidChangeConfiguration::METHOD, format_on_save(true));
let edits = will_save(&mut session, &uri, 1);
assert_eq!(edits, serde_json::json!([]), "{edits:#?}");
assert_eq!(edits, formatting_result(&mut session, &uri), "the same as the request's");
}
#[test]
fn a_buffer_the_formatter_refuses_is_saved_unedited_and_the_reason_is_shown() {
// CLAUDE.md invariant #1 on the save path: no partial output, ever.
// The message repeats per save on purpose — a save the user asked to
// be formatted, that was not, is worth saying every time it happens.
let tree = Tree::new("willsavebroken");
let mut session = Session::new(vec![tree.path.clone()], false);
let uri = session.open(&tree.path.join("m.sv"), "module m;\n wire ;\nendmodule\n");
session.notify(DidChangeConfiguration::METHOD, format_on_save(true));
let _ = session.drain();
for save in 1..=2 {
let edits = will_save(&mut session, &uri, 1);
assert_eq!(edits, serde_json::json!([]), "save {save}: no edit at all");
let shown = session.shown();
assert_eq!(shown.len(), 1, "save {save}: {shown:#?}");
assert_eq!(shown[0].0, MessageType::ERROR);
assert!(shown[0].1.starts_with("lucisv: cannot format — "), "{}", shown[0].1);
}
}
#[test]
fn applying_the_save_hooks_edit_leaves_the_next_save_nothing_to_do() {
// The formatter's own idempotency, asserted through this path: the
// buffer the client writes is a fixed point, so a save right after a
// save cannot keep rewriting the file.
let tree = Tree::new("willsaveidempotent");
let mut session = Session::new(vec![tree.path.clone()], false);
let uri = session.open(
&tree.path.join("m.sv"),
"module m;\nwire a;\n assign a = 1;\nendmodule\n",
);
session.notify(DidChangeConfiguration::METHOD, format_on_save(true));
let edits = will_save(&mut session, &uri, 1);
let formatted = edits[0]["newText"].as_str().expect("newText").to_string();
// The client applies the edit and writes; the buffer it holds is what
// the next save asks about.
change(&mut session, &uri, 2, serde_json::json!([{ "text": formatted.clone() }]));
assert_eq!(buffer(&session, &uri), formatted);
assert_eq!(will_save(&mut session, &uri, 1), serde_json::json!([]), "a fixed point");
}
/// What `textDocument/formatting` answers for the given `tabSize`.
fn formatting_with_tab_size(session: &mut Session, uri: &Uri, tab_size: u32) -> Value {
session.result(
Formatting::METHOD,
serde_json::json!({
"textDocument": { "uri": uri },
"options": { "tabSize": tab_size, "insertSpaces": true },
}),
)
}
#[test]
fn the_save_hook_and_a_manual_format_can_legitimately_disagree_on_indent() {
// QA (2026-08-26): the documented gap in Assumptions/Handshakes,
// constructed for real. No `lucisv.toml`, no `lucisv.indent` pushed,
// and an editor whose tab size is 4: a manual format honors rung 3
// (the editor's `tabSize`) and indents 4; the save hook has no rung 3
// to consult at all and falls straight to the built-in default, 2.
let tree = Tree::new("willsavetabgap");
let mut session = Session::new(vec![tree.path.clone()], false);
let uri = session.open(&tree.path.join("m.sv"), "module m;\nwire a;\nendmodule\n");
session.notify(DidChangeConfiguration::METHOD, format_on_save(true));
let manual = formatting_with_tab_size(&mut session, &uri, 4);
assert_eq!(manual[0]["newText"], "module m;\n wire a;\nendmodule\n", "{manual:#?}");
let saved = will_save(&mut session, &uri, 1);
assert_eq!(saved[0]["newText"], "module m;\n wire a;\nendmodule\n", "{saved:#?}");
assert_ne!(manual, saved, "the documented gap is real, not just written down");
}
#[test]
fn a_lucisv_toml_erases_the_tab_size_gap() {
// QA (2026-08-26): with a checked-in config, rung 1 outranks both the
// editor's `tabSize` and the built-in default, so the two paths agree
// exactly again — no `lucisv.toml`, and this would be the previous
// test.
let tree = Tree::new("willsavetabgapclosed");
tree.write("lucisv.toml", "indent = 4\n");
let mut session = Session::new(vec![tree.path.clone()], false);
let uri = session.open(&tree.path.join("m.sv"), "module m;\nwire a;\nendmodule\n");
session.notify(DidChangeConfiguration::METHOD, format_on_save(true));
// A wildly different editor tab size changes nothing: the config wins.
let manual = formatting_with_tab_size(&mut session, &uri, 8);
let saved = will_save(&mut session, &uri, 1);
assert_eq!(manual[0]["newText"], "module m;\n wire a;\nendmodule\n", "{manual:#?}");
assert_eq!(manual, saved, "the config makes the two paths agree exactly");
}
#[test]
fn a_broken_config_still_saves_with_defaults_and_warns_once() {
// QA (2026-08-26): the interaction attack-surface 4 calls out —
// `formatOnSave` on, the buffer itself fine, but `lucisv.toml` broken.
// The save must not be sacrificed to a typo in a file the user is not
// even editing: it formats with the built-in defaults, and the
// warning follows the same per-file-change dedup a broken config
// already gets everywhere else, so a save loop cannot turn it into
// spam the way the formatter-refusal ERROR deliberately can.
//
// The buffer is already at the built-in default (2-space indent), so
// neither save produces an edit and — crucially — neither save is
// followed by the client-applies-the-edit `didChange` that would
// itself re-arm the warning (`set_document` clears
// `config_warnings`). That is what isolates the dedup this test is
// actually about from the unrelated re-arming a *changed* buffer gets.
let tree = Tree::new("willsavebrokenconfig");
tree.write("lucisv.toml", "indent = 4\nbogus = 1\n");
let mut session = Session::new(vec![tree.path.clone()], false);
let uri = session.open(&tree.path.join("m.sv"), "module m;\n wire a;\nendmodule\n");
session.notify(DidChangeConfiguration::METHOD, format_on_save(true));
let _ = session.drain();
let first = will_save(&mut session, &uri, 1);
assert_eq!(first, serde_json::json!([]), "the buffer needed no edit: {first:#?}");
let shown = session.shown();
assert_eq!(shown.len(), 1, "{shown:#?}");
assert_eq!(shown[0].0, MessageType::WARNING);
assert!(shown[0].1.contains("formatting with default settings"), "{}", shown[0].1);
// A second save of the same still-broken config, with nothing having
// changed the buffer in between, says nothing new.
let second = will_save(&mut session, &uri, 1);
assert_eq!(second, serde_json::json!([]), "{second:#?}");
assert!(session.shown().is_empty(), "the warning does not repeat per save");
}
#[test]
fn a_reformatting_save_re_arms_the_broken_config_warning_on_the_very_next_save() {
// QA (2026-08-26) finding, not a fix: `warn_about_config`'s dedup is
// keyed on `set_document`, and `set_document` is exactly what runs
// when the client applies a save hook's edit and the resulting
// `didChange` reaches the server (see
// `applying_the_save_hooks_edit_leaves_the_next_save_nothing_to_do`,
// which does this on purpose to model the real sequence). So "warns
// once" (Assumptions, work log) only holds once the buffer stops
// needing edits — a save that *itself* reformats the buffer re-arms
// the same warning for the very next save, because that save is
// preceded by a `didChange` the dedup treats as a fresh state. Two
// back-to-back saves of a buffer that needs reformatting under a
// broken config warn twice, not once; the third (once the buffer is a
// fixed point and no further `didChange` lands) is finally silent.
// This is consistent with the doc comment on `warn_about_config`
// ("once per change of a file") — it is the *save hook's own* prose
// ("warns once") that does not spell out this edge, and a future
// reader relying on literally one warning per broken config should
// know better.
let tree = Tree::new("willsavebrokenconfigrearm");
tree.write("lucisv.toml", "indent = 4\nbogus = 1\n");
let mut session = Session::new(vec![tree.path.clone()], false);
let uri = session.open(&tree.path.join("m.sv"), "module m;\nwire a;\nendmodule\n");
session.notify(DidChangeConfiguration::METHOD, format_on_save(true));
let _ = session.drain();
let first = will_save(&mut session, &uri, 1);
let formatted = first[0]["newText"].as_str().expect("newText").to_string();
assert_eq!(formatted, "module m;\n wire a;\nendmodule\n", "{first:#?}");
assert_eq!(session.shown().len(), 1, "the first save warns");
// The client applies the edit and writes, exactly as
// `applying_the_save_hooks_edit_leaves_the_next_save_nothing_to_do`
// does — this is what re-arms the dedup.
change(&mut session, &uri, 2, serde_json::json!([{ "text": formatted.clone() }]));
let second = will_save(&mut session, &uri, 1);
assert_eq!(second, serde_json::json!([]), "already formatted: {second:#?}");
assert_eq!(session.shown().len(), 1, "the second save warns again, not zero times");
// No further `didChange` follows a no-op save, so the third finally
// stays quiet — the dedup this test is not disputing.
let third = will_save(&mut session, &uri, 1);
assert_eq!(third, serde_json::json!([]));
assert!(session.shown().is_empty(), "only now does the warning stop repeating");
}
}
+27 -1
View File
@@ -46,6 +46,13 @@ pub struct ClientSettings {
/// Unset means on, which is what the VS Code default declares — see
/// `docs/features/inline-templates/README.md`.
pub inline_templates: Option<bool>,
/// `lucisv.formatOnSave`: whether `textDocument/willSaveWaitUntil` formats
/// the buffer. A plain `bool` rather than an `Option`, because unset and
/// off are the same answer here: an editor with a format-on-save of its
/// own already runs `textDocument/formatting` on save, and a server that
/// also formatted would format twice. See
/// `docs/features/will-save-wait-until/README.md`.
pub format_on_save: bool,
}
/// Read the `lucisv` section out of a `workspace/didChangeConfiguration` payload.
@@ -70,6 +77,10 @@ pub fn from_payload(settings: &Value) -> ClientSettings {
exclude: strings(lucisv.get("exclude")),
filelist: path(lucisv.get("filelist")),
inline_templates: flag(lucisv.get("inlineTemplates")),
// Anything that is not `true` leaves the hook declining, wrong-typed
// values included: the safe direction for a setting that rewrites the
// user's buffer on every save is the one that does nothing.
format_on_save: flag(lucisv.get("formatOnSave")).unwrap_or(false),
}
}
@@ -132,7 +143,8 @@ mod tests {
"indent": indent,
"exclude": exclude,
"filelist": "",
"inlineTemplates": true
"inlineTemplates": true,
"formatOnSave": false
}
})
}
@@ -189,6 +201,20 @@ mod tests {
}
}
#[test]
fn format_on_save_is_off_until_a_client_asks_for_it() {
assert!(settings(json!({ "lucisv": { "formatOnSave": true } })).format_on_save);
assert!(!settings(json!({ "lucisv": { "formatOnSave": false } })).format_on_save);
// Absence is off: the hook runs on every save of every buffer, and a
// server that formatted uninvited would fight the editor's own
// format-on-save.
assert!(!settings(json!({ "lucisv": {} })).format_on_save, "and so is its absence");
for bad in [json!("true"), json!(1), json!(null), json!([true]), json!({ "on": true })] {
let found = settings(json!({ "lucisv": { "formatOnSave": bad } }));
assert!(!found.format_on_save, "formatOnSave {bad} must be ignored");
}
}
#[test]
fn a_populated_payload_is_read_whole() {
let found = settings(vscode_payload(json!(120), json!(4), json!(["vendor", "*_gen.sv"])));
+10
View File
@@ -572,6 +572,16 @@ mod tests {
}),
"widths do not move files"
);
// QA (2026-08-26): `format_on_save` is read afresh by
// `will_save_wait_until` exactly as `indent`/`lineLength` are by
// `formatting` — it must not ask for a rescan either, or every
// `lucisv.formatOnSave` toggle would pay for a full re-walk (and, on
// a client that pulls, bump the diagnostics generation along with
// it).
assert!(
!ws.set_client_settings(ClientSettings { format_on_save: true, ..Default::default() }),
"turning the save hook on does not move files either"
);
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");
+67
View File
@@ -721,6 +721,73 @@ fn pushed_settings_reach_the_formatter_and_can_change_mid_session() {
let _ = std::fs::remove_dir_all(&dir);
}
#[test]
fn the_save_hook_is_advertised_and_formats_only_when_it_is_asked_to() {
// The one thing a unit test cannot check: that the capability really
// reaches the wire, and that a client's `formatOnSave` push really turns
// the hook on for the requests that follow it.
let dir = temp_dir("willsave");
let file = dir.join("m.sv");
std::fs::write(&file, UNINDENTED).expect("write");
let root = format!("file://{}", dir.display());
let uri = format!("file://{}", file.display());
let will_save = |id: u32| {
frame(&format!(
r#"{{"jsonrpc":"2.0","id":{id},"method":"textDocument/willSaveWaitUntil","params":{{"textDocument":{{"uri":"{uri}"}},"reason":1}}}}"#
))
};
let formatted = "module settings_me;\n wire a;\nendmodule\n";
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: the hook declines, so a client that never opted in
// saves exactly what it was going to save.
will_save(2),
frame(r#"{"jsonrpc":"2.0","method":"workspace/didChangeConfiguration","params":{"settings":{"lucisv":{"formatOnSave":true}}}}"#),
will_save(3),
// The client applies the edit and writes; the buffer it now holds is
// what the next save asks about.
frame(&format!(
r#"{{"jsonrpc":"2.0","method":"textDocument/didChange","params":{{"textDocument":{{"uri":"{uri}","version":2}},"contentChanges":[{{"text":{}}}]}}}}"#,
serde_json::to_string(formatted).expect("json")
)),
will_save(4),
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 initialize = messages.iter().find(|m| m["id"] == 1).expect("initialize response");
let sync = &initialize["result"]["capabilities"]["textDocumentSync"];
assert_eq!(sync["willSaveWaitUntil"], true, "the hook is advertised: {sync:#?}");
assert!(sync.get("willSave").is_none(), "the notification is not: {sync:#?}");
let declined = messages.iter().find(|m| m["id"] == 2).expect("a response to the first save");
assert!(declined["result"].is_null(), "off by default: {declined:#?}");
assert_eq!(new_text(&messages, 3), formatted, "the push turns it on for the next save");
let again = messages.iter().find(|m| m["id"] == 4).expect("a response to the third save");
assert_eq!(
again["result"].as_array().expect("an array of edits").len(),
0,
"a formatted buffer saves with no edits at all: {again:#?}"
);
assert!(
!messages.iter().any(|m| m["method"] == "window/showMessage"),
"nothing went wrong, so nothing was said: {messages:#?}"
);
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