Skip to content

refactor(lsp,core): unify LSP and CLI formatters via format_posting - #1158

Merged
robcohen merged 5 commits into
mainfrom
feat/lsp-align-via-format-directive
May 20, 2026
Merged

robcohen merged 5 commits into
mainfrom
feat/lsp-align-via-format-directive

Conversation

@robcohen

@robcohen robcohen commented May 19, 2026 •

Copy link
Copy Markdown
Member

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:15 hardcoded AMOUNT_COLUMN = 50; FormatConfig::default() in core defaults to 60. rledger format on 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

Assets:Brokerage  10 AAPL {150 USD} @ 155 USD

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 through format_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_posting directly. That function omits trailing comments — so a source line like Assets:Bank -50.00 USD ; my comment would have had the ; my comment silently dropped on format. The pre-unification code accidentally avoided this via its needs_alignment token-compare heuristic. The fix (commit 73e1f5d9) extracts a format_posting_line helper in core that wraps format_posting + appends the first trailing comment, so the on-disk path (format_transaction) and the LSP edit path call the same helper. Regression test in test_formatting_preserves_trailing_comment_on_posting — verified to FAIL against the broken version.

Architecture after this PR

rustledger_core::format_posting_line(posting, config)
            │
            ├── format_transaction (on-disk, via rledger format)
            └── posting_text_edit (LSP)
                       │
                       ├── format_document (pure body)
                       │      ├── handle_formatting (textDocument/formatting)
                       │      │       └── document_format_config(Some(&opts))
                       │      └── handle_align_amounts (rledger.alignAmounts)
                       │              └── document_format_config(None)

One canonical posting-line renderer; one canonical FormatConfig resolver; 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 format already 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/executeCommand does not carry the client's FormattingOptions (tab size, etc.) — those only travel with textDocument/formatting. The rledger.alignAmounts command therefore always uses server defaults, while textDocument/formatting could honor client options.

Today both paths produce identical output because document_format_config ignores its argument and returns FormatConfig::default(). When the LSP server gains real config plumbing (server-wide settings via initializationOptions, or per-document via workspace/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 explicit None) rather than silently mirroring an absent client value.

This is documented in the code on both document_format_config and at the handle_align_amounts call site.

Test plan

  • 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 -p rustledger-core --all-features — 134 LSP + 305 core, 0 failures
  • cargo fmt --all -- --check
  • test_align_amounts_produces_canonical_alignment — applies emitted edits, asserts the amount column equals FormatConfig::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

`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]>
@robcohen
robcohen requested a review from a team as a code owner May 19, 2026 23:07
Copilot AI review requested due to automatic review settings May 19, 2026 23:07

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.alignAmounts now synthesizes DocumentFormattingParams and delegates to handle_formatting, returning a WorkspaceEdit.
  • 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.alignAmounts now delegates to handle_formatting, which also performs non-amount formatting (e.g., tab-to-spaces conversion and trailing-whitespace trimming in handlers/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 returned TextEdits 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(&params, 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.

@github-actions

github-actions Bot commented May 19, 2026 •

Copy link
Copy Markdown
Contributor

📊 Benchmark Results

Tool Time Memory
rustledger 33.2ms ± 0.6ms 25.2 MB
beancount 873.9ms ± 3.3ms 50.7 MB
Comparison 26.3x faster 2.0x less

vs main branch (2026-05-19)

Metric main this PR Change
Time 35.4ms 33.2ms -6.2% 🟢
10K transactions · 5 runs, 2 warmup · hyperfine
What do these numbers mean?
  • Time: Wall-clock time to parse and validate the ledger (± std dev)
  • Memory: Peak resident set size (RSS)
  • vs main: Compared to latest nightly benchmark on main branch

@github-actions

github-actions Bot commented May 19, 2026 •

Copy link
Copy Markdown
Contributor

✅ Compatibility Test Results

Metric Result
Check Compatibility 100%
BQL Compatibility 100%
Full AST Match 100%
Total Files 786
What's tested
  • Check: Exit codes and error counts match bean-check
  • BQL: Query results match bean-query
  • Files: ~800 test files downloaded from 10+ beancount repositories

Full results available in workflow artifacts

@codecov

codecov Bot commented May 19, 2026 •

Copy link
Copy Markdown

Codecov Report

❌ Patch coverage is 99.16667% with 1 line in your changes missing coverage. Please review.

Files with missing lines Patch % Lines
...tes/rustledger-lsp/src/handlers/execute_command.rs 98.30% 1 Missing ⚠️

📢 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]>
@robcohen robcohen changed the title refactor(lsp): align_amounts command delegates to formatting handler refactor(lsp,core): unify LSP and CLI formatters via format_posting May 19, 2026
robcohen and others added 3 commits May 19, 2026 18:32
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]>
@robcohen
robcohen merged commit 725a9bf into main May 20, 2026
34 checks passed
@robcohen
robcohen deleted the feat/lsp-align-via-format-directive branch May 20, 2026 00:10
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants