diff --git a/crates/engine/src/cmd/format.rs b/crates/engine/src/cmd/format.rs index a5c79bbf9..aeaf7866d 100644 --- a/crates/engine/src/cmd/format.rs +++ b/crates/engine/src/cmd/format.rs @@ -553,7 +553,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 @@ -732,9 +737,95 @@ fn number_format(s: &mut Session, p: &Json) -> Result { set_fmt(s, p, &code) } +/// How many stored cells [`widen_for_numbers`] looks at in one command. +const MAX_WIDEN_CELLS: usize = 1_000_000; + 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…) 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, +/// 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 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(); + // 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) + || in_merge(c) + { + 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). @@ -819,8 +910,8 @@ mod sizes; use cell_styles::cell_style; pub use cell_styles::{CELL_STYLE_NAMES, builtin_cell_style}; +use sizes::{EXACT_TEXT_WIDTHS, autofit_cols, autofit_rows, col_width, default_width, hide, row_height}; pub use sizes::{approx_text_width, chars_to_points}; -use sizes::{autofit_cols, autofit_rows, col_width, default_width, hide, row_height}; #[cfg(test)] mod tests { @@ -856,6 +947,112 @@ 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"); + } + + 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(); + 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/engine/src/cmd/format/sizes.rs b/crates/engine/src/cmd/format/sizes.rs index 5a4ba863a..cfbb548cb 100644 --- a/crates/engine/src/cmd/format/sizes.rs +++ b/crates/engine/src/cmd/format/sizes.rs @@ -107,6 +107,7 @@ pub(super) 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) @@ -187,7 +188,7 @@ fn arabic_em(c: char) -> Option { /// Distinct texts AutoFit measures exactly; past this many, `Session::text_width` is asked for a /// quick measure so a huge column doesn't lay out every value. -const EXACT_TEXT_WIDTHS: usize = 2_000; +pub(super) const EXACT_TEXT_WIDTHS: usize = 2_000; pub(super) fn autofit_cols(s: &mut Session, p: &Json) -> Result { let (si, lines) = line_targets(s, p, false)?; @@ -258,6 +259,7 @@ pub(super) 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) }) diff --git a/crates/model/src/features/print.rs b/crates/model/src/features/print.rs index bbceaecff..755df94e9 100644 --- a/crates/model/src/features/print.rs +++ b/crates/model/src/features/print.rs @@ -258,7 +258,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/it/interaction.rs b/crates/ui-egui/tests/it/interaction.rs index 71bdd6ae5..3bc51f888 100644 --- a/crates/ui-egui/tests/it/interaction.rs +++ b/crates/ui-egui/tests/it/interaction.rs @@ -1663,6 +1663,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/ui-egui/tests/it/shrink_to_fit.rs b/crates/ui-egui/tests/it/shrink_to_fit.rs index e3eee09f1..69dc5f2d7 100644 --- a/crates/ui-egui/tests/it/shrink_to_fit.rs +++ b/crates/ui-egui/tests/it/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/crates/xlsx/src/sheet_read.rs b/crates/xlsx/src/sheet_read.rs index daca3d1c9..28c3270ca 100644 --- a/crates/xlsx/src/sheet_read.rs +++ b/crates/xlsx/src/sheet_read.rs @@ -426,6 +426,7 @@ struct RawCol { max: u32, width: Option, custom_width: bool, + best_fit: bool, hidden: bool, outline_level: u8, collapsed: bool, @@ -441,6 +442,9 @@ fn apply_col_entry(cx: &Ctx<'_>, c: RawCol, remaining: &mut u64, sheet: &mut She let mut info = LineInfo::default(); if let Some(w) = c.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.custom_width && !c.best_fit; if c.custom_width || px != sheet.default_col_width { info.size = Some(px); } @@ -474,6 +478,7 @@ fn apply_craft_cols(cx: &Ctx<'_>, cols: &[craft_xlsx::Column], sheet: &mut Sheet max: c.last + 1, width: c.width, custom_width: c.custom_width, + best_fit: c.best_fit, hidden: c.hidden, outline_level: c.outline_level, collapsed: c.collapsed, @@ -497,6 +502,7 @@ fn apply_xml_cols(cx: &Ctx<'_>, sp: &CraftSheetPart, sheet: &mut Sheet) -> Resul max: c.attr_u32("max").unwrap_or(0), width: c.attr_f64("width"), custom_width: c.flag("customWidth", false), + best_fit: c.flag("bestFit", false), hidden: c.flag("hidden", false), outline_level: c.attr_u32("outlineLevel").unwrap_or(0).min(7) as u8, collapsed: c.flag("collapsed", false), diff --git a/crates/xlsx/src/sheet_write.rs b/crates/xlsx/src/sheet_write.rs index 4962dd1e4..c21b70376 100644 --- a/crates/xlsx/src/sheet_write.rs +++ b/crates/xlsx/src/sheet_write.rs @@ -239,8 +239,10 @@ fn build_craft_cols(sheet: &Sheet, sid: &dyn Fn(gridcraft_model::StyleId) -> u32 first: a, last: b, width: Some(px_to_col_width(w)), + // 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. custom_width: i.size.is_some(), - best_fit: false, + best_fit: i.size.is_some() && !i.custom, hidden: i.hidden, outline_level: i.outline.min(7), collapsed: i.collapsed, diff --git a/crates/xlsx/src/tests/fixtures.rs b/crates/xlsx/src/tests/fixtures.rs index 90a71bcfe..703878f48 100644 --- a/crates/xlsx/src/tests/fixtures.rs +++ b/crates/xlsx/src/tests/fixtures.rs @@ -181,7 +181,9 @@ fn assert_sheet_settings(s: &gridcraft_model::Sheet) { 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); @@ -294,6 +296,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 05137bd16..ca6b7093e 100644 --- a/crates/xlsx/src/tests/roundtrip.rs +++ b/crates/xlsx/src/tests/roundtrip.rs @@ -112,7 +112,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/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 919b1c01f..dbb27534c 100644 --- a/crates/xlsx/src/xls.rs +++ b/crates/xlsx/src/xls.rs @@ -227,11 +227,13 @@ fn sheet_of(s: &x::Sheet, styles: &[StyleId], unparsed: &mut bool) -> Sheet { let px = col_width_to_px(f64::from(c.width) / 256.0); let info = LineInfo { size: (c.custom_width || px != sheet.default_col_width).then_some(px), + // fUserSet. craft-xls does not expose fBestFit, so a width AutoFit stored with both + // flags also counts as set by hand here (#1077). + custom: c.custom_width, hidden: c.hidden, 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 0eea97675..2440e3416 100644 --- a/docs/decisions.md +++ b/docs/decisions.md @@ -127,3 +127,35 @@ so there the caps and the fuzzed input space are the protection. `crates/math/te gate on every test run, so a version bump has to pass it. RaTeX positions glyphs with KaTeX font metrics; GridCraft never bundles the KaTeX fonts, so glyphs are drawn with system fonts and a glyph no font has is drawn as a `[?]` box. + +## Number formats widen columns that weren't sized by hand (#1077) + +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: + +- 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. 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. + +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 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/file-format-parity.md b/docs/file-format-parity.md index 1b4dda1f2..253fe1d73 100644 --- a/docs/file-format-parity.md +++ b/docs/file-format-parity.md @@ -1,6 +1,6 @@ # File-format parity -> **Last reviewed:** 2026-11-01 · **Last updated:** 2026-11-14 · **Change:** minor (a protection password set in GridCraft keeps both its XLSX form and the SHA-256 digest OpenDocument stores; earlier: the style model keeps a cell's padding, for OpenDocument; XLSX and XLS have none, so they read none and the XLSX writer leaves it out; not drawn yet; earlier: XLSX fonts keep outlined letters, ``, through open and save; GridCraft draws them solid; earlier: PDF honours cell reading direction and mirrors right-to-left sheets; earlier: Arabic PDF export no longer fails when a character or the Arabic font is missing; earlier: Arabic PDF text is shaped with embedded Noto Arabic glyphs beside the non-embedded standard, Symbol and CID fonts; earlier: .xls data validation is read; earlier: .xls is read by the shared craft-xls crate: the workbook opens on the sheet it was saved on, and rich-text (RString) cells are read; earlier: form controls: buttons, scroll bars and spin buttons read and written; earlier: a web page's first table opens as a sheet, also when the page is named `.xls`; earlier: `workbookPr filterPrivacy` kept, and honoured on save; earlier: a workbook's R1C1 reference style, `calcPr refMode`, is kept through open and save; earlier: XLSX page margins are written as their decimals, `0.3` rather than `0.30000001192092896`; earlier: Python cells in `.xlsx` as [MS-XLSX] specifies, `_xlfn._xlws.PY(…)` naming code in the Python part, with cached values, and in GridCraft JSON, with limits on open; earlier: equations in xlsx as Office Math with a marker in `descr` so an edit made in Excel reads back, read back only up to the equation source cap, and a brace with a label and a script on its other side keeps both; Symbol font in PDF; earlier: XLSX reads and writes Page Setup's page order, `pageSetup pageOrder`, and PDF export follows it; earlier: chart data tables: native c:dTable import/export; earlier: XLSX workbook-view selection, normalized tab ratios and sheet-edit regressions; fidelity estimates unchanged; earlier: formulas from Google Sheets' XLSX export open as the original formula instead of `IFERROR(__xludf.DUMMYFUNCTION(…),…)` when GridCraft calculates every function in it, and save as it; `file.exportCsv {values: true}` writes raw values for automation; .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; earlier: `file.exportCsv {values: true}` writes raw values for automation; .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; CSV and text open detects each column's date order from values that read only one way, warns when every date is ambiguous, and keeps a column with both kinds as text (#2765)) · **Target:** Microsoft Excel (Microsoft 365), Excel for Mac 16.113.4 +> **Last reviewed:** 2026-11-01 · **Last updated:** 2026-11-14 · **Change:** minor (XLSX and `.xls` column widths keep whether they were set by hand, so automatic ones still widen for wider number formats, #1077; earlier: a protection password set in GridCraft keeps both its XLSX form and the SHA-256 digest OpenDocument stores; earlier: the style model keeps a cell's padding, for OpenDocument; XLSX and XLS have none, so they read none and the XLSX writer leaves it out; not drawn yet; earlier: XLSX fonts keep outlined letters, ``, through open and save; GridCraft draws them solid; earlier: PDF honours cell reading direction and mirrors right-to-left sheets; earlier: Arabic PDF export no longer fails when a character or the Arabic font is missing; earlier: Arabic PDF text is shaped with embedded Noto Arabic glyphs beside the non-embedded standard, Symbol and CID fonts; earlier: .xls data validation is read; earlier: .xls is read by the shared craft-xls crate: the workbook opens on the sheet it was saved on, and rich-text (RString) cells are read; earlier: form controls: buttons, scroll bars and spin buttons read and written; earlier: a web page's first table opens as a sheet, also when the page is named `.xls`; earlier: `workbookPr filterPrivacy` kept, and honoured on save; earlier: a workbook's R1C1 reference style, `calcPr refMode`, is kept through open and save; earlier: XLSX page margins are written as their decimals, `0.3` rather than `0.30000001192092896`; earlier: Python cells in `.xlsx` as [MS-XLSX] specifies, `_xlfn._xlws.PY(…)` naming code in the Python part, with cached values, and in GridCraft JSON, with limits on open; earlier: equations in xlsx as Office Math with a marker in `descr` so an edit made in Excel reads back, read back only up to the equation source cap, and a brace with a label and a script on its other side keeps both; Symbol font in PDF; earlier: XLSX reads and writes Page Setup's page order, `pageSetup pageOrder`, and PDF export follows it; earlier: chart data tables: native c:dTable import/export; earlier: XLSX workbook-view selection, normalized tab ratios and sheet-edit regressions; fidelity estimates unchanged; earlier: formulas from Google Sheets' XLSX export open as the original formula instead of `IFERROR(__xludf.DUMMYFUNCTION(…),…)` when GridCraft calculates every function in it, and save as it; `file.exportCsv {values: true}` writes raw values for automation; .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; earlier: `file.exportCsv {values: true}` writes raw values for automation; .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; CSV and text open detects each column's date order from values that read only one way, warns when every date is ambiguous, and keeps a column with both kinds as text (#2765)) · **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** @@ -194,6 +194,7 @@ refresh. Counted under features (Get & Transform, ~10% ready), not here. | 2026-10-26 | minor | PDF honors cell Context/LTR/RTL, preserves paragraph direction across wrapping, and mirrors RTL sheet geometry without reversing glyphs | | 2026-10-26 | minor | Arabic PDF export embeds licensed glyph outlines, joins letters and marks, preserves logical text and reports unsupported glyphs before writing; Arabic runs take the embedded faces ahead of the CJK CID font, and CJK inside Arabic text is set in the CID font instead of failing the export | | 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 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 | diff --git a/docs/ui-parity.md b/docs/ui-parity.md index e2233785e..062dd1f07 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-11-19 · **Change:** minor (a leading + or - starts a formula, #2023; earlier: AutoSum on one cell proposes its range in the editor, #1834; earlier: Quick Analysis, Ctrl+Q (#791); earlier: validation list rows keep to their slot height whatever the font, and the "More entries not shown" note is translated; earlier: the searched validation list shows its eight rows, keeps the highlight in view and opens above a cell near the bottom of the window; earlier: the dropdown arrow's full list reads its source once within the same budget, draws only its visible rows and shows eight of them; earlier: a searched validation list reads at most 200,000 cells of its source; earlier: Find and Replace keeps workbook Undo/Redo available while a button has keyboard focus; text fields keep their own Undo; earlier: punctuation shortcuts follow the keyboard layout's characters; earlier: preserve centered emoji and symbol fallback placement; earlier: preserve leading and trailing blank cell lines; earlier: align wrapped and unwrapped cells; earlier: CJK title baseline regression and mixed-script rendering validation; earlier: form controls: buttons, sliders and spin buttons on the sheet; earlier: Highlight the active cell's row, a global preference in File › Options › General; earlier: a linked cell's menu edits, opens or removes the link; earlier: Display options for this workbook: sheet tabs and scroll bars; earlier: dragging over row or column headers in point mode extends the reference; earlier: a picture on the system clipboard pastes as a floating picture at the active cell with Cmd/Ctrl+V or Paste (#699); earlier: frozen columns keep their text, gridlines and merged borders whole while the sheet scrolls (#2544); earlier: every Paste Special option has its access key; earlier: the Draw tab's live stroke preview uses the pen's colour and thickness; earlier: copy quotes only cells with a tab or line break, as Excel does; earlier: Ctrl+. Next Corner of Selection; earlier: dragging the selection's border onto data asks before replacing it; earlier: RefEdit reference boxes in dialogs: Goal Seek, Solver and Data Analysis use them, the arrow keys select while a dialog is collapsed and F4 cycles a reference's anchors; earlier: Python cells: Python mode in the formula bar; earlier: Insert › Equation and the equation editor; earlier: every floating object selects, resizes from eight handles and deletes with the keyboard; earlier: Formulas › Error Checking › Trace Error; trace arrows stay through a zoom (#3097); earlier: Page Setup sets the page order, Down, then over or Over, then down, which printing, the print preview, Page Break Preview and Page Layout view follow; earlier: Formulas › Function Library as labelled buttons with category menus; Recently Used and the Insert Function categories; Esc leaves a File-page text field before closing the view; earlier: checkbox cells print as boxes; Ctrl+arrow and Ctrl+Shift+arrow while pointing a formula reference; editing a hyperlink loads its existing fields; AutoSum over a selected row puts its total to the right; ribbon catalog count 276 / 292; earlier: typing into a cell with a list validation searches its dropdown; Enter/Tab take the highlighted entry) · **Target:** Microsoft Excel (Microsoft 365), Excel for Mac 16.113.4 +> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-11-19 · **Change:** minor (ribbon number formats widen columns nobody sized by hand, #1077; earlier: a leading + or - starts a formula, #2023; earlier: AutoSum on one cell proposes its range in the editor, #1834; earlier: Quick Analysis, Ctrl+Q (#791); earlier: validation list rows keep to their slot height whatever the font, and the "More entries not shown" note is translated; earlier: the searched validation list shows its eight rows, keeps the highlight in view and opens above a cell near the bottom of the window; earlier: the dropdown arrow's full list reads its source once within the same budget, draws only its visible rows and shows eight of them; earlier: a searched validation list reads at most 200,000 cells of its source; earlier: Find and Replace keeps workbook Undo/Redo available while a button has keyboard focus; text fields keep their own Undo; earlier: punctuation shortcuts follow the keyboard layout's characters; earlier: preserve centered emoji and symbol fallback placement; earlier: preserve leading and trailing blank cell lines; earlier: align wrapped and unwrapped cells; earlier: CJK title baseline regression and mixed-script rendering validation; earlier: form controls: buttons, sliders and spin buttons on the sheet; earlier: Highlight the active cell's row, a global preference in File › Options › General; earlier: a linked cell's menu edits, opens or removes the link; earlier: Display options for this workbook: sheet tabs and scroll bars; earlier: dragging over row or column headers in point mode extends the reference; earlier: a picture on the system clipboard pastes as a floating picture at the active cell with Cmd/Ctrl+V or Paste (#699); earlier: frozen columns keep their text, gridlines and merged borders whole while the sheet scrolls (#2544); earlier: every Paste Special option has its access key; earlier: the Draw tab's live stroke preview uses the pen's colour and thickness; earlier: copy quotes only cells with a tab or line break, as Excel does; earlier: Ctrl+. Next Corner of Selection; earlier: dragging the selection's border onto data asks before replacing it; earlier: RefEdit reference boxes in dialogs: Goal Seek, Solver and Data Analysis use them, the arrow keys select while a dialog is collapsed and F4 cycles a reference's anchors; earlier: Python cells: Python mode in the formula bar; earlier: Insert › Equation and the equation editor; earlier: every floating object selects, resizes from eight handles and deletes with the keyboard; earlier: Formulas › Error Checking › Trace Error; trace arrows stay through a zoom (#3097); earlier: Page Setup sets the page order, Down, then over or Over, then down, which printing, the print preview, Page Break Preview and Page Layout view follow; earlier: Formulas › Function Library as labelled buttons with category menus; Recently Used and the Insert Function categories; Esc leaves a File-page text field before closing the view; earlier: checkbox cells print as boxes; Ctrl+arrow and Ctrl+Shift+arrow while pointing a formula reference; editing a hyperlink loads its existing fields; AutoSum over a selected row puts its total to the right; ribbon catalog count 276 / 292; earlier: typing into a cell with a list validation searches its dropdown; Enter/Tab take the highlighted entry) · **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 @@ -338,6 +338,7 @@ scrollbar bugs 2–4 · pixel/feel pass against observed Excel 7–12. | 2026-10-22 | minor | One native window per workbook window on the desktop: per-window drafts, dialogs and ribbons; menu bar commands go to the focused window; closing one of several windows on a workbook doesn't ask; Quit asks in each unsaved workbook's window; the last window closed quits (Windows, Linux) or leaves macOS running | | 2026-10-22 | minor | New Window opens a second window on the same workbook instead of a copy that saved over the original; windows keep their own selection, sheet and scroll; titles Name:1 / Name:2; Switch Windows, Hide and Unhide work by window; File › Close closes one window of several without asking | | 2026-10-22 | minor | New workbook no longer loses the first one: the cell being typed is entered into its own workbook before any File or window command (an entry the workbook refuses stays open and the command doesn't run; an untouched F2 draft changes nothing), the editor is tied to its workbook, View › Switch Windows and the macOS Window menu list the open workbooks, and the macOS Quit item asks about unsaved workbooks like the close button | +| 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 | Typing into a cell with an in-cell list validation shows the list filtered to entries with a word starting with the typed text (case and Latin accents ignored, Vietnamese included, list order kept, only visible rows drawn); Up/Down move the highlight, Enter/Tab/click commit it with the list's spelling, Escape hides the list before cancelling. Column AutoComplete is off for those cells. New query command `data.validationList` | | 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 |