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

+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");
}
}