Repository navigation
refactor(lsp,core): unify LSP and CLI formatters via format_posting - #1158
Merged
Merged
Conversation
`execute_command::rledger.alignAmounts` had its own bespoke posting- alignment pipeline: a regex-style line scanner, an "Assets/Liabilities/ Equity/Income/Expenses" prefix check to identify posting lines, and a "max-existing-column" alignment heuristic. It produced visibly different output than the canonical paths: - `rledger format` (CLI, uses `rustledger_core::format::format_directive`). - `textDocument/formatting` (LSP, uses `handlers::formatting::handle_formatting`). It also pre-dates #1142 and #1151 — so it didn't benefit from any of: - Per-posting source spans (the bespoke line scanner can't see posting-level metadata interleaved between postings, just like the pre-#1142 formatting handlers). - The shared `LineIndex` (#1157 perf fix) — every alignment computed its own line positions from scratch. This commit deletes the bespoke pipeline and delegates to `handle_formatting`. The command now inherits every formatter fix automatically: - Per-posting span lookup preserves interleaved metadata (#1142). - Single `LineIndex` per request → O(log lines) offset lookups. - Posting-line detection comes from the parsed AST, not a hard-coded account-prefix list (custom account roots from `option "name_assets" ...` now work). - Plugin-synthesized postings (`file_id == SYNTHESIZED_FILE_ID`) are skipped consistently. Removed code: - `handle_align_amounts`'s 80-line scanner. - `is_posting_line` / `find_amount_position` helpers (dead after the scanner was removed; the on_type_formatting handler has its own `is_posting_line` copy and is unaffected). - Their two unit tests, replaced by one delegation smoke test that verifies both the misaligned-source and already-aligned shapes. Verified: cargo check --workspace --all-features --all-targets, RUSTFLAGS=-Dwarnings cargo build --workspace --all-features --all-targets, cargo clippy --workspace --all-features --all-targets -- -D warnings, RUSTDOCFLAGS=-Dwarnings cargo doc --workspace --no-deps, cargo test -p rustledger-lsp --all-features (133 tests, 0 failures), cargo fmt --all -- --check. Refs #1142 Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
Contributor
There was a problem hiding this comment.
Pull request overview
Refactors the rledger.alignAmounts LSP execute-command to reuse the canonical document formatting pipeline (handle_formatting) instead of maintaining a bespoke amount-alignment scanner, so the command inherits formatter fixes (e.g., span-based posting lookup that preserves interleaved metadata per #1142).
Changes:
rledger.alignAmountsnow synthesizesDocumentFormattingParamsand delegates tohandle_formatting, returning aWorkspaceEdit.- Removes the bespoke posting/amount scanning + helper functions previously local to
execute_command.rs. - Replaces helper unit tests with a single delegation-oriented smoke test.
Comments suppressed due to low confidence (1)
crates/rustledger-lsp/src/handlers/execute_command.rs:158
rledger.alignAmountsnow delegates tohandle_formatting, which also performs non-amount formatting (e.g., tab-to-spaces conversion and trailing-whitespace trimming inhandlers/formatting.rs). That means this command can change lines unrelated to amount alignment, which is a behavior change from the previous align-only implementation. If the command is intended to only align amounts, consider filtering the returnedTextEdits to the posting/amount edits (or introducing a dedicated formatter entrypoint for amount alignment). Otherwise, update the command’s message/documentation to reflect that it now applies full-document formatting.
let edits: Vec<TextEdit> = handle_formatting(¶ms, source, parse_result).unwrap_or_default();
if edits.is_empty() {
return Some(serde_json::json!({
"message": "No amounts to align"
}));
}
💡 Add Copilot custom instructions for smarter, more guided reviews. Learn how to get started.
Contributor
📊 Benchmark Results
vs main branch (2026-05-19)
What do these numbers mean?
|
Contributor
✅ Compatibility Test Results
What's tested
Full results available in workflow artifacts |
Codecov Report❌ Patch coverage is
📢 Thoughts on this report? Let us know! |
…ting
Closes the deeper duplication this PR's first round only partially
removed. The LSP's `handle_formatting` had its own bespoke
`format_posting_line` with two latent problems:
1. **Column mismatch.** Hardcoded `AMOUNT_COLUMN = 50` constant in
the LSP vs `FormatConfig::default().amount_column = 60` in core.
`rledger format` (CLI, via `format_directive` → `format_posting`)
wrote amounts to column 60 on disk; the editor's
`textDocument/formatting` and `rledger.alignAmounts` produced
column 50. The two never agreed.
2. **Silent data-shape loss.** The LSP's hand-rolled formatter
handled only the account + units. It did NOT format cost specs
(`{...}`) or price annotations (`@`/`@@`). For postings that
carried them, the resulting "formatted" string was a strict
subset of the source, the surrounding `needs_alignment` heuristic
correctly refused to emit an edit (the tokenization didn't
match), and the upshot was that **the LSP formatter silently
never realigned cost-bearing or priced postings**.
This commit:
- Exports `rustledger_core::format::format_posting` (was
module-private). It's the same function that `format_directive`
already uses internally for posting rendering.
- Rewrites the LSP's `format_posting_line` to a thin wrapper around
`format_posting`: format the posting via the core formatter using
`FormatConfig::default()`, compare to the source line trimmed of
trailing whitespace (which a separate pass strips), emit a
TextEdit if they differ. The bespoke alignment math, the
`needs_alignment` helper, and the `AMOUNT_COLUMN` constant are
gone.
- Updates the `rledger.alignAmounts` command's docstring to reflect
that all three formatting paths (CLI, LSP format, LSP align)
share one source of truth.
Test:
- `test_align_amounts_produces_canonical_alignment` (replaces the
earlier shape-only smoke test) applies the emitted edits to the
source and asserts the amount column matches
`FormatConfig::default().amount_column`. Pins the contract that
the three paths agree on alignment.
Verified: cargo check --workspace --all-features --all-targets,
RUSTFLAGS=-Dwarnings cargo build --workspace --all-features --all-targets,
cargo clippy --workspace --all-features --all-targets -- -D warnings,
RUSTDOCFLAGS=-Dwarnings cargo doc --workspace --no-deps,
cargo test -p rustledger-lsp --all-features (133 tests, 0 failures),
cargo fmt --all -- --check.
Refs #1142
Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
Address Copilot review on PR #1158. The previous comment claimed the synthesized `DocumentFormattingParams` would let "future option-driven behavior land automatically", which isn't true: `workspace/executeCommand` doesn't carry the client's formatting preferences — those only travel with `textDocument/formatting`. If `handle_formatting` ever honors `params.options`, this command will keep using server defaults and silently diverge. The honest fix is documenting that, plus a forward-looking note that the right solution (when this matters) is plumbing a server-wide `FormatConfig` through both handlers, not mirroring a client value this command can't actually see. Refs #1142 Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
The previous commit on this PR unified the LSP formatter with the
core formatter by routing through `format_posting`. That fixed the
column-mismatch and cost/price-drop bugs but introduced a new
data-loss regression: `format_posting` returns just account + amount
+ cost + price, omitting trailing comments. Any posting like
Assets:Bank -50.00 USD ; my comment
now had its source line replaced with a `format_posting` output that
silently dropped `; my comment`. The previous bespoke LSP formatter
accidentally avoided this via its `needs_alignment` heuristic
(whitespace-token compare); my unification removed the heuristic
without restoring an equivalent guard.
Fix: extract `format_posting_line` in core that wraps
`format_posting` and appends the first same-line trailing comment
(matching what `format_transaction` already does inline). Both the
on-disk path (`format_transaction`) and the LSP edit path now call
the same helper. One source of truth for "what does a posting line
look like as one line".
Changes:
- `rustledger_core::format::format_posting_line` (new public fn) —
wraps `format_posting` + appends `posting.trailing_comments[0]`.
- `format_transaction` in core uses it instead of the inline
`if let Some(trailing) = ... writeln!(...)` block.
- LSP's `posting_text_edit` (renamed from the colliding
`format_posting_line`) now calls
`rustledger_core::format_posting_line`.
Test:
- `test_formatting_preserves_trailing_comment_on_posting` — feeds a
misindented posting with a same-line `; comment`, asserts the
resulting `TextEdit`'s `new_text` still contains the comment.
Verified to FAIL against the bad version (calling `format_posting`
directly).
Verified: cargo test -p rustledger-lsp -p rustledger-core
--all-features (134 LSP + 305 core, 0 failures);
cargo clippy --workspace --all-features --all-targets -- -D warnings;
RUSTFLAGS=-Dwarnings cargo build --workspace --all-features --all-targets;
RUSTDOCFLAGS=-Dwarnings cargo doc --workspace --no-deps;
cargo fmt --all -- --check.
Refs #1142
Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
Address review item 2 (options divergence between handlers).
The previous shape had `handle_align_amounts` synthesizing a
`DocumentFormattingParams` with `options: Default::default()` and
passing it to `handle_formatting`. That hid the fact that the
executeCommand path has NO client formatting options to honor — it
just inherited whatever interpretation `handle_formatting` placed on
the synthetic default. The moment `handle_formatting` learned to
read `params.options`, the two paths would diverge silently.
Fix:
- Split `handle_formatting` into two functions:
* `handle_formatting(params, source, parse_result)` — the LSP
protocol wrapper, takes the client's `DocumentFormattingParams`,
resolves a `FormatConfig` from `params.options` via
`document_format_config(Some(...))`.
* `format_document(source, parse_result, &FormatConfig)` — the
pure formatting body, takes an already-resolved config.
- New `handlers::utils::document_format_config(opts: Option<&FormattingOptions>) -> FormatConfig`
is the single place that maps LSP options → `FormatConfig`. Today
it ignores `opts` and returns `FormatConfig::default()`; when
server-config plumbing lands, that one function changes. The
`Some` / `None` distinction is preserved so the helper can fall
back to server defaults when the executeCommand path provides no
client value.
- `handle_align_amounts` now calls
`format_document(source, parse_result, &document_format_config(None))`
directly — no more fake `DocumentFormattingParams`. The `None`
literally encodes "no client options here," and the comment
documents why.
This contains the divergence risk to a single function (the helper)
and a single boolean (`Some`/`None`). When the LSP server gains real
config, both paths benefit automatically.
Verified: cargo test -p rustledger-lsp --all-features (134 tests, 0
failures); cargo clippy --workspace --all-features --all-targets --
-D warnings; RUSTFLAGS=-Dwarnings cargo build --workspace
--all-features --all-targets; RUSTDOCFLAGS=-Dwarnings cargo doc
--workspace --no-deps; cargo fmt --all -- --check.
Refs #1142
Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Summary
Unifies the LSP and CLI formatters around
rustledger_core::format_posting_line, the single canonical "what does a posting line look like" function. The LSP previously had its own hand-rolled formatter with three latent problems that are now gone.What this PR fixes
Column mismatch (LSP=50, CLI=60)
crates/rustledger-lsp/src/handlers/formatting.rs:15hardcodedAMOUNT_COLUMN = 50;FormatConfig::default()in core defaults to 60.rledger formaton disk and the editor's "Format Document" produced amounts in different columns. They now agree — both use the core default.Silent cost/price drop
The old LSP formatter only handled account + units. For a posting like
the formatted output dropped
{150 USD} @ 155 USD. The surrounding tokenization heuristic noticed the mismatch and bailed, so the LSP silently never realigned cost-bearing or priced postings. Routing throughformat_posting_line(which handles cost + price + units uniformly) fixes it.Trailing-comment data loss (caught mid-review)
An earlier draft of this PR delegated to
format_postingdirectly. That function omits trailing comments — so a source line likeAssets:Bank -50.00 USD ; my commentwould have had the; my commentsilently dropped on format. The pre-unification code accidentally avoided this via itsneeds_alignmenttoken-compare heuristic. The fix (commit73e1f5d9) extracts aformat_posting_linehelper in core that wrapsformat_posting+ appends the first trailing comment, so the on-disk path (format_transaction) and the LSP edit path call the same helper. Regression test intest_formatting_preserves_trailing_comment_on_posting— verified to FAIL against the broken version.Architecture after this PR
One canonical posting-line renderer; one canonical
FormatConfigresolver; both LSP entrypoints share both. The on-disk and editor paths produce identical output for any given config.User-visible behavior changes
Amount column moves from 50 → 60. Anyone using the LSP's "Format Document" or "Align Amounts" command will see their amounts shift one column right. This matches the column
rledger formatalready produces on disk — and means saving via the editor and saving via the CLI produce the same file. Users who want column 50 back will need server-config plumbing (see next section).Cost-bearing and priced postings now realign. Previously the LSP formatter silently skipped them; now they format like any other posting.
Known limitation, with explicit deferred fix
workspace/executeCommanddoes not carry the client'sFormattingOptions(tab size, etc.) — those only travel withtextDocument/formatting. Therledger.alignAmountscommand therefore always uses server defaults, whiletextDocument/formattingcould honor client options.Today both paths produce identical output because
document_format_configignores its argument and returnsFormatConfig::default(). When the LSP server gains real config plumbing (server-wide settings viainitializationOptions, or per-document viaworkspace/configuration), that helper is the single point to update — both call sites benefit automatically, and the executeCommand path will fall back to server defaults (via the explicitNone) rather than silently mirroring an absent client value.This is documented in the code on both
document_format_configand at thehandle_align_amountscall site.Test plan
cargo check --workspace --all-features --all-targetsRUSTFLAGS=-Dwarnings cargo build --workspace --all-features --all-targetscargo clippy --workspace --all-features --all-targets -- -D warningsRUSTDOCFLAGS=-Dwarnings cargo doc --workspace --no-depscargo test -p rustledger-lsp -p rustledger-core --all-features— 134 LSP + 305 core, 0 failurescargo fmt --all -- --checktest_align_amounts_produces_canonical_alignment— applies emitted edits, asserts the amount column equalsFormatConfig::default().amount_column.test_formatting_preserves_trailing_comment_on_posting— verified to fail against the data-loss-prone version.Refs #1142
🤖 Generated with Claude Code