Skip to content

fix(format): align amounts by display width - #2869

Merged
robcohen merged 10 commits into
mainfrom
fix/format-align-by-display-width
Nov 5, 2026
Merged

robcohen merged 10 commits into
mainfrom
fix/format-align-by-display-width

Conversation

@robcohen

@robcohen robcohen commented Nov 5, 2026 •

Copy link
Copy Markdown
Member

What changed

  • New format::display_width (unicode-width) gives the number of terminal cells a string takes: East Asian Wide and Fullwidth characters 2, combining marks and zero-width characters 0, ambiguous-width characters 1 (as most terminals render them), and emoji as unicode-width gives them (2 for emoji-presentation characters).
  • It is the one width rule for every alignment computation:
    • the width pre-pass (compute_alignment);
    • the posting emitter (emit_posting), which also serves LSP document and range formatting through the shared emitter;
    • the LSP inferred-amount inlay hint, which places its label against the formatter's number_col. Its indent is still counted per character, as before (unicode-width gives a tab one cell, which is no closer to how a terminal renders it, so the count is left alone).
  • unicode-width 0.2 becomes a workspace dependency. It was already in Cargo.lock (0.2.2) through other crates, but it is new in the rustledger-wasm (wasm32) and rustledger-ffi-component (wasip2) build graphs. A minimal wasm32 cdylib probe grew by about 30 KB, the width tables; the WASM size gate warns only above 2 MB. cargo-vet covers it (Mozilla wildcard audit), deny.toml already skips it for its two versions, and cargo deny check reports advisories, bans, licenses and sources all ok.
  • No cache bump: ParseResult::alignment is not archived in the loader or WASM caches.

Why

The formatter padded the account field by character count, so a posting to Expenses:생활 (two characters, four cells) put its amount two columns right of the others in a monospaced editor (#2852).

A deliberate difference from bean-format

bean-format 3.2.3 never lines these amounts up. Its alignment regex is [\p{Lu}][\p{L}\p{Nd}\-]*(?::[\p{Lu}\p{Nd}][\p{L}\p{Nd}\-]*)+ followed by whitespace: each component after the root must start with an uppercase letter or a digit, and every character must be a letter, a digit or a hyphen. So:

  • a posting to Expenses:생활 or Expenses:食品 (a component starting with a letter that has no case), or to an account with an emoji (Assets:CORP✨) or a combining mark anywhere (Expenses:Cafe followed by U+0301, a decomposed é), does not match, and bean-format leaves its spacing as written, while still aligning every matching line, in that transaction and elsewhere in the file, to its one file-wide column. A precomposed Expenses:Café (U+00E9) does match, and é is one cell, so bean-format and rledger write it identically;
  • a line that does match but contains a wide character (Expenses:X생활, fullwidth Expenses:Food) is padded by code points (Python's len()), so the wide characters put its amount further right on screen: bean-format writes Expenses:X생활 12345 KRW above Assets:Bank -12345 KRW, two cells off. Emoji and combining marks never reach this case.

Both checked with bean-format in the dev shell. rledger lines the amounts up on screen in both cases. For ASCII-only text, amount alignment is unchanged by this PR. It still differs from bean-format's in other ways: bean-format also aligns dated balance and price lines, which widen the posting column, and leaves other spacing as written. This is documented in docs/reference/compatibility.md section 19 and at display_width.

Which files change

I ran rledger format from a main build and from this branch (separate target dirs; the binaries differ) over all 1,844 in-tree .beancount/.bean files and the compatibility corpus. Only two files change, both with a wide character in an account name:

  • double-entry-generator/example_hxsec_example-hxsec-output.beancount (Assets:Hxsec:Positions:沪深300): its amounts shift right by two cells, 35 lines.
  • fava-portfolio-returns/src_fava_portfolio_returns_test_ledger_unicode.beancount (Assets:CORP✨): one line shifts by one cell.

The corpus baselines record parser output, not formatter output, so none move.

How to test

cargo test -p rustledger-parser --test format_display_width runs 4 tests:

  • the issue's Korean example, and a CJK, combining-mark and emoji example: exact output, the amounts end in one visible column, and the output is idempotent;
  • ASCII input is unchanged;
  • display_width cell counts, including an ambiguous-width character.

The parser, LSP, CLI and WASM suites pass (91 result lines), as do format_compat, the idempotence matrix and the range-vs-whole-file drift guard. Workspace clippy, rustdoc and fmt are clean.

Review round 1

  • Merged main (a CHANGELOG conflict with fix(format): keep range formatting on a top-level comment idempotent #2863; both entries kept), so CI can run.
  • New test_inlay_hint_wide_account_pads_by_display_width_2852: an explicit Expenses:Restaurants -50.00 USD and an elided Assets:생활 give the hint UTF-16 position 11 and a 12-space gap. It fails with the inlay-hint change reverted (counting characters gives 14).
  • Corrected the tab note (unicode-width gives a tab one cell, not zero) and the dependency note above.
  • compatibility.md section 19 no longer claims ASCII-only files format exactly as bean-format does (rledger also normalizes other spacing, such as 2021-01-01 open Assets:Bank USD); it says amount alignment for ASCII-only text is unchanged and matches bean-format's.

Review round 2

  • Corrected how bean-format handles wide characters, verified with bean-format: it leaves a non-matching line such as Expenses:생활 as written and pads only matching lines by code points. Fixed in compatibility.md section 19, the display_width doc, the format_display_width.rs header, the CHANGELOG and this description.
  • No longer claims ASCII-only alignment matches bean-format's (bean-format also aligns dated balance and price lines).
  • The [Feature]: LSP amount hints should align with formatting #1346 inlay test has its own doc comment again, now saying display cells; end_col_chars is renamed end_col_cells.
  • Reverted the bot's unrelated utf8_iter audit churn in supply-chain/imports.lock: cargo vet --locked (0.10.2) passes with and without it (312 fully audited, 201 exempted).
  • Merged main again (a CHANGELOG conflict with fix(price): point ratesapi at Frankfurter, as beanprice does #2864; both entries kept).

Review round 3

  • Corrected the Expenses:Café example: a precomposed é matches bean-format's regex and aligns identically in both tools; only the decomposed form (Cafe + U+0301) is left as written. The example now names the decomposed form explicitly.
  • Stated bean-format's rule exactly (the regex above): uppercase-or-digit start for each component after the root, and letters, digits and hyphens only, so an emoji or combining mark anywhere leaves the line as written. Same tweak in display_width's doc, the test header and the CHANGELOG.
  • Noted that bean-format still realigns the other matching postings of such a transaction.
  • Verified with bean-format 3.2.3 in the dev shell: precomposed Café aligned (and byte-identical to rledger's output), decomposed Café and CORP✨ left as written, Expenses:생활 left as written while Assets:Bank / Assets:Cash were still aligned to the file-wide column.

Closes #2852

🤖 Generated with Claude Code

Review round 4

  • The sentence about bean-format realigning "the transaction's other postings among themselves" implied per-transaction alignment. Both tools use one column for the whole file, so the wording now says matching lines are aligned to the file-wide column (compatibility.md section 19 and this body).
  • Restored Expenses:食品 in section 19, where a Hangul 품 had slipped in.
  • Rewrapped an overlong doc line in format_display_width.rs.

The formatter padded the account field by character count, so a posting
to `Expenses:생활` (two characters, four cells) put its amount two columns
right of the others in a monospaced editor. A new `format::display_width`
(unicode-width: East Asian Wide/Fullwidth 2 cells, combining marks 0,
ambiguous 1) is now the one width rule for the alignment pre-pass, the
posting emitter, and the LSP inferred-amount inlay hint that places text
against the formatter's column. ASCII-only files are unchanged.

This deliberately differs from bean-format 3.2.3, which pads by code
points; documented in compatibility.md section 19 and pinned by
tests/format_display_width.rs. Over 1,844 in-tree and corpus files only
two change, both with wide characters in an account name.

Closes #2852

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@robcohen
robcohen requested a review from a team as a code owner November 5, 2026 06:41
rustledger-bot Bot and others added 3 commits November 5, 2026 06:43
… two doc claims

Merges main (CHANGELOG conflict with #2863: both entries kept).

Review of #2869: a test now covers the inlay-hint hunk (explicit
`Expenses:Restaurants  -50.00 USD`, elided `Assets:생활`: UTF-16 position
11 and a 12-space gap; counting characters gave 14). The tab comment
said unicode-width gives a tab 0 cells; it gives 1. compatibility.md
section 19 now says ASCII-only amount alignment is unchanged and matches
bean-format, instead of claiming whole-file parity.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@github-actions

github-actions Bot commented Nov 5, 2026 •

Copy link
Copy Markdown
Contributor

📊 Benchmark Results

Shape rustledger beancount Speedup RSS (rledger / beancount)
simple 57.8ms ± 0.7ms 765.1ms ± 6.1ms 13.2x 34.6 MB / 51.2 MB
investment 85.7ms ± 0.8ms 3317.4ms ± 46.8ms 38.7x 44.9 MB / 59.0 MB
fifo 81.2ms ± 0.5ms 18829.7ms ± 661.6ms 231.9x 40.8 MB / 58.7 MB

vs base, measured in this run

Shape base this PR Change RSS base → PR
simple 57.1ms ± 0.6ms 57.8ms ± 0.7ms +1.2% ✅ within noise 34.6 MB → 34.6 MB (+0.0%)
investment 85.1ms ± 0.7ms 85.7ms ± 0.8ms +0.7% ✅ within noise 44.6 MB → 44.9 MB (+0.7%)
fifo 83.9ms ± 9.6ms 81.2ms ± 0.5ms -3.2% ✅ within noise 40.8 MB → 40.8 MB (+0.0%)

A difference counts only when it clears the combined spread of the two measurements, per shape (2σ: simple 0.4ms, investment 0.5ms, fifo 4.3ms), and is at least 5%.
10,000 transactions per shape · 20 runs, 3 warmup · hyperfine

What do these numbers mean?
  • simple — Two-posting transfers, one currency. The historical workload — keep as the floor, not as the benchmark.
  • investment — Cost specs, per-unit prices and lot reductions. Exercises booking and inventory, which simple leaves at 0.3%.
  • fifo — Bare {} reductions against a FIFO account — how FIFO sells are normally written. The other four shapes reach the ordered-selection path twice in 2k transactions between them, so it was effectively unprofiled until it turned out to be quadratic (plan_ordered scans every lot per reduction: FIFO ledgers are quadratic (8.8s at 20k transactions) #2083).
  • vs base: the PR and the base-branch commit it is built on, built and measured in the same job
  • RSS: peak resident set size, a single sample — reported without a verdict because there is no spread to test it against
  • A shape with no beancount column is one bean-check reports errors on; it is timed for rledger only

@codecov

codecov Bot commented Nov 5, 2026 •

Copy link
Copy Markdown

Codecov Report

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

Files with missing lines Patch % Lines
crates/rustledger-lsp/src/handlers/inlay_hints.rs 96.42% 1 Missing ⚠️

📢 Thoughts on this report? Let us know!

@github-actions

github-actions Bot commented Nov 5, 2026

Copy link
Copy Markdown
Contributor

✅ Compatibility Test Results

Metric Result
Check Compatibility 100%
BQL Compatibility 100% (raw 93%, 179 masked)
Full AST Match 100%
Total Files 826
What's tested
  • Check: Exit codes and error counts match bean-check
  • BQL: Query results match bean-query
    The headline is the EFFECTIVE rate, after pairs where beanquery
    itself is wrong are masked. raw is the same run with nothing
    masked. A widening gap means the registry grew, not that rledger
    changed.
  • Files: ~800 test files downloaded from 10+ beancount repositories

Full results available in workflow artifacts

robcohen and others added 6 commits November 5, 2026 02:57
Review round 2 of #2869. bean-format 3.2.3 does not pad `Expenses:생활`
by code points: its alignment regex needs each account component to start
with an uppercase letter or a digit, so that line is left as written, and
only a line that matches (`Expenses:X생활`, fullwidth `Food`) is padded by
code points. Verified with bean-format. Corrected in compatibility.md
section 19, the display_width doc, the format_display_width.rs header and
the CHANGELOG, which also no longer claim ASCII-only alignment matches
bean-format (it also aligns dated balance and price lines).

Also gives the #1346 inlay test its doc comment back (now in display
cells), renames end_col_chars to end_col_cells, and reverts the bot's
unrelated utf8_iter imports.lock churn (cargo vet --locked passes either
way).

Co-Authored-By: Claude Opus 5.5 <[email protected]>
bean-format 3.2.3 matches a precomposed Expenses:Café (U+00E9) and
aligns it as rledger does; only a decomposed é (U+0301) is left as
written. Its regex also needs every character to be a letter, digit
or hyphen, so an emoji or combining mark anywhere in the account leaves
the line as written, while the transaction's other matching postings
are still realigned among themselves. Verified with bean-format.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
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.

[Bug]: Formatter aligns Unicode account names by character count instead of display width

1 participant