// Author: Guoliang Chen, a Senior Digital Design Engineer //! `textDocument/formatting`, `textDocument/rangeFormatting` and //! `textDocument/rangesFormatting`. //! //! The formatter's contract is all-or-nothing (CLAUDE.md invariant #1), and //! these handlers keep it: either one whole-document edit built from verified //! output, or no edit at all and an error for the user to read. That holds for //! the range requests too — their output is verified over the whole buffer, //! and what makes a request a *range* format is which constructs it laid out, //! not which bytes it was allowed to replace. The range requests go through //! `format_selection`: the smallest run of sibling items or statements the //! selection covers, laid out at the indentation it was written at — see //! `docs/features/selection-formatting/README.md`. use std::path::Path; use lsp_types::{FormattingOptions, Range, TextDocumentIdentifier, TextEdit}; use lucisv_core::config::{Discovery, FileConfig}; use vlog_formatter::{ format_selection, format_source, style, Alignment, Config, LineRanges, ListIndent, Placement, PortLists, Style, StyleOverrides, }; use crate::settings::ClientSettings; use crate::state::Document; /// Indent widths a client may ask for. The same 1..8 range `lucisv.toml`'s own /// `indent` key allows, so the two agree. const INDENT_RANGE: std::ops::RangeInclusive = 1..=8; /// What to format a buffer with, and the config problem to tell the user /// about. The two are separate because a broken `lucisv.toml` must not stop the /// buffer from being formatted. pub struct Settings { /// The settings to format with — the fallback defaults when `problem` is /// set. pub config: Config, /// The `lucisv.toml` error governing this buffer, if there is one. pub problem: Option, } /// Resolve the settings governing a buffer. /// /// Precedence, highest first: /// /// 1. **`lucisv.toml`** — a checked-in config is the project speaking, and it /// must stay authoritative or format-on-save would disagree with CI's /// `lucisv --check`. That divergence is the exact thing lifting the config /// into `lucisv_core` exists to remove. /// 2. **The client's `lucisv.*` 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 `lucisv.toml` and no `lucisv.*` settings behaves exactly as it did /// before either existed. /// /// **The style** (`[format] style`, `lucisv.format.style`) climbs rungs 1, 2 /// and 4 first, and supplies the indent and width the other keys then /// overwrite. A style that was chosen on rung 1 or 2 also outranks rung 3: /// `tabSize` is sent whether or not anyone chose it, and the editor's own /// default of 4 silently undoing `google`'s 2 is not what choosing a style /// asked for. With no style chosen — or `lucisv`, which is what VS Code sends /// when nobody touched the drop-down, and which means exactly "what lucisv /// always did", or `auto`, which chooses a layout but no size — rung 3 /// behaves exactly as it always has. pub fn settings_for( doc: &Document, client: &ClientSettings, options: &FormattingOptions, ) -> Settings { let (file, problem) = discover(doc.path.as_deref()); 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 /// edit that changes nothing still moves the cursor in some editors. `Err` /// carries the formatter's own message; the caller surfaces it, and must not /// invent an edit from it. pub fn formatting(doc: &Document, config: &Config) -> Result, String> { let formatted = format_source(&doc.text, config).map_err(|e| e.to_string())?; Ok(whole_document_edit(doc, formatted)) } /// The one edit that turns `doc` into `formatted`, or none when they are /// already the same text. pub fn whole_document_edit(doc: &Document, formatted: String) -> Option { if formatted == doc.text { return None; } Some(TextEdit { range: doc.positions().whole_document(), new_text: formatted }) } /// `textDocument/rangesFormatting`, the LSP 3.18 multi-range request. /// /// Spelled out here because `lsp-types` 0.97 predates it — the same reason /// `pairs::ScopePairsParams` is hand-rolled. See /// `docs/features/lsp-318-extras/README.md`. pub const RANGES_FORMATTING: &str = "textDocument/rangesFormatting"; /// `textDocument/rangesFormatting` params: one document, `n` ranges, one set /// of options. #[derive(serde::Deserialize)] #[serde(rename_all = "camelCase")] pub struct RangesFormattingParams { pub text_document: TextDocumentIdentifier, pub ranges: Vec, pub options: FormattingOptions, } /// Format the constructs a selection reaches, and nothing else. /// /// The one-range case of [`ranges_formatting`], which is where the whole /// answer lives — an `n`-range request is this request with `n` line spans. pub fn range_formatting( doc: &Document, config: &Config, range: Range, ) -> Result, String> { ranges_formatting(doc, config, std::slice::from_ref(&range)) } /// Format the constructs any of several selections reach, and nothing else. /// /// The ranges are a *set*: they are sorted and merged by `LineRanges::new` /// before the engine sees them, so overlapping, adjacent, repeated and /// unsorted input from the client all reach the same answer. Each merged span /// selects its own target (targets that overlap are re-selected from the hull /// of their spans), but no range is formatted on its own — one /// `format_selection` call lays out and verifies them all, which is what keeps /// the all-or-nothing contract (CLAUDE.md invariant #1) whole rather than /// making it a promise per range. /// /// The reply is still one whole-document edit: the engine's contract is /// all-or-nothing over the file, and a partial run's output differs from the /// buffer only where it decided to differ. An empty range list is not an /// error — it is an ask for nothing, answered with no edit. pub fn ranges_formatting( doc: &Document, config: &Config, ranges: &[Range], ) -> Result, String> { if ranges.is_empty() { return Ok(None); } let lines = LineRanges::new(ranges.iter().copied().map(lines_of))?; let formatted = format_selection(&doc.text, config, &lines).map_err(|e| e.to_string())?; if formatted == doc.text { return Ok(None); } Ok(Some(TextEdit { range: doc.positions().whole_document(), new_text: formatted })) } /// The 1-based inclusive line span an LSP range names. /// /// The protocol's `Range` is a half-open span of UTF-16 positions; the engine /// wants lines, so only the line numbers survive the conversion — which /// sidesteps the UTF-16 column question rather than solving it again. An end /// position at character 0 still names its line — an editor's "select these /// three lines" ends at the start of the fourth — so a range that stops at a /// line's very beginning does not drag that line in unless it is also where /// the range started. /// /// One conversion, shared by both range requests: a second spelling of this /// rule would be a second thing to get wrong. fn lines_of(range: Range) -> (u32, u32) { let first = range.start.line.saturating_add(1); // An end at character 0 of a later line is the start of that line, not // any of its content. let ends_before_its_line = range.end.character == 0 && range.end.line > range.start.line; let last = if ends_before_its_line { range.end.line } else { range.end.line.saturating_add(1) }; (first, last.max(first)) } /// The indent width governing a buffer, for a lint fix that has to write /// spaces where a tab was. /// /// A `textDocument/codeAction` request carries no `FormattingOptions`, so there /// is no client `tabSize` to consider here — the precedence is the same ladder /// `settings_for` documents with rung 3 missing: `lucisv.toml` > `lucisv.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>, client: &ClientSettings) -> usize { let (file, _problem) = discover(path); file.indent .or(client.indent) .unwrap_or(chosen_style(&file, client).unwrap_or(style::LUCISV).indent) } /// The preset a project or a user picked for this buffer, `lucisv.toml` /// first; `None` when neither did, or when the pick is `auto`, which names /// no preset and so no indent. fn chosen_style(file: &FileConfig, client: &ClientSettings) -> Option