fix(format): drop a temperature's space before its trailing zeros #168

Merged
abiwab merged 1 commit from fix/format-temperature-zeros into main 2026-11-16 23:24:11 +01:00
3 changed files with 33 additions and 9 deletions

View file

@ -0,0 +1,5 @@
---
"@gram-lang/format": patch
---
**Format**: Fixed a temperature written with a space and trailing zeros, such as `^{160.0 °C}`, that took two runs of the formatter to become `^{160°C}`: it is now fixed in one.

View file

@ -161,6 +161,18 @@ export function formatGram(source: string): {
return `{${trimmed}}`;
});
// Rule 5: Remove space before ° in temperature quantities (handles multiple temps per brace).
// Runs before rule 4, whose patterns allow no space before the unit: in
// the other order `{160.0 °C}` only became `{160.0°C}`, and a second run
// was needed to drop the zero.
body = body.replace(/\{([^}]*)\}/g, (_, inner) => {
const fixed = inner.replace(/(\d+)\s+°/g, (_m: string, n: string) => {
changes.temperatureSpacing++;
return `${n}°`;
});
return `{${fixed}}`;
});
// Rule 4: Remove trailing decimal zeros in quantities ({500.0g} → {500g}, {1.50g} → {1.5g})
body = body.replace(/\{(\d+)\.0+([a-zA-Z°%]*)\}/g, (_, n, u) => {
changes.trailingZeros++;
@ -171,15 +183,6 @@ export function formatGram(source: string): {
return `{${n}${u}}`;
});
// Rule 5: Remove space before ° in temperature quantities (handles multiple temps per brace)
body = body.replace(/\{([^}]*)\}/g, (_, inner) => {
const fixed = inner.replace(/(\d+)\s+°/g, (_m: string, n: string) => {
changes.temperatureSpacing++;
return `${n}°`;
});
return `{${fixed}}`;
});
// Rule 6 (from language-server): normalize composite separator spacing
// (@ingA{} < @ingB{} → @ingA{}<@ingB{})
body = body.replace(/ *< *@/g, (match) => {

View file

@ -277,3 +277,19 @@ describe("summarizeChanges", () => {
expect(summary).toContain("3 tabs converted to spaces");
});
});
describe("a temperature with a space and trailing zeros", () => {
it("is fixed in a single run", () => {
const { content, changes } = formatGram("## T\n\nBake at ^{160.0 °C}.\n");
expect(content).toContain("^{160°C}");
expect(changes.temperatureSpacing).toBe(1);
expect(changes.trailingZeros).toBe(1);
expect(formatGram(content).content).toBe(content);
});
it("keeps the zeros that matter", () => {
expect(formatGram("## T\n\nHeat to ^{37.50 °C}.\n").content).toContain(
"^{37.5°C}",
);
});
});