From f3a7c72bb61336a3d742a6dbc65ea3d90a010ead Mon Sep 17 00:00:00 2001 From: Vedran Dobos <19259909+vedran-dobos@users.noreply.github.com> Date: Thu, 22 Oct 2026 07:09:19 +0200 Subject: [PATCH 1/5] Format: number formats widen columns that weren't sized by hand (#1077) Increase/Decrease Decimal and the ribbon's other number formats widened the format but never the column, so the number turned into ####. A column nobody sized by hand now widens to the widest number in the target, as observed in Excel 16.0: AutoFit counts as automatic, Column Width (or dragging the border) as by hand; hidden columns, text, General numbers, merged and shrink-to-fit cells don't widen; columns never narrow. LineInfo::custom now marks columns set by hand too. XLSX reads and writes it as Excel does (customWidth without bestFit = by hand; automatic widths get bestFit and customWidth), and .xls reads COLINFO's fUserSet and fBestFit the same way. Co-Authored-By: Claude Opus 5.5 --- crates/engine/src/cmd/format.rs | 117 +++++++++++++++++++++++++++- crates/model/src/features.rs | 3 +- crates/ui-egui/tests/interaction.rs | 33 ++++++++ crates/xlsx/src/sheet_read.rs | 3 + crates/xlsx/src/sheet_write.rs | 4 +- crates/xlsx/src/tests/fixtures.rs | 23 ++++++ crates/xlsx/src/tests/roundtrip.rs | 3 +- crates/xlsx/src/xls/mod.rs | 1 + docs/decisions.md | 30 ++++++- docs/file-format-parity.md | 3 +- docs/ui-parity.md | 3 +- 11 files changed, 216 insertions(+), 7 deletions(-) diff --git a/crates/engine/src/cmd/format.rs b/crates/engine/src/cmd/format.rs index cd28cfbfa..2619f59bd 100644 --- a/crates/engine/src/cmd/format.rs +++ b/crates/engine/src/cmd/format.rs @@ -708,7 +708,64 @@ fn number_format(s: &mut Session, p: &Json) -> Result { fn set_fmt(s: &mut Session, p: &Json, code: &str) -> Result { let nf = NumFmt::new(code); - apply_style(s, p, |st| st.num_fmt = nf.clone()) + apply_style(s, p, |st| st.num_fmt = nf.clone())?; + widen_for_numbers(s, p) +} + +/// After a number format from the ribbon (Increase Decimal, Comma Style, the Number Format list…), +/// a column nobody sized by hand widens so the formatted numbers in the target fit, instead of +/// showing ####. Observed in Excel 16.0 (build 17932): a column at the default width, AutoFitted, or +/// widened this way before widens to the widest number in the range, also with Wrap Text and a large +/// font. A width set with Column Width (or by dragging) stays, even when it equals the default. Hidden +/// columns, text, General numbers (they round to fit), shrink-to-fit and merged cells don't widen, +/// and columns never narrow. +fn widen_for_numbers(s: &mut Session, p: &Json) -> Result { + let sheet = target_sheet(s, p)?; + let ranges = target_ranges(s, p)?; + let measure = s.text_width.clone(); + edit(s, |cx| { + let Some(sh) = cx.wb.sheet(sheet) else { return Ok(Json::Null) }; + let Some(used) = sh.used_range() else { return Ok(Json::Null) }; + if sh.show_formulas { + return Ok(Json::Null); + } + let mut need: std::collections::BTreeMap = std::collections::BTreeMap::new(); + // Measured as AutoFit Column Width measures (the UI's font when it supplies one). + let mut measured: std::collections::HashMap<(StyleId, String), f32> = Default::default(); + for r in ranges.iter().filter_map(|r| r.intersection(&used)) { + if r.count() > 4_000_000 { + continue; + } + for (c, cell) in sh.cells.iter_range(r) { + if !matches!(cell.value, gridcraft_core::Value::Number(_)) + || sh.cols.get(&c.col).is_some_and(|i| i.custom || i.hidden) + || sh.merge_at(c).is_some_and(|m| !m.is_single()) + { + continue; + } + let id = sh.style_id(c); + let st = cx.wb.styles.get(id); + if st.num_fmt.as_str() == "General" || st.align.shrink || st.align.h == HAlign::Fill { + continue; + } + let text = crate::display::cell_text(&cx.wb, sh, c); + let exact = measured.len() < EXACT_TEXT_WIDTHS; + let w = *measured.entry((id, text)).or_insert_with_key(|(_, t)| match &measure { + Some(m) => m(t, &st.font, exact), + None => approx_text_width(t, st.font.size, st.font.bold), + }); + let w = w + 6.0 + st.align.indent as f32 * 9.0; + let e = need.entry(c.col).or_insert(0.0); + *e = e.max(w); + } + } + let widen: Vec<(u32, f32)> = need.into_iter().filter(|&(c, w)| w > sh.col_width(c)).collect(); + let sh = cx.sheet_mut(sheet)?; + for (c, w) in widen { + sh.cols.entry(c).or_default().size = Some(w.ceil().min(1785.0)); + } + Ok(Json::Null) + }) } /// Adds or removes one decimal place in the number format (Increase/Decrease Decimal). @@ -1076,6 +1133,7 @@ fn col_width(s: &mut Session, p: &Json) -> Result { let e = sh.cols.entry(c).or_default(); e.size = Some(w as f32); e.hidden = w == 0.0; + e.custom = true; } } Ok(Json::Null) @@ -1167,6 +1225,7 @@ fn autofit_cols(s: &mut Session, p: &Json) -> Result { let e = sh.cols.entry(c).or_default(); e.size = Some(w.ceil()); e.hidden = false; + e.custom = false; // AutoFit makes a width set by hand automatic again (Excel). } Ok(Json::Null) }) @@ -1260,6 +1319,62 @@ mod tests { assert_eq!(adjust_decimals("0%", &v, 1), "0.0%"); } + fn col(s: &crate::Session, c: u32) -> (f32, bool) { + let sh = s.active().unwrap().wb.active().unwrap(); + (sh.col_width(c), sh.cols.get(&c).is_some_and(|i| i.custom)) + } + + /// #1077: Increase Decimal widened the format but not the column, so the number turned into ####. + #[test] + fn increase_decimal_widens_a_column_nobody_sized() { + let mut s = crate::Session::new(); + s.new_workbook(); + s.execute("cell.set", json!({"cell": "A1", "input": "3.14159265"})).unwrap(); + let (default, _) = col(&s, 0); + s.execute("home.increaseDecimal", json!({"range": "A1"})).unwrap(); + let (w, custom) = col(&s, 0); + let text = s.execute("cell.get", json!({"cell": "A1"})).unwrap()["text"].as_str().unwrap().to_string(); + assert_eq!(text, "3.141592650"); + assert!(w > default, "the column widens for {text}: {w} vs {default}"); + assert!(w >= approx_text_width(&text, gridcraft_model::DEFAULT_FONT_SIZE, false), "and fits it"); + assert!(!custom, "it isn't a width set by hand, so it can widen again"); + s.execute("home.increaseDecimal", json!({"range": "A1"})).unwrap(); + assert!(col(&s, 0).0 > w, "one more decimal, a little wider again"); + let wide = col(&s, 0).0; + s.execute("home.decreaseDecimal", json!({"range": "A1"})).unwrap(); + assert_eq!(col(&s, 0).0, wide, "fewer decimals don't narrow it"); + s.execute("edit.undo", json!({})).unwrap(); + s.execute("edit.undo", json!({})).unwrap(); + assert_eq!(col(&s, 0).0, w, "Undo takes back the format and the width in one step"); + } + + #[test] + fn number_formats_keep_a_width_set_by_hand_and_general_numbers_round_instead() { + let mut s = crate::Session::new(); + s.new_workbook(); + s.execute("range.setValues", json!({"range": "A1", "values": [[1234567.891, 1234567.891, 1234567.891, 1234567.891]]})).unwrap(); + s.execute("home.columnWidth", json!({"cols": "A:A", "width": 40})).unwrap(); + assert_eq!(col(&s, 0), (40.0, true), "Column Width (and dragging the border) is a width set by hand"); + s.execute("home.hideColumns", json!({"cols": "D:D"})).unwrap(); + for a in ["A1", "B1", "D1"] { + s.execute("home.comma", json!({"range": a})).unwrap(); + } + s.execute("home.numberFormat", json!({"range": "C1", "format": "General"})).unwrap(); + let (default, _) = col(&s, 4); + assert_eq!(col(&s, 0), (40.0, true), "a width set by hand stays: the cell shows ####, as in Excel"); + assert!(col(&s, 1).0 > default, "B widens for 1,234,567.89"); + assert_eq!(col(&s, 2).0, default, "General rounds to fit instead"); + assert_eq!(col(&s, 3).0, 0.0, "a hidden column stays hidden"); + // AutoFit makes a width set by hand automatic again; Wrap Text doesn't stop the widening. + s.execute("home.autofitColumnWidth", json!({"cols": "A:A"})).unwrap(); + assert!(!col(&s, 0).1); + s.execute("home.wrapText", json!({"range": "A1", "on": true})).unwrap(); + let fitted = col(&s, 0).0; + s.execute("home.increaseDecimal", json!({"range": "A1"})).unwrap(); + s.execute("home.increaseDecimal", json!({"range": "A1"})).unwrap(); + assert!(col(&s, 0).0 > fitted, "after AutoFit, with Wrap Text, A widens again"); + } + #[test] fn format_cells_takes_the_documented_keys() { let mut s = crate::Session::new(); diff --git a/crates/model/src/features.rs b/crates/model/src/features.rs index aa250b9b0..14d9549ca 100644 --- a/crates/model/src/features.rs +++ b/crates/model/src/features.rs @@ -925,7 +925,8 @@ pub struct LineInfo { pub outline: u8, pub collapsed: bool, pub style: Option, - /// The size was set by the user (rows): automatic heights follow the content. + /// The size was set by the user. Rows without it follow their content's height; columns + /// without it widen when a number format makes their numbers wider (`home.increaseDecimal`…). #[serde(default)] pub custom: bool, } diff --git a/crates/ui-egui/tests/interaction.rs b/crates/ui-egui/tests/interaction.rs index 46e981d0a..6679af1d4 100644 --- a/crates/ui-egui/tests/interaction.rs +++ b/crates/ui-egui/tests/interaction.rs @@ -963,6 +963,39 @@ fn general_numbers_fit_by_the_cells_own_font() { assert_eq!(texts.iter().filter(|t| t.starts_with('#')).count(), 1, "{texts:?}"); } +/// #1077: after Increase Decimal and the other ribbon number formats the column widens enough for +/// the real font, so the number is drawn instead of ####, at the default size and a large bold one. +#[test] +fn ribbon_number_formats_widen_the_column_enough_to_draw_the_number() { + let mut s = blank(); + s.execute("range.setValues", json!({"range": "A1", "values": [[1.23456789, 1234567.891, 98765.4321], [0.5, 1, 2]]})).unwrap(); + s.execute("home.fontSize", json!({"range": "C1", "size": 20})).unwrap(); + s.execute("home.bold", json!({"range": "C1", "on": true})).unwrap(); + for _ in 0..4 { + s.execute("home.increaseDecimal", json!({"range": "A1"})).unwrap(); + } + s.execute("home.comma", json!({"range": "B1"})).unwrap(); + s.execute("home.numberFormat", json!({"range": "C1", "format": "Currency"})).unwrap(); + s.execute("selection.set", json!({"cell": "E5"})).unwrap(); + let want: Vec = + ["A1", "B1", "C1"].iter().map(|a| s.execute("cell.get", json!({"cell": a})).unwrap()["text"].as_str().unwrap().trim().to_string()).collect(); + assert_eq!(want, ["1.234567890000", "1,234,567.89", "$98,765.43"]); + let h = harness(s); + let texts: Vec = h + .output() + .shapes + .iter() + .filter_map(|c| match &c.shape { + egui::Shape::Text(t) => Some(t.galley.job.text.clone()), + _ => None, + }) + .collect(); + for t in &want { + assert!(texts.iter().any(|x| x.trim() == t), "{t} drawn in full: {texts:?}"); + } + assert!(!texts.iter().any(|t| t.starts_with('#')), "no ####: {texts:?}"); +} + fn text_shapes(shape: &egui::Shape, clip: egui::Rect, out: &mut Vec<(egui::epaint::TextShape, egui::Rect)>) { match shape { egui::Shape::Text(t) => out.push((t.clone(), clip)), diff --git a/crates/xlsx/src/sheet_read.rs b/crates/xlsx/src/sheet_read.rs index 83955ee1f..71600c920 100644 --- a/crates/xlsx/src/sheet_read.rs +++ b/crates/xlsx/src/sheet_read.rs @@ -314,6 +314,9 @@ fn read_cols(cx: &Ctx<'_>, e: &El, sheet: &mut Sheet, remaining: &mut u64) -> Re // A width without `customWidth` that equals the default is just the default. if let Some(w) = c.attr_f64("width") { let px = col_width_to_px(w); + // Excel writes customWidth for every width it stores, and bestFit as well for one that + // AutoFit or a number format sized: only customWidth without bestFit was set by hand. + info.custom = c.flag("customWidth", false) && !c.flag("bestFit", false); if c.flag("customWidth", false) || px != sheet.default_col_width { info.size = Some(px); } diff --git a/crates/xlsx/src/sheet_write.rs b/crates/xlsx/src/sheet_write.rs index daac03daa..ba499b765 100644 --- a/crates/xlsx/src/sheet_write.rs +++ b/crates/xlsx/src/sheet_write.rs @@ -250,8 +250,10 @@ pub fn write_sheet(wb: &Workbook, si: usize, selected: bool, out: &mut Out) -> ( if i.hidden { s.push_str(" hidden=\"1\""); } + // As Excel writes them: a width that AutoFit or a number format sized is bestFit too, so + // it keeps widening when the file is opened again; one set by hand is customWidth only. if i.size.is_some() { - s.push_str(" customWidth=\"1\""); + s.push_str(if i.custom { " customWidth=\"1\"" } else { " bestFit=\"1\" customWidth=\"1\"" }); } if i.outline > 0 { let _ = write!(s, " outlineLevel=\"{}\"", i.outline.min(7)); diff --git a/crates/xlsx/src/tests/fixtures.rs b/crates/xlsx/src/tests/fixtures.rs index 0294f378f..d9396bfef 100644 --- a/crates/xlsx/src/tests/fixtures.rs +++ b/crates/xlsx/src/tests/fixtures.rs @@ -169,7 +169,9 @@ fn styles_theme_and_sizes() { assert!(s.cols.get(&2).unwrap().hidden); assert_eq!(s.cols.get(&2).unwrap().size, Some(145.0)); assert_eq!(s.cols.get(&2).unwrap().outline, 1); + assert!(s.cols.get(&2).unwrap().custom, "customWidth: a width set by hand"); assert_ne!(s.cols.get(&3).unwrap().style, None); + assert!(!s.cols.get(&3).unwrap().custom, "no customWidth: not set by hand"); assert_eq!(s.rows.get(&0).unwrap().size, Some(40.0)); let r2 = s.rows.get(&1).unwrap(); assert!(r2.hidden); @@ -250,6 +252,27 @@ fn dxf_border_is_written_before_protection() { assert!(b.is_some() && p.is_some() && b < p, "{dx}"); } +/// Which stored widths were set by hand, as Excel 16.0 treats them when a number format makes a +/// number wider (#1077): only customWidth without bestFit keeps its width; the others widen. +#[test] +fn column_widths_set_by_hand() { + let body = r#" + + "#; + let (wb, _) = read_xlsx(&minimal(body, &[], "", "")).unwrap(); + let s = wb.sheet(0).unwrap(); + let custom: Vec = (0..5).map(|c| s.cols.get(&c).is_some_and(|i| i.custom)).collect(); + assert_eq!(custom, [false, true, false, false, true]); + assert_eq!(s.col_width(4), s.default_col_width, "E: the default width, but set by hand"); + // Written back the way Excel writes them. + let bytes = crate::write_xlsx(&wb).unwrap(); + let mut pkg = crate::package::Package::open(&bytes).unwrap(); + let sheet = pkg.read_xml("xl/worksheets/sheet1.xml").unwrap().unwrap(); + let flags: Vec<(bool, bool)> = + sheet.child("cols").unwrap().kids("col").map(|c| (c.flag("customWidth", false), c.flag("bestFit", false))).collect(); + assert_eq!(flags, [(true, true), (true, false), (true, true), (true, false)], "C and D are one run"); +} + #[test] fn strict_namespace_and_shared_strings() { let ct = super::CT; diff --git a/crates/xlsx/src/tests/roundtrip.rs b/crates/xlsx/src/tests/roundtrip.rs index 5b79438db..0f6611992 100644 --- a/crates/xlsx/src/tests/roundtrip.rs +++ b/crates/xlsx/src/tests/roundtrip.rs @@ -103,7 +103,8 @@ fn sample() -> Workbook { s.spill.insert(at("H3"), Value::Number(3.0)); s.cols.insert(0, LineInfo { size: Some(100.0), ..Default::default() }); - s.cols.insert(1, LineInfo { size: Some(100.0), ..Default::default() }); + // Column B was sized by hand (customWidth), A widened by itself; both come back as they were. + s.cols.insert(1, LineInfo { size: Some(100.0), custom: true, ..Default::default() }); s.cols.insert(3, LineInfo { hidden: true, outline: 1, ..Default::default() }); s.cols.insert(5, LineInfo { style: Some(money), ..Default::default() }); s.rows.insert(0, LineInfo { size: Some(30.0), ..Default::default() }); diff --git a/crates/xlsx/src/xls/mod.rs b/crates/xlsx/src/xls/mod.rs index ceaf3e26d..363715d5d 100644 --- a/crates/xlsx/src/xls/mod.rs +++ b/crates/xlsx/src/xls/mod.rs @@ -698,6 +698,7 @@ fn sheet_record(rec: &Record<'_>, st: &mut SheetState<'_>, budget: &mut Budget, } let mut info = LineInfo::default(); let px = col_width_to_px(f64::from(width) / 256.0); + info.custom = flags & 0x0002 != 0 && flags & 0x0004 == 0; // fUserSet without fBestFit if flags & 0x0002 != 0 || px != st.sheet.default_col_width { info.size = Some(px); } diff --git a/docs/decisions.md b/docs/decisions.md index 2aa18069f..d624f44c8 100644 --- a/docs/decisions.md +++ b/docs/decisions.md @@ -79,4 +79,32 @@ to 115% or 100%. That's a large relative step at low zoom and a small one near 4 relative steps keep each notch feeling the same, and the doublings land on 25, 50, 100, 200 and 400%. The status bar's Zoom In / Zoom Out buttons and Ctrl+Alt+= / Ctrl+Alt+- keep their 10% steps, so the wheel and the buttons now step differently. Whether they should share one ladder -(this one, Excel's, or another) is left to the maintainers. \ No newline at end of file +(this one, Excel's, or another) is left to the maintainers. +## Number formats widen columns that weren't sized by hand (#1077) + +Increase/Decrease Decimal and the ribbon's other number formats (the Number Format list, Accounting, +Percent, Comma) widen a column so the formatted numbers in the target fit, instead of showing `####`. +Microsoft's support article "Stop showing rounded numbers" says only that "the column width adjusts +automatically", so the rule comes from observing Excel 16.0 (build 17932, Windows) with synthetic +workbooks: + +- A column at the default width, AutoFitted, or widened this way before widens to the widest number + in the formatted range, also with Wrap Text and a large bold font. It never narrows. +- A width set with Column Width (or by dragging the border) stays, even when it equals the default: + the number shows `####`. AutoFit makes such a column automatic again. +- Hidden columns, text, General numbers (they round to fit instead), merged cells and shrink-to-fit + cells don't widen. +- In XLSX, Excel writes `customWidth="1"` for every width it stores and adds `bestFit="1"` for widths + that AutoFit or a number format set. Only `customWidth` without `bestFit` is read as set by hand: a + width with no flags, `bestFit` alone, or both, keeps widening after the file is opened again. + +`LineInfo::custom`, already used for rows set by hand, now marks columns set by hand too; GridCraft +writes and reads the two flags as Excel does (and `.xls` COLINFO's fUserSet and fBestFit alike). +Files that earlier GridCraft versions saved have `customWidth` without `bestFit` on every stored +width, so those columns open as set by hand and keep their width. + +The engine has no font metrics, so the width is the same estimate AutoFit Column Width uses, which +errs on the wide side; a UI test checks that the real font then draws the number, not `####`. +Excel also widens when a number format is set another way (observed through the `NumberFormat` +property, as Format Cells sets it); GridCraft's Format Cells doesn't yet. That, and typing a number +into a formatted cell, are left for later. diff --git a/docs/file-format-parity.md b/docs/file-format-parity.md index cf567f8bd..668f54c40 100644 --- a/docs/file-format-parity.md +++ b/docs/file-format-parity.md @@ -1,6 +1,6 @@ # File-format parity -> **Last reviewed:** 2026-10-11 · **Last updated:** 2026-10-21 · **Change:** minor (.xls dialog sheets are skipped instead of read as worksheets; `.xls` import reads each sheet's display options from WINDOW2: right-to-left, gridlines, headings, zeros, formulas; XLSX text boxes and shapes keep their paragraphs' right-to-left direction on save; CSV/TSV/TXT can open with every field kept as text via `file.open {csvAsText}`; formulas over Excel's 8,192 characters, and `%` or call chains past the nesting limit, are parse errors instead of stack overflows when a file is opened; XLSX PivotTables read and write `rowGrandTotals`/`colGrandTotals` the way Excel does, so a table saved with only one grand total opens with the right one; HTML export keeps right-to-left; CSV and text import detects likely Windows-1256 Arabic when invalid UTF-8 has Arabic byte runs; other invalid UTF-8 remains Windows-1252; HTML export places pictures and charts, as inline SVG, at their anchors) · **Target:** Microsoft Excel (Microsoft 365), Excel for Mac 16.113.4 +> **Last reviewed:** 2026-10-11 · **Last updated:** 2026-10-22 · **Change:** minor (XLSX and `.xls` column widths keep whether they were set by hand, so automatic ones still widen for wider number formats, #1077; .xls dialog sheets are skipped instead of read as worksheets; `.xls` import reads each sheet's display options from WINDOW2: right-to-left, gridlines, headings, zeros, formulas; XLSX text boxes and shapes keep their paragraphs' right-to-left direction on save; CSV/TSV/TXT can open with every field kept as text via `file.open {csvAsText}`; formulas over Excel's 8,192 characters, and `%` or call chains past the nesting limit, are parse errors instead of stack overflows when a file is opened; XLSX PivotTables read and write `rowGrandTotals`/`colGrandTotals` the way Excel does, so a table saved with only one grand total opens with the right one; HTML export keeps right-to-left; CSV and text import detects likely Windows-1256 Arabic when invalid UTF-8 has Arabic byte runs; other invalid UTF-8 remains Windows-1252; HTML export places pictures and charts, as inline SVG, at their anchors) · **Target:** Microsoft Excel (Microsoft 365), Excel for Mac 16.113.4 Every format Excel opens or saves, with GridCraft's read and write support, fidelity and tests. Part of [target-app-parity.md](target-app-parity.md). **File formats: ~50% ready, 80–120 h** @@ -110,6 +110,7 @@ refresh. Counted under features (Get & Transform, ~10% ready), not here. | Date | Change | Summary | |---|---|---| +| 2026-10-22 | minor | XLSX column widths: `customWidth` without `bestFit` is a width set by hand, others (AutoFit, widened by a number format) are automatic, as Excel 16.0 reads them; written the same way (`bestFit="1" customWidth="1"` for automatic widths). `.xls` reads COLINFO's fUserSet and fBestFit alike (#1077) | | 2026-10-21 | minor | HTML (Save as Web Page) writes pictures (`data:` URI ``) and charts (inline SVG from the chart crate's drawing primitives, text included) at their anchors; the table uses the sheet's column widths and row heights when the sheet has either, and output for sheets without pictures or charts is unchanged | | 2026-10-20 | trivial | XLSX shared strings: Japanese phonetic runs (ふりがな, `` with ``) are read into the workbook and written back next to the string with the same text, so an open + save no longer deletes them; bad offsets and readings are dropped with a warning, a `` without runs is kept on its own, and when duplicate `` items share a text but not a reading only the first reading is written (reported on open) (`phonetic_tests.rs`) | | 2026-10-20 | minor | A workbook theme's major/minor per-script typefaces (``, also Hebr, Jpan and the rest) are read and written back in file order after ``; they were dropped before. A hostile file is held to 64 entries of 256 characters | diff --git a/docs/ui-parity.md b/docs/ui-parity.md index 07797d70d..3ea4097d5 100644 --- a/docs/ui-parity.md +++ b/docs/ui-parity.md @@ -1,6 +1,6 @@ # UI parity -> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-10-21 · **Change:** minor (Esc and Enter close a data validation alert over the cell editor; Ctrl+Enter fill gives each cell the automatic number format typing gives it; keytip letters typed with Alt held, #1846; Number Stored as Text indicator and Convert to Number) · **Target:** Microsoft Excel (Microsoft 365), Excel for Mac 16.113.4 +> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-10-22 · **Change:** minor (ribbon number formats widen columns nobody sized by hand, #1077; Esc and Enter close a data validation alert over the cell editor; Ctrl+Enter fill gives each cell the automatic number format typing gives it; keytip letters typed with Alt held, #1846; Number Stored as Text indicator and Convert to Number) · **Target:** Microsoft Excel (Microsoft 365), Excel for Mac 16.113.4 Interaction, controls and feel, against Excel. Part of [target-app-parity.md](target-app-parity.md). **UI/UX fidelity: ~55% ready, 50–80 h** (estimated). Ribbon command coverage is measured @@ -176,6 +176,7 @@ scrollbar bugs 2–4 · pixel/feel pass against observed Excel 7–12. | Date | Change | Summary | |---|---|---| +| 2026-10-22 | minor | Increase/Decrease Decimal and the ribbon's other number formats (Number Format list, Accounting, Percent, Comma) widen a column nobody sized by hand so the numbers fit, instead of showing #### (#1077). As observed in Excel 16.0: AutoFit counts as automatic, Column Width or dragging the border as by hand; hidden columns, text, General numbers, merged and shrink-to-fit cells don't widen, and columns never narrow | | 2026-10-21 | minor | Background error checking, first part (#1994): a constant whose text would be a number if typed (signs, thousands, currency, percent, exponent, parenthesised negative) gets Excel's green corner triangle; the active cell then shows a warning button whose menu names the problem and offers Convert to Number for the selection (`formulas.convertToNumber`). Dates, times and fractions kept as text and formula results are not flagged, as in Excel | | 2026-10-21 | minor | Paste Special laid out as Excel's: Paste and Operation options each in two columns inside a frame, Skip blanks and Transpose side by side, Paste Link as a button that pastes references at once; labels translated (the generic form didn't translate them) and the window no longer runs past the screen | | 2026-10-21 | minor | Form dialogs (conditional-format quick rules, New Name, Remove Duplicates, Text to Columns and every other `Dialog::form`) fit their content: OK and Cancel sit in a row under the last field instead of a right-to-left layout that took the screen's whole height and left the buttons floating halfway down | From f30c206a05419bcf559542471e1f1503a61f3e00 Mon Sep 17 00:00:00 2001 From: Vedran Dobos <19259909+vedran-dobos@users.noreply.github.com> Date: Thu, 22 Oct 2026 15:20:40 +0200 Subject: [PATCH 2/5] Format: Format Cells' number formats widen columns too, as in Excel (#1077) Observed in Excel 16.0: a number format applied to a number widens a column not sized by hand, whether it comes from the ribbon or the NumberFormat property (as Format Cells sets it); a value entered into an already formatted cell doesn't. shrink_to_fit's #### case now sets its column's width by hand, as Excel would otherwise widen it. Co-Authored-By: Claude Opus 5.5 --- crates/engine/src/cmd/format.rs | 26 ++++++++++++++++++++++---- crates/ui-egui/tests/shrink_to_fit.rs | 2 ++ docs/decisions.md | 11 ++++++----- docs/ui-parity.md | 2 +- 4 files changed, 31 insertions(+), 10 deletions(-) diff --git a/crates/engine/src/cmd/format.rs b/crates/engine/src/cmd/format.rs index 2619f59bd..f6b92562c 100644 --- a/crates/engine/src/cmd/format.rs +++ b/crates/engine/src/cmd/format.rs @@ -528,7 +528,12 @@ fn format_cells(s: &mut Session, p: &Json) -> Result { { *st = new; } - }) + })?; + // A number format set here widens columns as the ribbon's do (observed: Excel 16.0). + if patch.get("num_fmt").is_some() { + widen_for_numbers(s, p)?; + } + ok() } /// The style patch with camelCase keys (`numFmt`, `diagDown`, as documented) renamed to the @@ -712,9 +717,9 @@ fn set_fmt(s: &mut Session, p: &Json, code: &str) -> Result { widen_for_numbers(s, p) } -/// After a number format from the ribbon (Increase Decimal, Comma Style, the Number Format list…), -/// a column nobody sized by hand widens so the formatted numbers in the target fit, instead of -/// showing ####. Observed in Excel 16.0 (build 17932): a column at the default width, AutoFitted, or +/// After a number format from the ribbon (Increase Decimal, Comma Style, the Number Format list…) or +/// Format Cells, a column nobody sized by hand widens so the formatted numbers in the target fit, +/// instead of showing ####. Observed in Excel 16.0 (build 17932): a column at the default width, AutoFitted, or /// widened this way before widens to the widest number in the range, also with Wrap Text and a large /// font. A width set with Column Width (or by dragging) stays, even when it equals the default. Hidden /// columns, text, General numbers (they round to fit), shrink-to-fit and merged cells don't widen, @@ -1375,6 +1380,19 @@ mod tests { assert!(col(&s, 0).0 > fitted, "after AutoFit, with Wrap Text, A widens again"); } + #[test] + fn format_cells_widens_for_a_number_format_only() { + let mut s = crate::Session::new(); + s.new_workbook(); + s.execute("range.setValues", json!({"range": "A1", "values": [[1234567.891, 1234567.891]]})).unwrap(); + let (default, _) = col(&s, 0); + s.execute("home.formatCells", json!({"range": "B1", "style": {"font": {"bold": true}}})).unwrap(); + assert_eq!(col(&s, 1).0, default, "no number format, no widening"); + s.execute("home.formatCells", json!({"range": "A1", "style": {"numFmt": "#,##0.000000"}})).unwrap(); + assert!(col(&s, 0).0 > default, "A widens for 1,234,567.891000, as Excel's Format Cells does"); + assert!(!col(&s, 0).1); + } + #[test] fn format_cells_takes_the_documented_keys() { let mut s = crate::Session::new(); diff --git a/crates/ui-egui/tests/shrink_to_fit.rs b/crates/ui-egui/tests/shrink_to_fit.rs index a9428fa23..2d17ca133 100644 --- a/crates/ui-egui/tests/shrink_to_fit.rs +++ b/crates/ui-egui/tests/shrink_to_fit.rs @@ -15,6 +15,8 @@ fn harness() -> Harness { s.execute("cell.set", json!({"cell": "A1", "input": "Executive Producer"})).unwrap(); s.execute("home.formatCells", json!({"range": "A1", "style": shrink})).unwrap(); s.execute("cell.set", json!({"cell": "A2", "input": "Control Producer"})).unwrap(); + // Column A's width set by hand (to the default), so the numbers formatted below keep it. + s.execute("home.columnWidth", json!({"cols": "A:A", "width": 64})).unwrap(); s.execute("cell.set", json!({"cell": "A4", "input": "123456789012"})).unwrap(); s.execute("home.formatCells", json!({"range": "A4", "style": {"num_fmt": "#,##0", "align": {"shrink": true}}})).unwrap(); s.execute("cell.set", json!({"cell": "A5", "input": "123456789012"})).unwrap(); diff --git a/docs/decisions.md b/docs/decisions.md index d624f44c8..153523040 100644 --- a/docs/decisions.md +++ b/docs/decisions.md @@ -82,8 +82,9 @@ steps, so the wheel and the buttons now step differently. Whether they should sh (this one, Excel's, or another) is left to the maintainers. ## Number formats widen columns that weren't sized by hand (#1077) -Increase/Decrease Decimal and the ribbon's other number formats (the Number Format list, Accounting, -Percent, Comma) widen a column so the formatted numbers in the target fit, instead of showing `####`. +Increase/Decrease Decimal, the ribbon's other number formats (the Number Format list, Accounting, +Percent, Comma) and a number format set in Format Cells widen a column so the formatted numbers in +the target fit, instead of showing `####`. Microsoft's support article "Stop showing rounded numbers" says only that "the column width adjusts automatically", so the rule comes from observing Excel 16.0 (build 17932, Windows) with synthetic workbooks: @@ -105,6 +106,6 @@ width, so those columns open as set by hand and keep their width. The engine has no font metrics, so the width is the same estimate AutoFit Column Width uses, which errs on the wide side; a UI test checks that the real font then draws the number, not `####`. -Excel also widens when a number format is set another way (observed through the `NumberFormat` -property, as Format Cells sets it); GridCraft's Format Cells doesn't yet. That, and typing a number -into a formatted cell, are left for later. +Excel doesn't widen when a value is entered into a cell that already has the format (observed through +the `Value` property: the cell shows `####`), and neither does GridCraft. Typing into such a cell +wasn't observed. diff --git a/docs/ui-parity.md b/docs/ui-parity.md index 3ea4097d5..bb02254f5 100644 --- a/docs/ui-parity.md +++ b/docs/ui-parity.md @@ -176,7 +176,7 @@ scrollbar bugs 2–4 · pixel/feel pass against observed Excel 7–12. | Date | Change | Summary | |---|---|---| -| 2026-10-22 | minor | Increase/Decrease Decimal and the ribbon's other number formats (Number Format list, Accounting, Percent, Comma) widen a column nobody sized by hand so the numbers fit, instead of showing #### (#1077). As observed in Excel 16.0: AutoFit counts as automatic, Column Width or dragging the border as by hand; hidden columns, text, General numbers, merged and shrink-to-fit cells don't widen, and columns never narrow | +| 2026-10-22 | minor | Increase/Decrease Decimal, the ribbon's other number formats (Number Format list, Accounting, Percent, Comma) and Format Cells' number formats widen a column nobody sized by hand so the numbers fit, instead of showing #### (#1077). As observed in Excel 16.0: AutoFit counts as automatic, Column Width or dragging the border as by hand; hidden columns, text, General numbers, merged and shrink-to-fit cells don't widen, and columns never narrow | | 2026-10-21 | minor | Background error checking, first part (#1994): a constant whose text would be a number if typed (signs, thousands, currency, percent, exponent, parenthesised negative) gets Excel's green corner triangle; the active cell then shows a warning button whose menu names the problem and offers Convert to Number for the selection (`formulas.convertToNumber`). Dates, times and fractions kept as text and formula results are not flagged, as in Excel | | 2026-10-21 | minor | Paste Special laid out as Excel's: Paste and Operation options each in two columns inside a frame, Skip blanks and Transpose side by side, Paste Link as a button that pastes references at once; labels translated (the generic form didn't translate them) and the window no longer runs past the screen | | 2026-10-21 | minor | Form dialogs (conditional-format quick rules, New Name, Remove Duplicates, Text to Columns and every other `Dialog::form`) fit their content: OK and Cancel sit in a row under the last field instead of a right-to-left layout that took the screen's whole height and left the buttons floating halfway down | From 6ce1ce9c6d4919a8c3588bedf6b95fa214893162 Mon Sep 17 00:00:00 2001 From: Vedran Dobos <19259909+vedran-dobos@users.noreply.github.com> Date: Thu, 22 Oct 2026 23:20:08 +0200 Subject: [PATCH 3/5] Format: widening looks at the target's stored cells and spills, and indexes its merges (#1077) Review of #2271. A target over 4,000,000 positions was skipped whole, so whole columns with a number a million rows down didn't widen: the stored cells looked at are capped instead (1,000,000). Spilled numbers are measured as the grid shows them; before, a spill child's empty stored cell hid its number. Merged areas are checked through per-column row intervals built once per command, not a scan of every merge for every number. Co-Authored-By: Claude Opus 5.5 --- crates/engine/src/cmd/format.rs | 80 ++++++++++++++++++++++++++++++--- 1 file changed, 73 insertions(+), 7 deletions(-) diff --git a/crates/engine/src/cmd/format.rs b/crates/engine/src/cmd/format.rs index f6b92562c..ad089f1df 100644 --- a/crates/engine/src/cmd/format.rs +++ b/crates/engine/src/cmd/format.rs @@ -724,6 +724,9 @@ fn set_fmt(s: &mut Session, p: &Json, code: &str) -> Result { /// font. A width set with Column Width (or by dragging) stays, even when it equals the default. Hidden /// columns, text, General numbers (they round to fit), shrink-to-fit and merged cells don't widen, /// and columns never narrow. +/// How many stored cells [`widen_for_numbers`] looks at in one command. +const MAX_WIDEN_CELLS: usize = 1_000_000; + fn widen_for_numbers(s: &mut Session, p: &Json) -> Result { let sheet = target_sheet(s, p)?; let ranges = target_ranges(s, p)?; @@ -734,17 +737,43 @@ fn widen_for_numbers(s: &mut Session, p: &Json) -> Result { if sh.show_formulas { return Ok(Json::Null); } + let targets: Vec = ranges.iter().filter_map(|r| r.intersection(&used)).collect(); + // Merged areas over the targets as sorted row intervals per column, so each cell is checked + // with a binary search rather than a scan of every merge. + let mut merged: std::collections::HashMap> = Default::default(); + for m in sh.merges.iter().filter(|m| !m.is_single()) { + for x in targets.iter().filter_map(|r| m.intersection(r)) { + for col in x.start.col..=x.end.col { + merged.entry(col).or_default().push((m.start.row, m.end.row)); + } + } + } + for v in merged.values_mut() { + v.sort_unstable(); + v.dedup(); + } + let in_merge = |c: CellRef| { + merged.get(&c.col).is_some_and(|v| { + let i = v.partition_point(|&(r0, _)| r0 <= c.row); + i > 0 && v.get(i - 1).is_some_and(|&(_, r1)| c.row <= r1) + }) + }; let mut need: std::collections::BTreeMap = std::collections::BTreeMap::new(); // Measured as AutoFit Column Width measures (the UI's font when it supplies one). let mut measured: std::collections::HashMap<(StyleId, String), f32> = Default::default(); - for r in ranges.iter().filter_map(|r| r.intersection(&used)) { - if r.count() > 4_000_000 { - continue; - } - for (c, cell) in sh.cells.iter_range(r) { - if !matches!(cell.value, gridcraft_core::Value::Number(_)) + // The stored cells looked at are capped, not the area: a sparse target as tall as the sheet + // still widens for the numbers it holds. Spilled values count as the grid shows them. + let mut budget = MAX_WIDEN_CELLS; + for r in &targets { + let spilled = sh.spill.range(r.start..=r.end).map(|(c, _)| *c).filter(|c| r.contains(*c)); + for c in sh.cells.iter_range(*r).map(|(c, _)| c).chain(spilled) { + if budget == 0 { + break; + } + budget -= 1; + if !matches!(sh.value_ref(c), Some(gridcraft_core::Value::Number(_))) || sh.cols.get(&c.col).is_some_and(|i| i.custom || i.hidden) - || sh.merge_at(c).is_some_and(|m| !m.is_single()) + || in_merge(c) { continue; } @@ -1380,6 +1409,43 @@ mod tests { assert!(col(&s, 0).0 > fitted, "after AutoFit, with Wrap Text, A widens again"); } + fn book() -> (crate::Session, f32) { + let mut s = crate::Session::new(); + s.new_workbook(); + let (default, _) = col(&s, 0); + (s, default) + } + + /// Whole columns as tall as the sheet with two numbers: the cells are looked at, not the area. + #[test] + fn a_sparse_target_widens_for_the_numbers_it_holds() { + let (mut s, default) = book(); + s.execute("cell.set", json!({"cell": "A1", "input": "1"})).unwrap(); + s.execute("cell.set", json!({"cell": "E1000000", "input": "1234567.891"})).unwrap(); + s.execute("home.comma", json!({"range": "A:E"})).unwrap(); + assert!(col(&s, 4).0 > default, "E widens for 1,234,567.89 a million rows down"); + } + + /// A spilled number counts as the grid shows it: G1's formula spills 1,234,567.891 into H1. + #[test] + fn a_spilled_number_widens_its_column() { + let (mut s, default) = book(); + s.execute("cell.set", json!({"cell": "G1", "input": "=SEQUENCE(1,2,1,1234566.891)"})).unwrap(); + s.execute("home.numberFormat", json!({"range": "H1", "code": "#,##0.000"})).unwrap(); + assert!(col(&s, 7).0 > default, "H widens for the value it shows"); + } + + /// A merged area keeps its columns; the cell beside it widens. + #[test] + fn a_merged_area_keeps_its_columns() { + let (mut s, default) = book(); + s.execute("range.setValues", json!({"range": "J1", "values": [[1234567.891, null, 1234567.891]]})).unwrap(); + s.execute("home.mergeCells", json!({"range": "J1:K1"})).unwrap(); + s.execute("home.comma", json!({"range": "J1:L1"})).unwrap(); + assert_eq!((col(&s, 9).0, col(&s, 10).0), (default, default), "the merged J1:K1 doesn't widen J or K"); + assert!(col(&s, 11).0 > default, "L does"); + } + #[test] fn format_cells_widens_for_a_number_format_only() { let mut s = crate::Session::new(); From 62899818bee324e823dcffdae42450b45af619fc Mon Sep 17 00:00:00 2001 From: Vedran Dobos <19259909+vedran-dobos@users.noreply.github.com> Date: Thu, 5 Nov 2026 21:55:16 +0100 Subject: [PATCH 4/5] Model: restore the ellipsis in LineInfo::custom's doc comment Garbled into three characters when it moved to features/print.rs in the merge of main. Co-Authored-By: Claude Opus 5.5 --- crates/model/src/features/print.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/crates/model/src/features/print.rs b/crates/model/src/features/print.rs index 5113063dd..7bbdd2e54 100644 --- a/crates/model/src/features/print.rs +++ b/crates/model/src/features/print.rs @@ -253,7 +253,7 @@ pub struct LineInfo { pub collapsed: bool, pub style: Option, /// The size was set by the user. Rows without it follow their content's height; columns - /// without it widen when a number format makes their numbers wider (`home.increaseDecimal`…). + /// without it widen when a number format makes their numbers wider (`home.increaseDecimal`…). #[serde(default)] pub custom: bool, } From 111fc70b7502d8aa0db193884391cdc730f44963 Mon Sep 17 00:00:00 2001 From: Vedran Dobos <19259909+vedran-dobos@users.noreply.github.com> Date: Sun, 15 Nov 2026 14:22:36 +0100 Subject: [PATCH 5/5] XLS: COLINFO's fUserSet marks a column width set by hand (#1077) Main now reads .xls with the shared craft-xls crate, which reports fUserSet but not fBestFit. A test covers fUserSet, no flags, and both flags; the docs say what the .xls reader can tell apart. Co-Authored-By: Claude Opus 5.5 --- crates/xlsx/src/tests/xls_tests.rs | 13 +++++++++++++ crates/xlsx/src/xls.rs | 1 - docs/decisions.md | 4 +++- docs/file-format-parity.md | 2 +- 4 files changed, 17 insertions(+), 3 deletions(-) diff --git a/crates/xlsx/src/tests/xls_tests.rs b/crates/xlsx/src/tests/xls_tests.rs index 84189e674..bdc167e3c 100644 --- a/crates/xlsx/src/tests/xls_tests.rs +++ b/crates/xlsx/src/tests/xls_tests.rs @@ -794,6 +794,19 @@ fn xls_window2_right_to_left_sheet_opens_right_to_left() { assert_eq!(view(&one_sheet_with(&window2(0x0001 | 0x0002 | 0x0010))), (false, true, false, true, true)); } +/// COLINFO's fUserSet marks a width set by hand, which a wider number format leaves alone (#1077). +/// craft-xls does not report fBestFit, so fUserSet with fBestFit also reads as set by hand. +#[test] +fn xls_column_widths_set_by_hand() { + let colinfo = |col: u16, flags: u16| rec(0x007D, &u16s(&[col, col, 20 * 256, 0, flags, 0])); + let file = one_sheet_with(&cat(&[&colinfo(0, 0x0002), &colinfo(1, 0), &colinfo(2, 0x0006)])); + let (wb, _) = read_xls(&file).unwrap(); + let sh = &wb.sheets[0]; + let custom: Vec = (0..3).map(|c| sh.cols.get(&c).is_some_and(|i| i.custom)).collect(); + assert_eq!(custom, [true, false, true]); + assert!((0..3).all(|c| sh.col_width(c) > sh.default_col_width), "all three keep their stored width"); +} + #[test] fn xls_short_window2_is_ignored() { for payload in [&[][..], &[0x40][..], &[0x40, 0][..], &[0x40, 0, 0, 0, 0, 0, 0, 0, 0][..]] { diff --git a/crates/xlsx/src/xls.rs b/crates/xlsx/src/xls.rs index cf61b8cfd..61c054035 100644 --- a/crates/xlsx/src/xls.rs +++ b/crates/xlsx/src/xls.rs @@ -234,7 +234,6 @@ fn sheet_of(s: &x::Sheet, styles: &[StyleId], unparsed: &mut bool) -> Sheet { outline: c.outline, collapsed: c.collapsed, style: c.format.map(|f| style(Some(f))).filter(|&id| id != StyleId::DEFAULT), - ..LineInfo::default() }; if info != LineInfo::default() { sheet.cols.insert(u32::from(col), info); diff --git a/docs/decisions.md b/docs/decisions.md index 741f9495b..2440e3416 100644 --- a/docs/decisions.md +++ b/docs/decisions.md @@ -148,7 +148,9 @@ workbooks: width with no flags, `bestFit` alone, or both, keeps widening after the file is opened again. `LineInfo::custom`, already used for rows set by hand, now marks columns set by hand too; GridCraft -writes and reads the two flags as Excel does (and `.xls` COLINFO's fUserSet and fBestFit alike). +writes and reads the two flags as Excel does. In `.xls`, COLINFO's fUserSet marks a column set by +hand; the shared craft-xls reader does not report fBestFit, so a `.xls` width with both flags also +counts as set by hand. Files that earlier GridCraft versions saved have `customWidth` without `bestFit` on every stored width, so those columns open as set by hand and keep their width. diff --git a/docs/file-format-parity.md b/docs/file-format-parity.md index 3daa5a4d2..102f64f98 100644 --- a/docs/file-format-parity.md +++ b/docs/file-format-parity.md @@ -186,7 +186,7 @@ refresh. Counted under features (Get & Transform, ~10% ready), not here. | 2026-10-31 | minor | CSV and text open detects each column's date order: a value that reads only day first (`31/05/2026`) makes the column day first, a value that reads only month first (`12/31/2026`) makes it month first, an all-ambiguous column keeps month first with a warning, and a column with both kinds stays text with a warning (#2765) | | 2026-10-31 | minor | XLSX open reads Google Sheets' `IFERROR(__xludf.DUMMYFUNCTION("…"),cached)` export wrapper as the formula inside when GridCraft calculates every function in it (plain, shared and array formulas, whole or nested; Google-only functions and unparseable, over-long or over-deep inner text keep the wrapper and the cached value) and keeps the cached value; saving writes the real formula with Excel's `_xlfn.` prefixes (#2871) | | 2026-10-26 | minor | Alignment readingOrder 0/1/2 survives cell, named-style and differential-style round-trips; Format Cells exposes reading direction and CF priority preserves unspecified inheritance | -| 2026-10-22 | minor | XLSX column widths: `customWidth` without `bestFit` is a width set by hand, others (AutoFit, widened by a number format) are automatic, as Excel 16.0 reads them; written the same way (`bestFit="1" customWidth="1"` for automatic widths). `.xls` reads COLINFO's fUserSet and fBestFit alike (#1077) | +| 2026-10-22 | minor | XLSX column widths: `customWidth` without `bestFit` is a width set by hand, others (AutoFit, widened by a number format) are automatic, as Excel 16.0 reads them; written the same way (`bestFit="1" customWidth="1"` for automatic widths). `.xls` reads COLINFO's fUserSet as set by hand (the shared craft-xls reader does not report fBestFit) (#1077) | | 2026-10-21 | minor | HTML (Save as Web Page) writes pictures (`data:` URI ``) and charts (inline SVG from the chart crate's drawing primitives, text included) at their anchors; the table uses the sheet's column widths and row heights when the sheet has either, and output for sheets without pictures or charts is unchanged | | 2026-10-20 | trivial | XLSX shared strings: Japanese phonetic runs (ふりがな, `` with ``) are read into the workbook and written back next to the string with the same text, so an open + save no longer deletes them; bad offsets and readings are dropped with a warning, a `` without runs is kept on its own, and when duplicate `` items share a text but not a reading only the first reading is written (reported on open) (`phonetic_tests.rs`) | | 2026-10-20 | minor | A workbook theme's major/minor per-script typefaces (``, also Hebr, Jpan and the rest) are read and written back in file order after ``; they were dropped before. A hostile file is held to 64 entries of 256 characters |