fix: make lsp formatting match formatter

This commit is contained in:
Dandaedre 2026-09-30 00:01:38 +02:00
parent 62d99e3015
commit b42ac6f221
Signed by: Dandaedre
GPG Key ID: 440C6592E8A26D99
7 changed files with 130 additions and 14 deletions

View File

@ -10,8 +10,8 @@ use tower_lsp_server::{
CodeAction, CodeActionKind, CodeActionOptions, CodeActionOrCommand, CodeActionParams,
CodeActionProviderCapability, CodeActionResponse, Diagnostic, DiagnosticSeverity,
DidChangeConfigurationParams, DidChangeTextDocumentParams, DidCloseTextDocumentParams,
DidOpenTextDocumentParams, DocumentChanges, InitializeParams, InitializeResult,
InitializedParams, MessageType, NumberOrString, OneOf,
DidOpenTextDocumentParams, DocumentChanges, DocumentFormattingParams, InitializeParams,
InitializeResult, InitializedParams, MessageType, NumberOrString, OneOf,
OptionalVersionedTextDocumentIdentifier, Position, Range, ServerCapabilities, ServerInfo,
TextDocumentEdit, TextDocumentSyncCapability, TextDocumentSyncKind,
TextEdit as LspTextEdit, Uri, WorkspaceEdit,
@ -250,6 +250,19 @@ fn replacement_code_actions(
.collect()
}
fn formatting_edits(config: &Config, source: &str) -> Result<Vec<LspTextEdit>, PositionError> {
let index = LineIndex::new(source);
plan_replacements(config, source)
.into_iter()
.map(|edit| {
Ok(LspTextEdit::new(
index.range(edit.byte_span)?,
edit.replacement,
))
})
.collect()
}
fn ranges_overlap(left: &Range, right: &Range) -> bool {
left.start <= right.end && right.start <= left.end
}
@ -472,6 +485,7 @@ impl LanguageServer for LspBackend {
..CodeActionOptions::default()
},
)),
document_formatting_provider: Some(OneOf::Left(true)),
..ServerCapabilities::default()
},
offset_encoding: None,
@ -570,6 +584,20 @@ impl LanguageServer for LspBackend {
.map_err(|error| JsonError::invalid_params(error.to_string()))?;
Ok(Some(actions))
}
async fn formatting(
&self,
params: DocumentFormattingParams,
) -> JsonResult<Option<Vec<LspTextEdit>>> {
let uri = params.text_document.uri;
let Some(snapshot) = self.documents.read().await.get(&uri) else {
return Ok(None);
};
let config = self.runtime.read().await.config.clone();
formatting_edits(&config, &snapshot.text)
.map(Some)
.map_err(|error| JsonError::invalid_params(error.to_string()))
}
}
#[cfg(test)]

View File

@ -44,8 +44,8 @@ The modules within those crates retain deliberately narrow responsibilities:
- `replacement` produces non-overlapping edits and validates/applies arbitrary
edit sets without performing I/O;
- `lsp` indexes open snapshots, runs the compiled detector, converts canonical
finding spans to UTF-16 coordinates, and implements versioned replacement
quick fixes;
finding and replacement spans to UTF-16 coordinates, and implements
versioned quick fixes plus whole-document formatting;
- `model` contains presentation-neutral domain values;
- `error` exposes typed input failures for library consumers;
- `src/bin` contains the detector presentation/exit policy and formatter/LSP
@ -92,7 +92,8 @@ documents in deterministic URI order. The detector is compiled once per
resolved configuration rather than once per edit. File URI paths drive normal
scope applicability; language IDs supply source/prose context for untitled or
extensionless buffers. All findings become diagnostics, while only findings
with core `TextEdit`s become code actions. See
with core `TextEdit`s become code actions. Document formatting calls the same
replacement planner directly and never derives mutations from diagnostics. See
[ADR 0003](decisions/0003-lsp-framework-and-protocol.md) for framework and
protocol choices.

View File

@ -76,3 +76,15 @@ This amendment does not broaden mutation behavior:
The original full-snapshot synchronization, UTF-16 conversion, version checks,
stdio purity, no-write boundary, and stale-action guarantees remain unchanged.
## Amendment: document formatting parity
Milestone 21 adds the standard `textDocument/formatting` capability. The server
plans edits from its current open-document snapshot with the same resolved
configuration and core replacement planner used by `john-slop-fmt`, then
converts only the edit coordinates from UTF-8 bytes to LSP UTF-16 positions.
Formatting remains limited to configured safe ASCII replacements; the server
does not write files, infer formatting from diagnostics, or apply broader
Unicode review findings. Protocol tests compare the result of an actual
formatting request with the standalone formatter contract, including Unicode,
CRLF, no-op, and configuration-reload cases.

View File

@ -3,7 +3,9 @@
Both `john-slop-fmt` and `john-slop-lsp` are operational. The LSP publishes all
applicable configured heuristic findings, including prompt leakage, repeated
transitions, source placeholders, tutorial narration, and typography. Safe
ASCII-replacement findings additionally provide versioned quick fixes.
ASCII-replacement findings additionally provide versioned quick fixes, and the
server implements whole-document formatting with the exact same replacement
planner as `john-slop-fmt`.
Install all three binaries somewhere on `PATH`, then confirm the editor-facing
help is available:
@ -34,9 +36,12 @@ auto-format = false
```
This complete custom language entry makes the repository's `example.txt`
fixtures useful without depending on a built-in plain-text grammar. Use
`:format` to run the formatter. Set `auto-format = true` only if save-time
replacement is wanted.
fixtures useful without depending on a built-in plain-text grammar. It selects
the external `john-slop-fmt` adapter. To exercise formatting through the LSP
instead, omit the `formatter = ...` line; `:format` then requests
`textDocument/formatting` from `john-slop-lsp`. Both routes resolve the same
configuration and produce the same text. Set `auto-format = true` only if
save-time replacement is wanted.
For an existing language, merge John Slop into that language's entry rather
than replacing its useful defaults. For example, Rust should retain
@ -49,6 +54,11 @@ formatter = { command = "john-slop-fmt" }
language-servers = ["rust-analyzer", "john-slop"]
```
When several language servers advertise formatting, retain an explicit Helix
`formatter` or select the intended server interactively; John Slop must not
silently replace language-specific formatting from `rust-analyzer` or another
primary server.
Run `hx --health rust` (or the selected language name) to confirm both binaries
are visible. Helix documents that a formatter reads the buffer from stdin and
writes it to stdout, while an LSP command must be on `PATH`; those are the
@ -91,6 +101,11 @@ commands to inspect server state, move through heuristic diagnostics, and apply
available ASCII quick fixes. The registration shape and `allowlist` follow the
plugin's current upstream documentation.
Clients that expose LSP document formatting can request it directly from John
Slop instead of configuring `formatprg`; both paths use the same replacement
catalog. Keep `formatprg=john-slop-fmt` when the Vim client cannot select one
formatter among multiple attached language servers.
The server uses the same configuration layers as the other binaries. Add
`args = ["--config-name", "editorial"]` to the Helix language-server table, or
append those arguments to the Vim `cmd` list, when an editor-specific named

View File

@ -13,6 +13,9 @@ pub const EDITOR_SETUP: &str = r#"EDITOR SETUP (formatter and heuristic LSP avai
formatter = { command = "john-slop-fmt" }
language-servers = ["john-slop"]
Omit the formatter line to send :format through john-slop-lsp instead;
both routes use the same configured replacement plan.
Vim ~/.vimrc formatter (use gggqG for the whole buffer):
autocmd BufRead,BufNewFile *.txt setfiletype text
autocmd FileType text,markdown,rust setlocal formatprg=john-slop-fmt

View File

@ -517,7 +517,7 @@ package assembly, and Tarpaulin passed; coverage remains 92.34%
## Milestone 21 — LSP formatter parity and Unicode review diagnostics
- [ ] Implement and advertise `textDocument/formatting` in the LSP using the
- [x] Implement and advertise `textDocument/formatting` in the LSP using the
same resolved configuration and core replacement planner as `john-slop-fmt`.
Return deterministic UTF-16 edits against the current editor snapshot, cover
Unicode/CRLF/no-op/custom-config/reload cases, and replace the misleading

View File

@ -54,6 +54,10 @@ impl Harness {
response.result().unwrap()["capabilities"]["textDocumentSync"],
1
);
assert_eq!(
response.result().unwrap()["capabilities"]["documentFormattingProvider"],
true
);
harness.notify("initialized", json!({})).await;
harness
}
@ -255,6 +259,28 @@ async fn lifecycle_versions_unicode_quick_fixes_and_formatter_equivalence() {
json!({"line": 0, "character": 2})
);
let formatting = harness
.request(
"textDocument/formatting",
json!({
"textDocument": { "uri": uri },
"options": { "tabSize": 4, "insertSpaces": true }
}),
2,
)
.await;
let formatting_edits = formatting.result().unwrap().as_array().unwrap();
assert_eq!(formatting_edits.len(), 2);
let mut formatted = source.to_owned();
for edit in formatting_edits.iter().rev() {
let start = utf16_position_to_byte(source, &edit["range"]["start"]);
let end = utf16_position_to_byte(source, &edit["range"]["end"]);
formatted.replace_range(start..end, edit["newText"].as_str().unwrap());
}
let formatter_output =
apply_replacements(source, &plan_replacements(&Config::embedded(), source)).unwrap();
assert_eq!(formatted, formatter_output);
let response = harness
.request(
"textDocument/codeAction",
@ -266,7 +292,7 @@ async fn lifecycle_versions_unicode_quick_fixes_and_formatter_equivalence() {
},
"context": { "diagnostics": published["diagnostics"] }
}),
2,
3,
)
.await;
let actions = response.result().unwrap().as_array().unwrap();
@ -285,8 +311,6 @@ async fn lifecycle_versions_unicode_quick_fixes_and_formatter_equivalence() {
.collect::<Vec<_>>();
edits.sort_by_key(|edit| edit.byte_span.start);
let lsp_output = apply_replacements(source, &edits).unwrap();
let formatter_output =
apply_replacements(source, &plan_replacements(&Config::embedded(), source)).unwrap();
assert_eq!(lsp_output, formatter_output);
harness
@ -312,7 +336,7 @@ async fn lifecycle_versions_unicode_quick_fixes_and_formatter_equivalence() {
"range": { "start": { "line": 0, "character": 0 }, "end": { "line": 0, "character": 1 } },
"context": { "diagnostics": published["diagnostics"] }
}),
3,
4,
)
.await;
assert_eq!(stale.error().unwrap().code, ErrorCode::InvalidParams);
@ -358,6 +382,24 @@ enabled = false
.collect::<std::collections::HashMap<_, _>>();
assert!(by_uri[first]["diagnostics"].as_array().unwrap().is_empty());
assert_eq!(by_uri[second]["diagnostics"].as_array().unwrap().len(), 1);
let initially_disabled_format = harness
.request(
"textDocument/formatting",
json!({
"textDocument": { "uri": first },
"options": { "tabSize": 4, "insertSpaces": true }
}),
30,
)
.await;
assert!(
initially_disabled_format
.result()
.unwrap()
.as_array()
.unwrap()
.is_empty()
);
fs::write(
harness.explicit_path(),
@ -391,6 +433,21 @@ enabled = true
refreshed[second]["diagnostics"].as_array().unwrap().len(),
1
);
let reloaded_format = harness
.request(
"textDocument/formatting",
json!({
"textDocument": { "uri": first },
"options": { "tabSize": 4, "insertSpaces": true }
}),
31,
)
.await;
assert_eq!(
reloaded_format.result().unwrap()[0]["newText"],
"-",
"formatting must use the reloaded replacement configuration"
);
fs::write(harness.explicit_path(), "schema_version = 999\n").unwrap();
let failed_reload = Request::build("workspace/didChangeConfiguration")