From f066fe994efd385867402bd2be20f84a7f8945b9 Mon Sep 17 00:00:00 2001 From: Harrison Booth Date: Wed, 14 Oct 2026 19:43:43 -0500 Subject: [PATCH 01/55] XLSX: keep self-contained workbook and sheet extLst entries on save Workbook extLst entries on an allowlist of single attribute-only elements are kept in source order with calcFeatures: x15 and x14 workbookPr, xlwcv:version and the Excel for Mac mx:ArchID. On sheets, the Excel for Mac mx:PLV is kept and written after the extensions the sheet writer emits, skipping any URI it already wrote. Entries are rebuilt from the parsed element with the schema's attributes only. Extensions that point at other content (slicers, timelines, data model, Google Sheets custom data) stay dropped and are named in an open warning. Co-Authored-By: Claude Opus 5.5 --- ROADMAP.md | 4 +- crates/xlsx/src/extlist.rs | 282 +++++++++++++++++++++ crates/xlsx/src/lib.rs | 1 + crates/xlsx/src/passthrough.rs | 24 +- crates/xlsx/src/read.rs | 8 + crates/xlsx/src/sheet_read.rs | 1 + crates/xlsx/src/sheet_write.rs | 10 +- crates/xlsx/src/tests/extlist.rs | 116 +++++++++ crates/xlsx/src/tests/mod.rs | 1 + crates/xlsx/src/tests/passthrough_tests.rs | 4 +- docs/file-format-parity.md | 5 +- 11 files changed, 435 insertions(+), 21 deletions(-) create mode 100644 crates/xlsx/src/extlist.rs create mode 100644 crates/xlsx/src/tests/extlist.rs diff --git a/ROADMAP.md b/ROADMAP.md index 070552d07e..48142ec34d 100644 --- a/ROADMAP.md +++ b/ROADMAP.md @@ -2,7 +2,7 @@ **Stage: alpha** · next: beta, ~25 points of "ready for real work" and ~160–240 h away -> **Last reviewed:** 2026-10-11 · **Last updated:** 2026-10-12 · **Change:** minor (rows auto-fit oversized fonts on open and whole-row/column formatting) · **Target:** Microsoft Excel (Microsoft 365) +> **Last reviewed:** 2026-10-11 · **Last updated:** 2026-10-14 · **Change:** trivial (progress log: XLSX self-contained extLst entries kept on save) · **Target:** Microsoft Excel (Microsoft 365) GridCraft aims at full Microsoft Excel parity, and at being better in places: faster, open (XLSX is the native format), fully scriptable by agents (MCP, control channel, CLI), and on the web. @@ -132,6 +132,7 @@ Ranked; estimates in Opus 5.5 agent-hours. Detail and the full beta-gate list in | Date | What landed | |---|---| +| 2026-10-14 | XLSX self-contained `extLst` entries are kept on save: x15 and x14 workbook properties, the workbook compatibility version and Excel for Mac entries, alongside calcFeatures; extensions that point at other content (slicers, timelines, data model, Google Sheets data) stay dropped and are named in an open warning | | 2026-10-12 | Rows auto-fit oversized fonts: opening a file and whole-row/column formatting grow non-custom rows to their tallest font (#833) | | 2026-10-12 | Number formats: parsing a format code is linear in its length (long runs of `[`, `,` or `/` no longer take quadratic time), and an unclosed `[` is a literal when splitting sections as well as when tokenizing (#810) | | 2026-10-12 | Number formats: a fraction denominator with 65,536 zeros no longer crashes; format codes are capped at 255 characters like Excel (longer codes display as General, `TEXT` gives `#VALUE!`) (#807) | @@ -193,6 +194,7 @@ Ranked; estimates in Opus 5.5 agent-hours. Detail and the full beta-gate list in | Date | Change | Summary | |---|---|---| +| 2026-10-14 | trivial | Progress log: XLSX self-contained extLst entries kept on save | | 2026-10-12 | minor | Rows auto-fit oversized fonts on open and whole-row/column formatting (#833); progress log row | | 2026-10-12 | minor | Progress log: multi-area row/column delete (#758) | | 2026-10-12 | trivial | Progress log: XLSX chart sheets kept on save (#727) | diff --git a/crates/xlsx/src/extlist.rs b/crates/xlsx/src/extlist.rs new file mode 100644 index 0000000000..ce9bc6e3fc --- /dev/null +++ b/crates/xlsx/src/extlist.rs @@ -0,0 +1,282 @@ +//! Self-contained extensions (``) of the workbook and its sheets, kept on save. +//! +//! An extension is kept only when its URI is on an allowlist of entries that are one element +//! holding attributes and nothing else: no children, no text, no relationship ids, no references +//! to cells, names or parts GridCraft renumbers. They are rebuilt from the parsed element with the +//! schema's attributes only, in source order. Extensions that point at other content (slicer +//! caches and lists, timelines, the data model, PivotTable caches, Google Sheets custom data with +//! its `r:id`) are left out: GridCraft rewrites or drops what they point at. Extensions GridCraft +//! models itself (x14 conditional formats, data validations, sparklines) are read into the model +//! and written by the sheet writer, never kept here. Every other extension is dropped and counted +//! in a read warning. +//! +//! Kept extensions go into the owner's [`Preserved`] as elements of slot `"ext"`: the workbook's +//! are written by `write.rs`, a sheet's after the extensions the sheet writer emits, skipping any +//! URI it already wrote. + +use std::fmt::Write as _; +use std::sync::Arc; + +use gridcraft_model::{Preserved, PreservedXml, Sheet}; + +use crate::read::Ctx; +use crate::xml::{El, esc_attr}; + +/// One allowlisted extension: its URI, the single element it holds and that element's attributes. +struct Allowed { + uri: &'static str, + prefix: &'static str, + ns: &'static str, + el: &'static str, + attrs: &'static [&'static str], +} + +const NS_X14: &str = "http://schemas.microsoft.com/office/spreadsheetml/2009/9/main"; +const NS_X15: &str = "http://schemas.microsoft.com/office/spreadsheetml/2010/11/main"; +const NS_XLWCV: &str = "http://schemas.microsoft.com/office/spreadsheetml/2024/workbookCompatibilityVersion"; +/// Excel for Mac 2011 extensions; older files use the namespace itself as the URI. +const NS_MX: &str = "http://schemas.microsoft.com/office/mac/excel/2008/main"; + +/// The workbook extension listing the calculation features the saved values were computed with. +/// Excel needs it, with ``, to trust the saved values (#799). +pub(crate) const CALC_FEATURES_URI: &str = "{B58B0392-4F1F-4190-BB64-5DF3571DCE5F}"; +const NS_CALC_FEATURES: &str = "http://schemas.microsoft.com/office/spreadsheetml/2018/calcfeatures"; + +/// Kept workbook extensions. +const WORKBOOK: &[Allowed] = &[ + // x15:workbookPr (CT_WorkbookPr in the 2010/11 schema). + Allowed { uri: "{140A7094-0E35-4892-8432-C4D2E57EDEB5}", prefix: "x15", ns: NS_X15, el: "workbookPr", attrs: &["chartTrackingRefBase"] }, + // x14:workbookPr (CT_WorkbookPr in the 2009/9 schema). + Allowed { + uri: "{79F54976-1DA5-4618-B147-4CDE4B953A38}", + prefix: "x14", + ns: NS_X14, + el: "workbookPr", + attrs: &["defaultImageDpi", "discardImageEditData", "accuracyVersion"], + }, + // The workbook compatibility version Excel 365 stamps. + Allowed { uri: "{D14903EA-33C4-47F7-8F05-3474C54BE107}", prefix: "xlwcv", ns: NS_XLWCV, el: "version", attrs: &["setVersion"] }, + // Excel for Mac architecture flags. + Allowed { uri: "{7523E5D3-25F3-A5E0-1632-64F254C22452}", prefix: "mx", ns: NS_MX, el: "ArchID", attrs: &["Flags"] }, + Allowed { uri: NS_MX, prefix: "mx", ns: NS_MX, el: "ArchID", attrs: &["Flags"] }, +]; + +/// Kept sheet extensions. +const SHEET: &[Allowed] = &[ + // Excel for Mac page layout view settings. + Allowed { uri: "{64002731-A6B0-56B0-2670-7721B7C09600}", prefix: "mx", ns: NS_MX, el: "PLV", attrs: &["Mode", "OnePage", "WScale"] }, + Allowed { uri: NS_MX, prefix: "mx", ns: NS_MX, el: "PLV", attrs: &["Mode", "OnePage", "WScale"] }, +]; + +/// Sheet extension elements the sheet reader models (x14 conditional formats, data validations, +/// sparklines). +const SHEET_MODELLED: &[&str] = &["conditionalFormattings", "dataValidations", "sparklineGroups"]; + +/// Longest attribute value kept (the kept attributes are flags and small numbers). +const MAX_VALUE: usize = 32; +/// Most dropped URIs named in one warning. +const MAX_NAMED: usize = 5; + +/// The `uri` attribute of `ext`, trimmed. +fn uri(ext: &El) -> &str { + ext.attr("uri").unwrap_or("").trim() +} + +/// `ext` rebuilt from `table` when it is allowlisted and self-contained. +fn rebuild(ext: &El, table: &[Allowed]) -> Option { + let u = uri(ext); + let a = table.iter().find(|a| a.uri.eq_ignore_ascii_case(u))?; + // Exactly one element, the expected one, holding attributes only. + let [el] = ext.children.as_slice() else { return None }; + if el.name != a.el || !el.children.is_empty() || !el.text.trim().is_empty() || !ext.text.trim().is_empty() { + return None; + } + let mut x = format!("<{p}:{}", a.uri, a.ns, a.el, p = a.prefix); + for name in a.attrs { + if let Some(v) = el.attr(name).map(str::trim) + && !v.is_empty() + && v.len() <= MAX_VALUE + && v.bytes().all(|b| b.is_ascii_alphanumeric() || b == b'.' || b == b'-') + { + let _ = write!(x, " {name}=\"{}\"", esc_attr(v)); + } + } + x.push_str("/>"); + Some(x) +} + +/// The calcFeatures extension rebuilt: the feature names only. +fn calc_features(ext: &El) -> Option { + let c = ext.child("calcFeatures")?; + let mut x = format!(""); + for name in c.kids("feature").filter_map(|f| f.attr("name")) { + let _ = write!(x, "", esc_attr(name)); + } + x.push_str(""); + Some(x) +} + +/// Adds `uri` to the dropped list once. +fn dropped(list: &mut Vec, uri: &str) { + let u = if uri.is_empty() { "(no URI)".to_string() } else { uri.to_string() }; + if !list.iter().any(|d| d.eq_ignore_ascii_case(&u)) { + list.push(u); + } +} + +/// The read warning naming the dropped extension URIs of `owner` ("the workbook", "sheet \"A\""). +fn warn_dropped(cx: &mut Ctx<'_>, owner: &str, list: &[String]) { + if list.is_empty() { + return; + } + let mut named = list.iter().take(MAX_NAMED).cloned().collect::>().join(", "); + if list.len() > MAX_NAMED { + let _ = write!(named, " and {} more", list.len() - MAX_NAMED); + } + let n = list.len(); + cx.warn(format!( + "{owner}: {n} Excel extension{} GridCraft does not model {} dropped ({named})", + if n == 1 { "" } else { "s" }, + if n == 1 { "was" } else { "were" } + )); +} + +/// Keeps the workbook's calcFeatures and allowlisted extensions from `ext_lst` (the workbook's +/// ``), in source order, as elements of slot `"ext"` of `p`; warns about the others. +pub(crate) fn keep_workbook(cx: &mut Ctx<'_>, ext_lst: Option<&El>, p: &mut Preserved) { + let Some(list) = ext_lst else { return }; + let mut kept: Vec = vec![]; + let mut lost = vec![]; + for ext in list.kids("ext") { + let u = uri(ext); + if kept.iter().any(|k| k.eq_ignore_ascii_case(u)) { + continue; + } + let x = if u.eq_ignore_ascii_case(CALC_FEATURES_URI) { calc_features(ext) } else { rebuild(ext, WORKBOOK) }; + match x { + Some(x) => { + kept.push(u.to_string()); + p.elements.push(PreservedXml { slot: "ext".into(), xml: x }); + } + None => dropped(&mut lost, u), + } + } + warn_dropped(cx, "the workbook", &lost); +} + +/// While a sheet is read: keeps the allowlisted extension `ext` of its `` until +/// [`keep_sheet`] attaches it, or counts it as dropped. Modelled extensions are left to the +/// sheet reader. +pub(crate) fn read_sheet_ext(cx: &mut Ctx<'_>, ext: &El) { + if ext.children.iter().any(|c| SHEET_MODELLED.contains(&c.name.as_str())) { + return; + } + let u = uri(ext); + if cx.sheet_exts.iter().any(|(k, _)| k.eq_ignore_ascii_case(u)) { + return; + } + match rebuild(ext, SHEET) { + Some(x) => cx.sheet_exts.push((u.to_string(), x)), + None => dropped(&mut cx.sheet_exts_dropped, u), + } +} + +/// After a sheet is read: adds the extensions [`read_sheet_ext`] kept to `preserved` (the sheet's +/// other kept content), when unmodelled content is kept at all (`keep`), and warns about the +/// dropped ones. +pub(crate) fn keep_sheet(cx: &mut Ctx<'_>, name: &str, preserved: Option>, keep: bool) -> Option> { + let exts = std::mem::take(&mut cx.sheet_exts); + let mut lost = std::mem::take(&mut cx.sheet_exts_dropped); + if !keep { + for (u, _) in &exts { + dropped(&mut lost, u); + } + } + warn_dropped(cx, &format!("sheet \"{name}\""), &lost); + if !keep || exts.is_empty() { + return preserved; + } + let mut p = preserved.map(Arc::unwrap_or_clone).unwrap_or_default(); + p.elements.extend(exts.into_iter().map(|(_, xml)| PreservedXml { slot: "ext".into(), xml })); + Some(Arc::new(p)) +} + +/// The kept extensions of `sheet`, minus those whose URI is in `written` (the `` elements the +/// sheet writer already emitted). +pub(crate) fn sheet_exts(sheet: &Sheet, written: &str) -> String { + let Some(p) = sheet.preserved.as_deref() else { return String::new() }; + let lower = written.to_ascii_lowercase(); + let mut s = String::new(); + for e in p.elements.iter().filter(|e| e.slot == "ext") { + let uri = e.xml.split('"').nth(1).unwrap_or(""); + if uri.is_empty() || !lower.contains(&format!("uri=\"{}\"", uri.to_ascii_lowercase())) { + s.push_str(&e.xml); + } + } + s +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::xml::parse; + + fn ext(x: &str) -> El { + parse(x.as_bytes()).unwrap() + } + + #[test] + fn rebuilds_allowlisted_entries_only() { + let x15 = + ext(r#""#); + assert_eq!( + rebuild(&x15, WORKBOOK).as_deref(), + Some( + format!( + r#""# + ) + .as_str() + ) + ); + // A known URI with unexpected content: children, text, another element, or nothing. + for bad in [ + r#""#, + r#"text"#, + r#""#, + r#""#, + r#""#, + ] { + assert_eq!(rebuild(&ext(bad), WORKBOOK), None, "{bad}"); + } + // Not allowlisted: the data model and slicer caches point at other parts. + for uri in ["{FCE2AD5D-F65C-4FA6-A056-5C36A1767C68}", "{BBE1A952-AA13-448e-AADC-164F8A28A991}", "GOOGLESHEETSCUSTOMDATAVERSION2"] { + assert_eq!(rebuild(&ext(&format!(r#""#)), WORKBOOK), None); + } + // Sheet entries are not workbook entries. + let plv = ext(r#""#); + assert_eq!(rebuild(&plv, WORKBOOK), None); + assert!(rebuild(&plv, SHEET).unwrap().contains(r#""#)); + } + + #[test] + fn values_that_are_not_flags_or_numbers_are_left_out() { + let e = + ext(r#""#); + assert_eq!( + rebuild(&e, WORKBOOK).as_deref(), + Some( + format!(r#""#) + .as_str() + ) + ); + } + + #[test] + fn written_uris_are_not_repeated() { + let mut sheet = Sheet::new("A".to_string()); + let plv = rebuild(&ext(r#""#), SHEET).unwrap(); + sheet.preserved = Some(Arc::new(Preserved { elements: vec![PreservedXml { slot: "ext".into(), xml: plv.clone() }], ..Default::default() })); + assert_eq!(sheet_exts(&sheet, ""), plv); + assert_eq!(sheet_exts(&sheet, r#""#), ""); + } +} diff --git a/crates/xlsx/src/lib.rs b/crates/xlsx/src/lib.rs index 3300f97fe5..b302c912cd 100644 --- a/crates/xlsx/src/lib.rs +++ b/crates/xlsx/src/lib.rs @@ -18,6 +18,7 @@ mod chartex; mod crypto; mod csv; mod drawing; +mod extlist; mod feature_bags; mod fmla; mod ods; diff --git a/crates/xlsx/src/passthrough.rs b/crates/xlsx/src/passthrough.rs index dd881c1e9a..908098cd7d 100644 --- a/crates/xlsx/src/passthrough.rs +++ b/crates/xlsx/src/passthrough.rs @@ -75,6 +75,13 @@ fn kept_total() -> usize { } } +impl KeptReader { + /// Whether unmodelled content is kept for this package (not for Strict Open XML files). + pub fn keeps(&self) -> bool { + self.on + } +} + const NS_REL_STRICT: &str = "http://purl.oclc.org/ooxml/officeDocument/relationships"; const CT_VML: &str = "application/vnd.openxmlformats-officedocument.vmlDrawing"; @@ -88,9 +95,6 @@ const SHEET_ROOTS: &[&str] = &["queryTable", "tableSingleCells"]; const SHEET_ELEMENT_KINDS: &[&str] = &["oleObject", "ctrlProp", "control", "image", "package", "printerSettings"]; /// Attributes of `` (CT_FileVersion). const FILE_VERSION_ATTRS: &[&str] = &["appName", "lastEdited", "lowestEdited", "rupBuild", "codeName"]; -/// The workbook extension listing the calculation features the saved values were computed with. -const CALC_FEATURES_URI: &str = "{B58B0392-4F1F-4190-BB64-5DF3571DCE5F}"; -const NS_CALC_FEATURES: &str = "http://schemas.microsoft.com/office/spreadsheetml/2018/calcfeatures"; /// Kept sheet elements, in schema order (all after ``, before ``). const SHEET_SLOTS: &[&str] = &["picture", "oleObjects", "controls"]; @@ -445,18 +449,8 @@ impl KeptReader { x.push_str("/>"); p.elements.push(PreservedXml { slot: "fileVersion".into(), xml: x }); } - let calc_features = wb_xml - .child("extLst") - .and_then(|l| l.kids("ext").find(|e| e.attr("uri").is_some_and(|u| u.eq_ignore_ascii_case(CALC_FEATURES_URI)))) - .and_then(|e| e.child("calcFeatures")); - if let Some(c) = calc_features { - let mut x = format!(""); - for name in c.kids("feature").filter_map(|f| f.attr("name")) { - let _ = write!(x, "", esc_attr(name)); - } - x.push_str(""); - p.elements.push(PreservedXml { slot: "ext".into(), xml: x }); - } + // calcFeatures and the self-contained extensions (x14/x15 workbookPr, Mac entries). + crate::extlist::keep_workbook(cx, wb_xml.child("extLst"), &mut p); (!p.is_empty()).then(|| Arc::new(p)) } diff --git a/crates/xlsx/src/read.rs b/crates/xlsx/src/read.rs index 1a479081c2..2b47e7e11e 100644 --- a/crates/xlsx/src/read.rs +++ b/crates/xlsx/src/read.rs @@ -30,6 +30,10 @@ pub struct Ctx<'a> { pub cell_pictures: Vec>>, /// x14 conditional-format ids of the current sheet's data bars, with the index of the rule in `cond_formats`. pub cf_ext_ids: Vec<(String, usize)>, + /// Kept extensions of the current sheet's `` (URI, rebuilt XML), until attached. + pub sheet_exts: Vec<(String, String)>, + /// URIs of the current sheet's extensions that were dropped. + pub sheet_exts_dropped: Vec, } impl Ctx<'_> { @@ -82,6 +86,8 @@ pub fn read_xlsx(bytes: &[u8]) -> Result<(Workbook, ReadReport), IoError> { num_fmts: Default::default(), cell_pictures: vec![], cf_ext_ids: vec![], + sheet_exts: vec![], + sheet_exts_dropped: vec![], }; let root_rels = cx.pkg.rels("")?; let wb_part = find_rel(&root_rels, "officeDocument").map(|r| r.target.clone()).unwrap_or_else(|| "xl/workbook.xml".into()); @@ -238,6 +244,8 @@ pub fn read_xlsx(bytes: &[u8]) -> Result<(Workbook, ReadReport), IoError> { Some("veryHidden") => Visibility::VeryHidden, _ => Visibility::Visible, }; + // Self-contained sheet extensions (Excel for Mac page layout settings). + sheet.preserved = crate::extlist::keep_sheet(&mut cx, &name, sheet.preserved.take(), kept.keeps()); file_to_model.push(Some(wb.sheets.len())); wb.sheets.push(Arc::new(sheet)); } diff --git a/crates/xlsx/src/sheet_read.rs b/crates/xlsx/src/sheet_read.rs index 0194d22688..4faed3ea1a 100644 --- a/crates/xlsx/src/sheet_read.rs +++ b/crates/xlsx/src/sheet_read.rs @@ -952,6 +952,7 @@ fn read_threaded(cx: &Ctx<'_>, x: &El, sheet: &mut Sheet) { /// Worksheet extensions: x14 data validations and sparklines. fn read_ext(cx: &mut Ctx<'_>, e: &El, sheet: &mut Sheet) { for ext in e.kids("ext") { + crate::extlist::read_sheet_ext(cx, ext); for c in &ext.children { match c.name.as_str() { "dataValidations" => { diff --git a/crates/xlsx/src/sheet_write.rs b/crates/xlsx/src/sheet_write.rs index 78e1afaaef..5d2b048ef2 100644 --- a/crates/xlsx/src/sheet_write.rs +++ b/crates/xlsx/src/sheet_write.rs @@ -584,9 +584,13 @@ pub fn write_sheet(wb: &Workbook, si: usize, selected: bool, out: &mut Out) -> ( .filter(|(_, cf)| !cf.ranges.is_empty() && matches!(cf.rule, CfRule::DataBar { gradient: false, .. })) .map(|(i, cf)| (cf, prio.get(i).copied().unwrap_or(1))) .collect(); - if !solid_bars.is_empty() || !sheet.sparklines.is_empty() { + // Then the self-contained extensions kept from the source file. + let has_kept_exts = !crate::extlist::sheet_exts(sheet, "").is_empty(); + let has_exts = !solid_bars.is_empty() || !sheet.sparklines.is_empty() || has_kept_exts; + if has_exts { s.push_str(""); } + let exts_start = s.len(); if !solid_bars.is_empty() { let _ = write!( s, @@ -622,7 +626,9 @@ pub fn write_sheet(wb: &Workbook, si: usize, selected: bool, out: &mut Out) -> ( } s.push_str(""); } - if !solid_bars.is_empty() || !sheet.sparklines.is_empty() { + if has_exts { + let kept_exts = crate::extlist::sheet_exts(sheet, s.get(exts_start..).unwrap_or("")); + s.push_str(&kept_exts); s.push_str(""); } s.push_str(""); diff --git a/crates/xlsx/src/tests/extlist.rs b/crates/xlsx/src/tests/extlist.rs new file mode 100644 index 0000000000..79c49c50c9 --- /dev/null +++ b/crates/xlsx/src/tests/extlist.rs @@ -0,0 +1,116 @@ +//! Workbook and sheet extensions (``) kept on save. Packages are built in code. + +use std::io::Read; + +use super::{CT, ROOT_RELS, make_zip}; +use crate::{read_xlsx, write_xlsx}; + +const NS_MAIN: &str = "http://schemas.openxmlformats.org/spreadsheetml/2006/main"; +const NS_R: &str = "http://schemas.openxmlformats.org/officeDocument/2006/relationships"; +const NS_X14: &str = "http://schemas.microsoft.com/office/spreadsheetml/2009/9/main"; +const NS_X15: &str = "http://schemas.microsoft.com/office/spreadsheetml/2010/11/main"; +const NS_MX: &str = "http://schemas.microsoft.com/office/mac/excel/2008/main"; + +const CALC: &str = r#""#; +const X14_WB: &str = r#""#; +const X15_WB: &str = r#""#; +const XLWCV: &str = r#""#; +const ARCH_ID: &str = r#""#; +const PLV: &str = r#""#; + +/// A workbook whose `` holds the kept extensions, interleaved with ones that point at +/// other content (the data model, Google Sheets custom data); sheet "A" has a sparkline, Mac page +/// layout settings and a web extension reference. +fn package() -> Vec { + let workbook = format!( + r#"{X14_WB}{X15_WB}{CALC}{XLWCV}{ARCH_ID}"# + ); + let sheet = format!( + r#"12A!A1:B1C1"# + ); + let rels = format!( + r#""# + ); + make_zip(&[ + ("[Content_Types].xml", CT.as_bytes()), + ("_rels/.rels", ROOT_RELS.as_bytes()), + ("xl/workbook.xml", workbook.as_bytes()), + ("xl/_rels/workbook.xml.rels", rels.as_bytes()), + ("xl/worksheets/sheet1.xml", sheet.as_bytes()), + ]) +} + +fn part(bytes: &[u8], name: &str) -> String { + let mut z = zip::ZipArchive::new(std::io::Cursor::new(bytes)).unwrap(); + let mut s = String::new(); + z.by_name(name).unwrap().read_to_string(&mut s).unwrap(); + s +} + +/// The `…` of a part. +fn ext_lst(xml: &str) -> &str { + let a = xml.find("").unwrap_or_else(|| panic!("no extLst: {xml}")); + let b = xml.find("").unwrap(); + &xml[a..b + "".len()] +} + +#[test] +fn self_contained_extensions_survive_saves_in_source_order() { + let (wb, report) = read_xlsx(&package()).unwrap(); + let w = report.warnings.iter().find(|w| w.starts_with("the workbook:")).unwrap_or_else(|| panic!("{:?}", report.warnings)); + assert!( + w.contains("2 Excel extensions") && w.contains("{FCE2AD5D-F65C-4FA6-A056-5C36A1767C68}") && w.contains("GOOGLESHEETSCUSTOMDATAVERSION2"), + "{w}" + ); + let s = report.warnings.iter().find(|w| w.starts_with("sheet \"A\":")).unwrap_or_else(|| panic!("{:?}", report.warnings)); + assert!(s.contains("1 Excel extension ") && s.contains("{F7C9EE02-42E1-4005-9D12-6889AFFD525C}"), "{s}"); + // Twice: what was kept on the first save is read back and kept again. + let first = write_xlsx(&wb).unwrap(); + let (again, report) = read_xlsx(&first).unwrap(); + assert!(!report.warnings.iter().any(|w| w.contains("Excel extension")), "{:?}", report.warnings); + for saved in [first, write_xlsx(&again).unwrap()] { + let book = part(&saved, "xl/workbook.xml"); + assert_eq!(ext_lst(&book), format!("{X14_WB}{X15_WB}{CALC}{XLWCV}{ARCH_ID}")); + assert!(book.ends_with(""), "{book}"); + let sheet = part(&saved, "xl/worksheets/sheet1.xml"); + let list = ext_lst(&sheet); + // The sparkline written by the sheet writer once, then the kept page layout settings once. + assert_eq!(list.matches("{05C60535-1F16-4fd2-B633-F4F36F0B64E0}").count(), 1, "{list}"); + assert_eq!(list.matches("{64002731-A6B0-56B0-2670-7721B7C09600}").count(), 1, "{list}"); + assert!(list.ends_with(&format!("{PLV}")), "{list}"); + assert!(!list.contains("webExtension"), "{list}"); + crate::xml::parse(sheet.as_bytes()).unwrap(); + crate::xml::parse(book.as_bytes()).unwrap(); + } +} + +#[test] +fn a_sheet_with_only_kept_extensions_gets_an_ext_list() { + let sheet = format!(r#"{PLV}"#); + let rels = format!( + r#""# + ); + let workbook = format!( + r#""# + ); + let bytes = make_zip(&[ + ("[Content_Types].xml", CT.as_bytes()), + ("_rels/.rels", ROOT_RELS.as_bytes()), + ("xl/workbook.xml", workbook.as_bytes()), + ("xl/_rels/workbook.xml.rels", rels.as_bytes()), + ("xl/worksheets/sheet1.xml", sheet.as_bytes()), + ]); + let (wb, report) = read_xlsx(&bytes).unwrap(); + assert!(!report.warnings.iter().any(|w| w.contains("Excel extension")), "{:?}", report.warnings); + let saved = write_xlsx(&wb).unwrap(); + assert!(part(&saved, "xl/worksheets/sheet1.xml").ends_with(&format!("{PLV}"))); + // No extension on the workbook: none written. + assert!(!part(&saved, "xl/workbook.xml").contains("extLst")); +} + +#[test] +fn a_new_workbook_has_no_ext_lists() { + let saved = write_xlsx(&gridcraft_model::Workbook::new()).unwrap(); + assert!(!part(&saved, "xl/workbook.xml").contains("extLst")); + assert!(!part(&saved, "xl/worksheets/sheet1.xml").contains("extLst")); +} diff --git a/crates/xlsx/src/tests/mod.rs b/crates/xlsx/src/tests/mod.rs index 517113d0f6..ea0474b822 100644 --- a/crates/xlsx/src/tests/mod.rs +++ b/crates/xlsx/src/tests/mod.rs @@ -4,6 +4,7 @@ mod array_export; mod chart_bool_default; mod csv_tests; mod encrypted_tests; +mod extlist; mod fixtures; mod ink_roundtrip; mod literal_category_roundtrip; diff --git a/crates/xlsx/src/tests/passthrough_tests.rs b/crates/xlsx/src/tests/passthrough_tests.rs index d844daa055..5b901ff0b5 100644 --- a/crates/xlsx/src/tests/passthrough_tests.rs +++ b/crates/xlsx/src/tests/passthrough_tests.rs @@ -816,7 +816,9 @@ fn file_version_and_calc_features_survive_a_save() { assert_eq!(root.children.first().map(|e| e.name.as_str()), Some("fileVersion"), "{text}"); assert_eq!(root.children.last().map(|e| e.name.as_str()), Some("extLst"), "{text}"); assert!(text.contains(r#""#), "{text}"); - assert!(text.contains(&format!("{calc_features}")), "{text}"); + // The x15 workbook properties are kept too, in source order (see tests::extlist). + let x15 = r#""#; + assert!(text.contains(&format!("{x15}{calc_features}")), "{text}"); } // A workbook that had neither gets neither. diff --git a/docs/file-format-parity.md b/docs/file-format-parity.md index 9884724146..a154f535b3 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-12 · **Change:** trivial (XLSX chart sheets are kept on save (#727); previously minor: CSV save keeps the separator it was opened with) · **Target:** Microsoft Excel (Microsoft 365), Excel for Mac 16.113.4 +> **Last reviewed:** 2026-10-11 · **Last updated:** 2026-10-14 · **Change:** trivial (XLSX self-contained workbook and sheet extensions are kept on save; previously trivial: chart sheets are kept on save (#727)) · **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** @@ -22,7 +22,7 @@ and repair-free opening remain unverified. | Format | Excel | GridCraft read | GridCraft write | Fidelity / notes | Tests | |---|---|---|---|---|---| -| `.xlsx` Excel Workbook (transitional) | R/W, native | yes | yes | Cells, shared/array/dynamic formulas, styles, themes, merges, CF, validation, tables, comments and notes, hyperlinks, names, freeze panes, outline, print settings, pictures, shapes, charts (simplified, see [chart-parity.md](chart-parity.md)), sparklines, PivotTables (caches and tables), protection, calc settings. **Kept unchanged on save (pass-through, `passthrough.rs`):** custom document properties, ribbon customisation and add-in task panes, custom XML, links to external workbooks (never followed or refreshed), data connections, sheet query tables, printer settings (#324), form controls, ActiveX controls, OLE objects and sheet backgrounds (with their VML shapes), and chart sheets (#727: the sheet, drawing, chart, style and colour parts are written back unchanged in their place, and left out when a sheet they plot was deleted or renamed or a worksheet took their name; they can't be edited or created); dropped when their sheet is deleted or their parts point at content GridCraft rewrites. **Not preserved:** slicers and slicer caches, timelines, data model, query tables attached to tables, sheet and workbook `extLst` entries we don't model, chart details; Strict Open XML files keep nothing. Never checked in Excel across a corpus: repair prompts unknown. 100 MB files fail (#175) | `roundtrip.rs`, `fixtures.rs`, `malformed.rs`, `pivot_tests.rs` | +| `.xlsx` Excel Workbook (transitional) | R/W, native | yes | yes | Cells, shared/array/dynamic formulas, styles, themes, merges, CF, validation, tables, comments and notes, hyperlinks, names, freeze panes, outline, print settings, pictures, shapes, charts (simplified, see [chart-parity.md](chart-parity.md)), sparklines, PivotTables (caches and tables), protection, calc settings. **Kept unchanged on save (pass-through, `passthrough.rs`):** custom document properties, ribbon customisation and add-in task panes, custom XML, links to external workbooks (never followed or refreshed), data connections, sheet query tables, printer settings (#324), form controls, ActiveX controls, OLE objects and sheet backgrounds (with their VML shapes), and chart sheets (#727: the sheet, drawing, chart, style and colour parts are written back unchanged in their place, and left out when a sheet they plot was deleted or renamed or a worksheet took their name; they can't be edited or created); dropped when their sheet is deleted or their parts point at content GridCraft rewrites. Self-contained `extLst` entries (`extlist.rs`, an allowlist of single attribute-only elements, rebuilt in source order): the workbook's calcFeatures, x15 and x14 `workbookPr`, `xlwcv:version` and Excel for Mac `mx:ArchID`, and the sheet's Excel for Mac `mx:PLV`. **Not preserved:** slicers and slicer caches, timelines, data model, query tables attached to tables, other sheet and workbook `extLst` entries we don't model (each dropped URI is named in an open warning), chart details; Strict Open XML files keep nothing. Never checked in Excel across a corpus: repair prompts unknown. 100 MB files fail (#175) | `roundtrip.rs`, `fixtures.rs`, `malformed.rs`, `pivot_tests.rs` | | `.xlsx` Excel Workbook (transitional) | R/W, native | yes | yes | Cells, shared/array/dynamic formulas, styles, themes, merges, CF, validation, tables, notes (with their shown/hidden state) and threaded comments with replies, resolved state and timestamps (`threadedComments` and `persons` parts, #300), hyperlinks, names, freeze panes, outline, print settings, pictures, shapes, charts (simplified, see [chart-parity.md](chart-parity.md)), sparklines, PivotTables (caches and tables), protection, calc settings. **Not preserved:** unmodelled parts and extensions (form controls, slicer caches, timelines, external links, OLE objects, custom XML, data model, query tables, chart details). Never checked in Excel across a corpus: repair prompts unknown. 100 MB files fail (#175) | `roundtrip.rs`, `fixtures.rs`, `malformed.rs`, `pivot_tests.rs` | | `.xlsx` Excel Workbook (transitional) | R/W, native | yes | yes | Cells, shared/array/dynamic formulas, styles, themes, merges, CF, validation, tables, comments and notes, hyperlinks, names, freeze panes, outline, print settings, pictures, shapes, charts (simplified, see [chart-parity.md](chart-parity.md)), sparklines, PivotTables (caches and tables), protection, Allow Edit Ranges (`protectedRanges` with their password hashes, #307), calc settings. **Not preserved:** unmodelled parts and extensions (form controls, slicer caches, timelines, external links, OLE objects, custom XML, data model, query tables, chart details). Never checked in Excel across a corpus: repair prompts unknown. 100 MB files fail (#175) | `roundtrip.rs`, `fixtures.rs`, `malformed.rs`, `pivot_tests.rs` | | `.xlsx` Strict Open XML | R/W | yes | no (writes transitional) | Excel also saves transitional by default | fixtures | @@ -85,6 +85,7 @@ refresh. Counted under features (Get & Transform, ~10% ready), not here. | Date | Change | Summary | |---|---|---| +| 2026-10-14 | trivial | XLSX self-contained workbook and sheet `extLst` entries are kept on save; the others are named in an open warning | | 2026-10-12 | trivial | XLSX chart sheets are kept on save (#727) | | 2026-10-12 | trivial | CSV and TSV export is capped at 512 MiB and refuses a larger used range with an error (#528) | | 2026-10-12 | minor | `.xls` import reads the calculation settings (CalcMode, CalcIter, CalcCount, CalcDelta, CalcPrecision), so circular models calculate instead of showing `#CIRC!` (#724) | From 43ccb39ba3f1ee35126866daa906f5f486d98371 Mon Sep 17 00:00:00 2001 From: Harrison Booth Date: Thu, 15 Oct 2026 04:17:26 -0500 Subject: [PATCH 02/55] Keyboard: F8 Extend Selection and Shift+F8 Add or Remove Selection F8 toggles Extend Selection: arrows, Page Up/Down, Ctrl+arrows, Home and Ctrl+Home/End extend from the anchor as if Shift were held, and a click extends like Shift+click. Shift+F8 toggles Add or Remove Selection: arrows move the active cell and keep the selected areas, Shift+arrows grow a new area from there, and a click adds an area or removes a selected one, like Ctrl+click. The status bar names the mode (translated in every catalog). The key again, Esc or editing a cell ends it. UI-only command ui.selectionMode sets or reports the mode for agents. Co-Authored-By: Claude Opus 5.5 --- ROADMAP.md | 4 +- crates/ui-egui/src/control.rs | 5 + crates/ui-egui/src/grid.rs | 130 ++++++++++++++++-- crates/ui-egui/src/i18n.rs | 2 + crates/ui-egui/src/i18n/cs.rs | 2 + crates/ui-egui/src/i18n/de.rs | 2 + crates/ui-egui/src/i18n/es.rs | 2 + crates/ui-egui/src/i18n/fr.rs | 2 + crates/ui-egui/src/i18n/ko.rs | 2 + crates/ui-egui/src/i18n/pt.rs | 2 + crates/ui-egui/src/i18n/ru.rs | 2 + crates/ui-egui/src/i18n/sr.rs | 2 + crates/ui-egui/src/i18n/zh.rs | 2 + crates/ui-egui/src/lib.rs | 14 ++ crates/ui-egui/src/tabs.rs | 5 + crates/ui-egui/tests/keyboard_shortcuts.rs | 149 ++++++++++++++++++++- docs/ui-parity.md | 8 +- 17 files changed, 321 insertions(+), 14 deletions(-) diff --git a/ROADMAP.md b/ROADMAP.md index 070552d07e..097e4c9f67 100644 --- a/ROADMAP.md +++ b/ROADMAP.md @@ -2,7 +2,7 @@ **Stage: alpha** · next: beta, ~25 points of "ready for real work" and ~160–240 h away -> **Last reviewed:** 2026-10-11 · **Last updated:** 2026-10-12 · **Change:** minor (rows auto-fit oversized fonts on open and whole-row/column formatting) · **Target:** Microsoft Excel (Microsoft 365) +> **Last reviewed:** 2026-10-11 · **Last updated:** 2026-10-15 · **Change:** minor (F8 / Shift+F8 selection modes) · **Target:** Microsoft Excel (Microsoft 365) GridCraft aims at full Microsoft Excel parity, and at being better in places: faster, open (XLSX is the native format), fully scriptable by agents (MCP, control channel, CLI), and on the web. @@ -132,6 +132,7 @@ Ranked; estimates in Opus 5.5 agent-hours. Detail and the full beta-gate list in | Date | What landed | |---|---| +| 2026-10-15 | Keyboard: F8 Extend Selection and Shift+F8 Add or Remove Selection: arrows and clicks extend from the anchor or build multi-area selections without holding Shift or Ctrl, the status bar names the mode, and Esc, the key again or editing a cell ends it | | 2026-10-12 | Rows auto-fit oversized fonts: opening a file and whole-row/column formatting grow non-custom rows to their tallest font (#833) | | 2026-10-12 | Number formats: parsing a format code is linear in its length (long runs of `[`, `,` or `/` no longer take quadratic time), and an unclosed `[` is a literal when splitting sections as well as when tokenizing (#810) | | 2026-10-12 | Number formats: a fraction denominator with 65,536 zeros no longer crashes; format codes are capped at 255 characters like Excel (longer codes display as General, `TEXT` gives `#VALUE!`) (#807) | @@ -193,6 +194,7 @@ Ranked; estimates in Opus 5.5 agent-hours. Detail and the full beta-gate list in | Date | Change | Summary | |---|---|---| +| 2026-10-15 | minor | Progress log: F8 and Shift+F8 selection modes | | 2026-10-12 | minor | Rows auto-fit oversized fonts on open and whole-row/column formatting (#833); progress log row | | 2026-10-12 | minor | Progress log: multi-area row/column delete (#758) | | 2026-10-12 | trivial | Progress log: XLSX chart sheets kept on save (#727) | diff --git a/crates/ui-egui/src/control.rs b/crates/ui-egui/src/control.rs index 2ea5cfae01..6035323cf3 100644 --- a/crates/ui-egui/src/control.rs +++ b/crates/ui-egui/src/control.rs @@ -184,6 +184,11 @@ pub fn handle(app: &mut SheetApp, ctx: &egui::Context, method: &str, p: &Json) - ("options.autoComplete", "Enable AutoComplete for cell values", "{on?: bool} (toggles without it) → {on}"), ("view.interfaceScale", "Interface Size", "{percent: 75–200 | \"auto\"} (100 = auto; clamped)"), ("ui.dialog", "Open Dialog", ""), + ( + "ui.selectionMode", + "Extend or Add to Selection", + "{mode?: \"extend\" (F8) | \"add\" (Shift+F8) | \"off\"} → {mode}; {} reports the mode", + ), ("ui.backstage", "File (Backstage view)", "{page?: home|new|open|info|saveAs|print|export|options|close}"), ( "ui.printSettings", diff --git a/crates/ui-egui/src/grid.rs b/crates/ui-egui/src/grid.rs index 97b787ef33..b5a536a6fc 100644 --- a/crates/ui-egui/src/grid.rs +++ b/crates/ui-egui/src/grid.rs @@ -149,6 +149,65 @@ pub struct GridState { pub hscroll: Option, /// Ctrl+wheel zoom in progress (see [`WheelZoom`]). pub wheel_zoom: Option, + /// F8 Extend Selection or Shift+F8 Add or Remove Selection mode (see [`SelectionMode`]). + pub selection_mode: SelectionMode, + /// Add mode: the last area is the cell an arrow key moved to, not yet extended, so the next + /// arrow moves it again instead of keeping it. + pub add_pending: bool, +} + +/// Excel's keyboard selection modes, shown in the status bar. In Extend mode (F8) arrow keys and +/// clicks extend from the anchor as if Shift were held. In Add mode (Shift+F8) arrow keys move the +/// active cell without dropping the selected areas, Shift+arrows grow a new area from there, and a +/// click adds an area (or removes one already selected) as Ctrl+click does. Esc, the same key +/// again, or editing a cell turns the mode off. +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] +pub enum SelectionMode { + #[default] + Off, + Extend, + Add, +} + +impl SelectionMode { + /// The id the `ui.selectionMode` command takes and returns. + pub fn id(self) -> &'static str { + match self { + Self::Off => "off", + Self::Extend => "extend", + Self::Add => "add", + } + } + + pub fn parse(id: &str) -> Option { + match id.trim().to_ascii_lowercase().as_str() { + "off" | "none" => Some(Self::Off), + "extend" => Some(Self::Extend), + "add" => Some(Self::Add), + _ => None, + } + } + + /// The status bar text (an i18n catalog key), when the mode shows one. + pub fn status_text(self) -> Option<&'static str> { + match self { + Self::Off => None, + Self::Extend => Some("Extend Selection"), + Self::Add => Some("Add or Remove Selection"), + } + } +} + +impl GridState { + /// Turns `mode` on, or off when it is already on (F8 / Shift+F8); the other mode ends. + pub fn toggle_selection_mode(&mut self, mode: SelectionMode) { + self.set_selection_mode(if self.selection_mode == mode { SelectionMode::Off } else { mode }); + } + + pub fn set_selection_mode(&mut self, mode: SelectionMode) { + self.selection_mode = mode; + self.add_pending = false; + } } /// Ctrl+wheel zoom for one (doc uid, sheet). egui eases a notch in over several frames and @@ -1784,6 +1843,14 @@ fn interact(app: &mut SheetApp, ui: &mut egui::Ui, resp: &egui::Response, geo: & let primary_clicked = resp.clicked_by(egui::PointerButton::Primary); let pointer = ctx.input(|i| i.pointer.clone()); let mods = ctx.input(|i| i.modifiers); + // Selecting with the pointer: Extend mode (F8) clicks as if Shift were held, Add mode + // (Shift+F8) as if Ctrl were. + let mut sel_mods = mods; + match app.grid.selection_mode { + SelectionMode::Extend => sel_mods.shift = true, + SelectionMode::Add => sel_mods.command = true, + SelectionMode::Off => {} + } // Hit-testing works in logical coordinates (see `Geo::rtl`). let pos = pointer.interact_pos().or(pointer.hover_pos()).map(|p| geo.mirror_pos(p)); let in_cells = pos.is_some_and(|p| geo.in_cells(p)); @@ -2020,7 +2087,7 @@ fn interact(app: &mut SheetApp, ui: &mut egui::Ui, resp: &egui::Response, geo: & return; } if resp.drag_started() - && !mods.any() + && !sel_mods.any() && sel.ranges.len() == 1 && sel.current().is_full_cols() && sel.current().contains(CellRef::new(0, c)) @@ -2028,9 +2095,9 @@ fn interact(app: &mut SheetApp, ui: &mut egui::Ui, resp: &egui::Response, geo: & app.grid.drag = Drag::MoveCols { source: sel.current(), before: None }; return; } - let range = if mods.shift { RangeRef::cols(sel.anchor.col.min(c), sel.anchor.col.max(c)) } else { RangeRef::cols(c, c) }; - select_ranges(app, range, mods.command, CellRef::new(geo.row_at(sh, geo.cells.top() + 1.0), c)); - app.grid.drag = Drag::Cols(if mods.shift { sel.anchor.col } else { c }); + let range = if sel_mods.shift { RangeRef::cols(sel.anchor.col.min(c), sel.anchor.col.max(c)) } else { RangeRef::cols(c, c) }; + select_ranges(app, range, sel_mods.command, CellRef::new(geo.row_at(sh, geo.cells.top() + 1.0), c)); + app.grid.drag = Drag::Cols(if sel_mods.shift { sel.anchor.col } else { c }); return; } if in_row_header { @@ -2042,9 +2109,9 @@ fn interact(app: &mut SheetApp, ui: &mut egui::Ui, resp: &egui::Response, geo: & if point_header(app, wb, sh, RangeRef::rows(r, r)) { return; } - let range = if mods.shift { RangeRef::rows(sel.anchor.row.min(r), sel.anchor.row.max(r)) } else { RangeRef::rows(r, r) }; - select_ranges(app, range, mods.command, CellRef::new(r, geo.col_at(sh, geo.cells.left() + 1.0))); - app.grid.drag = Drag::Rows(if mods.shift { sel.anchor.row } else { r }); + let range = if sel_mods.shift { RangeRef::rows(sel.anchor.row.min(r), sel.anchor.row.max(r)) } else { RangeRef::rows(r, r) }; + select_ranges(app, range, sel_mods.command, CellRef::new(r, geo.col_at(sh, geo.cells.left() + 1.0))); + app.grid.drag = Drag::Rows(if sel_mods.shift { sel.anchor.row } else { r }); return; } if !in_cells { @@ -2108,12 +2175,12 @@ fn interact(app: &mut SheetApp, ui: &mut egui::Ui, resp: &egui::Response, geo: & return; } app.grid.last_click = Some((c, now)); - if mods.shift { + if sel_mods.shift { let _ = app.session.run("selection.set", json!({"range": RangeRef::new(sel.anchor, c).a1(), "active": sel.active.a1()})); if let Some(d) = app.session.active_mut() { d.selection.anchor = sel.anchor; } - } else if mods.command { + } else if sel_mods.command { select_ranges(app, RangeRef::cell(c), true, c); } else { let _ = app.session.run("selection.set", json!({"cell": c.a1()})); @@ -2553,7 +2620,37 @@ fn toggled_ranges(mut ranges: Vec, clicked: String, add: bool) -> Vec>().join(","); + let _ = app.session.run("selection.set", json!({"range": range, "active": active.a1()})); + app.grid.add_pending = !kept; +} + fn select_ranges(app: &mut SheetApp, r: RangeRef, add: bool, active: CellRef) { + // A clicked area is kept: the next Add mode arrow starts a new one. + app.grid.add_pending = false; let current: Vec = if add { app.session.active().map(|d| d.selection.ranges.iter().map(|x| x.a1()).collect()).unwrap_or_default() } else { vec![] }; let clicked = r.a1(); @@ -2609,12 +2706,22 @@ fn keyboard(app: &mut SheetApp, ctx: &egui::Context, resp: &egui::Response, geo: } egui::Event::Key { key, physical_key, pressed: true, modifiers: m, .. } => { use egui::Key; + let navigation = matches!( + key, + Key::ArrowUp | Key::ArrowDown | Key::ArrowLeft | Key::ArrowRight | Key::PageUp | Key::PageDown | Key::Home | Key::End + ); + // Extend mode (F8): navigation keys extend from the anchor as if Shift were held. + let m = if navigation && app.grid.selection_mode == SelectionMode::Extend { egui::Modifiers { shift: true, ..m } } else { m }; if crate::keymap::dispatch(app, ctx, key, physical_key, m, geo, sh) { continue; } let cmd = m.command; let shift = m.shift; let mv = |app: &mut SheetApp, dr: i64, dc: i64| { + if app.grid.selection_mode == SelectionMode::Add { + add_mode_move(app, dr, dc, shift, cmd); + return; + } let _ = app.session.run("selection.move", json!({"dr": dr, "dc": dc, "extend": shift, "jump": cmd})); app.grid.ensure_visible = true; app.grid.reveal_moving_end = shift; @@ -2673,8 +2780,13 @@ fn keyboard(app: &mut SheetApp, ctx: &egui::Context, resp: &egui::Response, geo: Key::Escape => { app.session.clipboard = None; app.session.format_painter = None; + app.grid.set_selection_mode(SelectionMode::Off); } Key::Space if !cmd && !shift && is_checkbox(sh, app) => app.run_or_alert("cell.toggleCheckbox", json!({})), + // F8 Extend Selection, Shift+F8 Add or Remove Selection: each toggles its mode. + Key::F8 if !m.alt && !cmd => { + app.grid.toggle_selection_mode(if shift { SelectionMode::Add } else { SelectionMode::Extend }); + } Key::F8 if m.alt => { app.open_dialog("macros", json!({})); } diff --git a/crates/ui-egui/src/i18n.rs b/crates/ui-egui/src/i18n.rs index 061698df9b..72c0042dfc 100644 --- a/crates/ui-egui/src/i18n.rs +++ b/crates/ui-egui/src/i18n.rs @@ -457,6 +457,8 @@ const JAPANESE: &[(&str, &str)] = &[ ("Point", "ポイント"), ("Calculate", "計算"), ("Select destination and press Enter or choose Paste", "貼り付け先を選び、Enter キーを押すか [貼り付け] を選びます"), + ("Extend Selection", "選択範囲の拡張"), + ("Add or Remove Selection", "選択範囲の追加または削除"), ("General", "標準"), ("Number", "数値"), ("Currency", "通貨"), diff --git a/crates/ui-egui/src/i18n/cs.rs b/crates/ui-egui/src/i18n/cs.rs index 7ed8372c7d..581038d078 100644 --- a/crates/ui-egui/src/i18n/cs.rs +++ b/crates/ui-egui/src/i18n/cs.rs @@ -385,6 +385,8 @@ pub(super) fn translate(text: &str) -> Option<&'static str> { "Point" => "Výběr odkazu", "Calculate" => "Přepočítat", "Select destination and press Enter or choose Paste" => "Vyberte cíl a stiskněte Enter nebo zvolte Vložit", + "Extend Selection" => "Rozšířit výběr", + "Add or Remove Selection" => "Přidat nebo odebrat výběr", "General" => "Obecný", "Number" => "Číslo", "Currency" => "Měna", diff --git a/crates/ui-egui/src/i18n/de.rs b/crates/ui-egui/src/i18n/de.rs index c20c7d1b36..77a9314189 100644 --- a/crates/ui-egui/src/i18n/de.rs +++ b/crates/ui-egui/src/i18n/de.rs @@ -383,6 +383,8 @@ pub(super) fn translate(text: &str) -> Option<&'static str> { "Point" => "Zeigen", "Calculate" => "Berechnen", "Select destination and press Enter or choose Paste" => "Ziel auswählen und die Eingabetaste drücken oder „Einfügen“ wählen", + "Extend Selection" => "Markierung erweitern", + "Add or Remove Selection" => "Markierung hinzufügen oder entfernen", "General" => "Standard", "Number" => "Zahl", "Currency" => "Währung", diff --git a/crates/ui-egui/src/i18n/es.rs b/crates/ui-egui/src/i18n/es.rs index 4ce231bcad..07ffcfc1c2 100644 --- a/crates/ui-egui/src/i18n/es.rs +++ b/crates/ui-egui/src/i18n/es.rs @@ -382,6 +382,8 @@ pub(super) fn translate(text: &str) -> Option<&'static str> { "Point" => "Señalar", "Calculate" => "Calcular", "Select destination and press Enter or choose Paste" => "Seleccione el destino y presione Entrar o elija Pegar", + "Extend Selection" => "Extender selección", + "Add or Remove Selection" => "Agregar o quitar selección", "General" => "General", "Number" => "Número", "Currency" => "Moneda", diff --git a/crates/ui-egui/src/i18n/fr.rs b/crates/ui-egui/src/i18n/fr.rs index 5d20ab0ca2..616db6fc28 100644 --- a/crates/ui-egui/src/i18n/fr.rs +++ b/crates/ui-egui/src/i18n/fr.rs @@ -284,6 +284,8 @@ pub(super) fn translate(text: &str) -> Option<&'static str> { "Point" => "Point", "Calculate" => "Calculer", "Select destination and press Enter or choose Paste" => "Sélectionnez la destination et appuyez sur Entrée ou choisissez Coller", + "Extend Selection" => "Étendre la sélection", + "Add or Remove Selection" => "Ajouter ou supprimer la sélection", "General" => "Standard", "Number" => "Nombre", "Currency" => "Monétaire", diff --git a/crates/ui-egui/src/i18n/ko.rs b/crates/ui-egui/src/i18n/ko.rs index 1902ad3015..17b1d0ba06 100644 --- a/crates/ui-egui/src/i18n/ko.rs +++ b/crates/ui-egui/src/i18n/ko.rs @@ -273,6 +273,8 @@ pub(super) fn translate(text: &str) -> Option<&'static str> { "Point" => "가리키기", "Calculate" => "계산", "Select destination and press Enter or choose Paste" => "대상을 선택하고 Enter 키를 누르거나 [붙여넣기]를 선택하세요", + "Extend Selection" => "선택 영역 확장", + "Add or Remove Selection" => "선택 영역 추가 또는 제거", "General" => "일반", "Number" => "숫자", "Currency" => "통화", diff --git a/crates/ui-egui/src/i18n/pt.rs b/crates/ui-egui/src/i18n/pt.rs index fb9236cdb6..9adf19256d 100644 --- a/crates/ui-egui/src/i18n/pt.rs +++ b/crates/ui-egui/src/i18n/pt.rs @@ -274,6 +274,8 @@ pub(super) fn translate(text: &str) -> Option<&'static str> { "Point" => "Apontar", "Calculate" => "Calcular", "Select destination and press Enter or choose Paste" => "Selecione o destino e pressione Enter ou escolha Colar", + "Extend Selection" => "Estender Seleção", + "Add or Remove Selection" => "Adicionar ou Remover Seleção", "General" => "Geral", "Number" => "Número", "Currency" => "Moeda", diff --git a/crates/ui-egui/src/i18n/ru.rs b/crates/ui-egui/src/i18n/ru.rs index 765f6bb326..1669676b7d 100644 --- a/crates/ui-egui/src/i18n/ru.rs +++ b/crates/ui-egui/src/i18n/ru.rs @@ -273,6 +273,8 @@ pub(super) fn translate(text: &str) -> Option<&'static str> { "Point" => "Указание", "Calculate" => "Вычисление", "Select destination and press Enter or choose Paste" => "Выберите место вставки и нажмите Enter или выберите «Вставить»", + "Extend Selection" => "Расширить выделение", + "Add or Remove Selection" => "Добавить или удалить выделение", "General" => "Общий", "Number" => "Числовой", "Currency" => "Денежный", diff --git a/crates/ui-egui/src/i18n/sr.rs b/crates/ui-egui/src/i18n/sr.rs index cbf18d4c46..80e1acd214 100644 --- a/crates/ui-egui/src/i18n/sr.rs +++ b/crates/ui-egui/src/i18n/sr.rs @@ -276,6 +276,8 @@ pub(super) fn translate(text: &str) -> Option<&'static str> { "Point" => "Pokaži", "Calculate" => "Izračunavanje", "Select destination and press Enter or choose Paste" => "Izaberi odredište i pritisni Enter ili izaberi Nalepi", + "Extend Selection" => "Proširi izbor", + "Add or Remove Selection" => "Dodaj ili ukloni izbor", "General" => "Opšte", "Number" => "Broj", "Currency" => "Valuta", diff --git a/crates/ui-egui/src/i18n/zh.rs b/crates/ui-egui/src/i18n/zh.rs index 00175925e6..516ea4ee72 100644 --- a/crates/ui-egui/src/i18n/zh.rs +++ b/crates/ui-egui/src/i18n/zh.rs @@ -273,6 +273,8 @@ pub(super) fn translate(text: &str) -> Option<&'static str> { "Point" => "指向", "Calculate" => "计算", "Select destination and press Enter or choose Paste" => "选择目标位置并按 Enter,或选择“粘贴”", + "Extend Selection" => "扩展式选定", + "Add or Remove Selection" => "添加或删除所选内容", "General" => "常规", "Number" => "数值", "Currency" => "货币", diff --git a/crates/ui-egui/src/lib.rs b/crates/ui-egui/src/lib.rs index f96cdac3c0..ce2cea4820 100644 --- a/crates/ui-egui/src/lib.rs +++ b/crates/ui-egui/src/lib.rs @@ -663,6 +663,18 @@ impl SheetApp { self.open_dialog(name, p.clone()); Ok(json!({"dialog": self.dialog.as_ref().map(|d| d.name())})) } + "ui.selectionMode" => { + // `{"mode": "extend"}` (F8), `"add"` (Shift+F8) or `"off"`; `{}` reports the mode. + match p.get("mode").and_then(Json::as_str) { + Some(id) => match grid::SelectionMode::parse(id) { + Some(mode) => self.grid.set_selection_mode(mode), + None => return Some(Err(format!("unknown selection mode {id:?} (use \"extend\", \"add\" or \"off\")"))), + }, + None if p.get("mode").is_some_and(|v| !v.is_null()) => return Some(Err("`mode` must be \"extend\", \"add\" or \"off\"".into())), + None => {} + } + Ok(json!({"mode": self.grid.selection_mode.id()})) + } "ui.message.dismiss" => { self.message = None; Ok(Json::Null) @@ -867,6 +879,8 @@ impl SheetApp { self.message = Some(("Text Box".into(), clean_error(&e))); return; } + // Editing a cell ends Extend and Add mode, as in Excel. + self.grid.set_selection_mode(grid::SelectionMode::Off); let Some(d) = self.session.active() else { return }; let Some(sh) = d.wb.active() else { return }; let at = sh.merge_at(d.selection.active).map(|m| m.start).unwrap_or(d.selection.active); diff --git a/crates/ui-egui/src/tabs.rs b/crates/ui-egui/src/tabs.rs index b77524bb96..89b021c176 100644 --- a/crates/ui-egui/src/tabs.rs +++ b/crates/ui-egui/src/tabs.rs @@ -237,6 +237,11 @@ pub fn status_bar(app: &mut SheetApp, ui: &mut Ui) { gridcraft_engine::Mode::Point => "Point", }; ui.label(egui::RichText::new(app.ui.language.tr(mode)).font(theme::ui_font(12.5)).color(t.text_dim)); + // F8 / Shift+F8 selection mode. + if let Some(text) = app.grid.selection_mode.status_text() { + ui.add_space(12.0); + ui.label(egui::RichText::new(app.ui.language.tr(text)).font(theme::ui_font(12.5)).color(t.text_dim)); + } if let Some(d) = app.session.active() { if d.wb.vba_project.is_some() { ui.add_space(12.0); diff --git a/crates/ui-egui/tests/keyboard_shortcuts.rs b/crates/ui-egui/tests/keyboard_shortcuts.rs index c0a1307b3d..3f39850324 100644 --- a/crates/ui-egui/tests/keyboard_shortcuts.rs +++ b/crates/ui-egui/tests/keyboard_shortcuts.rs @@ -1,10 +1,12 @@ //! Excel keyboard shortcuts (crate::keymap) dispatched through real egui key events. -use egui::{Event, Key, Modifiers}; +use egui::{Event, Key, Modifiers, PointerButton}; +use egui_kittest::kittest::Queryable as _; use gridcraft_engine::Session; use gridcraft_engine::core::CellRef; use gridcraft_engine::model::BorderStyle; use gridcraft_ui_egui::SheetApp; +use gridcraft_ui_egui::grid::{Geo, SelectionMode}; use gridcraft_ui_egui::keymap::{Shortcut, lookup}; use serde_json::json; @@ -86,6 +88,151 @@ fn copy_formula_from_above_and_function_keys() { assert_eq!(h.state().session.active().unwrap().wb.sheets[0].zoom, 110); } +fn selection_a1(h: &Harness) -> String { + h.state().session.active().unwrap().selection.a1() +} + +fn active_a1(h: &Harness) -> String { + h.state().session.active().unwrap().selection.active.a1() +} + +fn mode(h: &Harness) -> SelectionMode { + h.state().grid.selection_mode +} + +#[test] +fn f8_extend_selection_extends_from_the_anchor_until_turned_off() { + let mut h = harness(book("A1")); + assert!(h.query_by_label("Extend Selection").is_none()); + key(&mut h, Key::F8, Modifiers::NONE); + assert_eq!(mode(&h), SelectionMode::Extend); + assert!(h.query_by_label("Extend Selection").is_some(), "the status bar shows the mode"); + key(&mut h, Key::ArrowRight, Modifiers::NONE); + key(&mut h, Key::ArrowDown, Modifiers::NONE); + assert_eq!(selection_a1(&h), "A1:B2"); + assert_eq!(active_a1(&h), "A1", "the active cell stays on the anchor"); + // Ctrl+arrow extends to the edge of the data, as Ctrl+Shift+arrow does. + key(&mut h, Key::ArrowDown, CTRL); + assert_eq!(selection_a1(&h), "A1:B3"); + // F8 again ends the mode: arrows move again. + key(&mut h, Key::F8, Modifiers::NONE); + assert_eq!(mode(&h), SelectionMode::Off); + assert!(h.query_by_label("Extend Selection").is_none()); + key(&mut h, Key::ArrowRight, Modifiers::NONE); + assert_eq!(selection_a1(&h), "B1"); + // Esc ends it too, and keeps the extended selection. + key(&mut h, Key::F8, Modifiers::NONE); + key(&mut h, Key::ArrowRight, Modifiers::NONE); + key(&mut h, Key::Escape, Modifiers::NONE); + assert_eq!(mode(&h), SelectionMode::Off); + assert_eq!(selection_a1(&h), "B1:C1"); + key(&mut h, Key::ArrowDown, Modifiers::NONE); + assert_eq!(selection_a1(&h), "B2"); +} + +#[test] +fn shift_f8_add_to_selection_builds_areas_with_arrow_keys() { + let mut h = harness(book("A1:A2")); + key(&mut h, Key::F8, Modifiers::SHIFT); + assert_eq!(mode(&h), SelectionMode::Add); + assert!(h.query_by_label("Add or Remove Selection").is_some(), "the status bar shows the mode"); + assert!(h.query_by_label("Extend Selection").is_none()); + // Arrows move the active cell and keep A1:A2; the next arrow moves the new cell again. + key(&mut h, Key::ArrowRight, Modifiers::NONE); + assert_eq!(selection_a1(&h), "A1:A2,B1"); + key(&mut h, Key::ArrowRight, Modifiers::NONE); + assert_eq!(selection_a1(&h), "A1:A2,C1"); + assert_eq!(active_a1(&h), "C1"); + // Shift+arrow grows that area from it and keeps it. + key(&mut h, Key::ArrowRight, Modifiers::SHIFT); + assert_eq!(selection_a1(&h), "A1:A2,C1:D1"); + assert_eq!(active_a1(&h), "C1"); + // The next arrow starts a third area. + key(&mut h, Key::ArrowDown, Modifiers::NONE); + key(&mut h, Key::ArrowDown, Modifiers::NONE); + assert_eq!(selection_a1(&h), "A1:A2,C1:D1,C3"); + // F8 switches to Extend mode, and Shift+F8 twice ends Add mode. + key(&mut h, Key::F8, Modifiers::NONE); + assert_eq!(mode(&h), SelectionMode::Extend); + key(&mut h, Key::F8, Modifiers::SHIFT); + assert_eq!(mode(&h), SelectionMode::Add); + key(&mut h, Key::F8, Modifiers::SHIFT); + assert_eq!(mode(&h), SelectionMode::Off); + assert!(h.query_by_label("Add or Remove Selection").is_none()); + key(&mut h, Key::ArrowRight, Modifiers::NONE); + assert_eq!(selection_a1(&h), "D3", "with the mode off an arrow drops the areas"); +} + +#[test] +fn editing_a_cell_ends_the_selection_mode() { + let mut h = harness(book("A1")); + key(&mut h, Key::F8, Modifiers::NONE); + key(&mut h, Key::F2, Modifiers::NONE); + assert!(h.state().editor.is_some()); + assert_eq!(mode(&h), SelectionMode::Off); + key(&mut h, Key::Escape, Modifiers::NONE); + key(&mut h, Key::F8, Modifiers::SHIFT); + h.input_mut().events.push(Event::Text("7".into())); + h.run_steps(2); + assert!(h.state().editor.is_some(), "typing starts an edit"); + assert_eq!(mode(&h), SelectionMode::Off); +} + +fn click(h: &mut Harness, a1: &str) { + let at = { + let app = h.state(); + let sheet = app.session.active().unwrap().wb.active().unwrap(); + Geo::new(sheet, app.grid.rect.unwrap(), app.view().scroll).cell_rect(sheet, CellRef::parse(a1).unwrap()).center() + }; + h.input_mut().events.push(Event::PointerMoved(at)); + h.run_steps(1); + for pressed in [true, false] { + h.input_mut().events.push(Event::PointerButton { pos: at, button: PointerButton::Primary, pressed, modifiers: Modifiers::NONE }); + h.run_steps(1); + } + h.run_steps(1); +} + +#[test] +fn clicks_extend_or_add_in_the_selection_modes() { + let mut h = harness(book("B2")); + key(&mut h, Key::F8, Modifiers::NONE); + click(&mut h, "D4"); + assert_eq!(selection_a1(&h), "B2:D4", "in Extend mode a click extends from the anchor"); + assert_eq!(mode(&h), SelectionMode::Extend, "the mode stays on"); + key(&mut h, Key::F8, Modifiers::SHIFT); + click(&mut h, "F6"); + assert_eq!(selection_a1(&h), "B2:D4,F6", "in Add mode a click adds an area"); + // (Not a double-click: that would edit the cell.) + h.state_mut().grid.last_click = None; + click(&mut h, "F6"); + assert_eq!(selection_a1(&h), "B2:D4", "and a click on a selected area removes it"); + // An arrow after a click keeps the clicked areas. + click(&mut h, "H8"); + key(&mut h, Key::ArrowDown, Modifiers::NONE); + assert_eq!(selection_a1(&h), "B2:D4,H8,H9"); + // Moving back onto the kept H8 and off again keeps it. + key(&mut h, Key::ArrowUp, Modifiers::NONE); + assert_eq!(selection_a1(&h), "B2:D4,H8"); + key(&mut h, Key::ArrowDown, Modifiers::NONE); + assert_eq!(selection_a1(&h), "B2:D4,H8,H9"); +} + +#[test] +fn selection_mode_command_sets_and_reports_without_a_dialog() { + let mut h = harness(book("A1")); + assert_eq!(h.state_mut().run("ui.selectionMode", json!({})), Ok(json!({"mode": "off"}))); + assert_eq!(h.state_mut().run("ui.selectionMode", json!({"mode": "extend"})), Ok(json!({"mode": "extend"}))); + h.run_steps(2); + assert!(h.query_by_label("Extend Selection").is_some()); + assert_eq!(h.state_mut().run("ui.selectionMode", json!({"mode": "add"})), Ok(json!({"mode": "add"}))); + assert!(h.state_mut().run("ui.selectionMode", json!({"mode": "sideways"})).is_err()); + assert!(h.state_mut().run("ui.selectionMode", json!({"mode": 3})).is_err()); + assert_eq!(mode(&h), SelectionMode::Add, "a bad mode changes nothing"); + assert_eq!(h.state_mut().run("ui.selectionMode", json!({"mode": "off"})), Ok(json!({"mode": "off"}))); + assert!(h.state().dialog.is_none()); +} + #[test] fn windows_and_mac_variants() { let cmd = CTRL; diff --git a/docs/ui-parity.md b/docs/ui-parity.md index 22e221e698..cb4ee67988 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-13 · **Change:** minor (horizontal scrollbar in the sheet tab bar, #840) · **Target:** Microsoft Excel (Microsoft 365), Excel for Mac 16.113.4 +> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-10-15 · **Change:** minor (F8 Extend Selection and Shift+F8 Add or Remove Selection) · **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 @@ -75,7 +75,7 @@ this logic, with one undo step. | Shortcuts bound to commands | 200+ documented shortcuts per platform | audited below (#110): shortcuts whose feature exists are bound, with the exceptions listed; the rest wait for their features | | Ctrl+arrow, Ctrl+Shift+arrow, Ctrl+Home/End, Ctrl+Shift+Home/End, Page Up/Down, Alt+Page | yes | done | | Ctrl+1, Ctrl+; and Ctrl+Shift+; , Ctrl+D/R, Ctrl+E, Ctrl+T/L, Ctrl+K, Ctrl+Shift+L, Ctrl+Shift+~!@#$%^&_ | yes | done | -| F2, F4, F5, F7, F9 family, Shift+F2/F3/F10/F11, F12 | yes | done; F11 chart sheet, F8 extend mode, F3 Paste Name, F4 Repeat missing | +| F2, F4, F5, F7, F9 family, Shift+F2/F3/F10/F11, F12 | yes | done; F8 / Shift+F8 extend and add modes with their status bar text; F11 chart sheet, F3 Paste Name, F4 Repeat missing | | Mac-specific (Cmd variants, Control variants, Fn keys) | yes | done where a feature exists (`keymap.rs` picks the Mac variant) | | Sequential Alt access keys (Alt, H, N, …) on every ribbon tab | yes | 364-sequence keytip table for all tabs: per-control badges, prefix waiting, dropdowns open for editing (type/arrows/Enter), pending bindings for not-yet-built commands; QAT/Backstage excluded | | Requests | — | #110 (more shortcuts and hot keys), #33 (sequential Alt; initial support landed in #43) | @@ -123,7 +123,8 @@ otherwise. Number-format and border keys match the physical key (Ctrl+Shift+4, w | Shift+F3, Ctrl+F3, Ctrl+Shift+F3 | Shift+F3, Cmd+F3 (Define Name), Cmd+Shift+F3 | Insert Function, Name Manager, Create from Selection | **added** | | F5, Shift+F5 (Mac), F7, Shift+F9, Ctrl+Alt+F9, F12, Ctrl+F4 | same | Go To, Find, Spelling, calculate sheet / all, Save As, close | **added** | | Shift+F10, Alt+Shift+F10, Ctrl+F1 | Shift+F10, Cmd+Option+R | context menu, Error Checking, ribbon | **added** | -| F1, F3, F4 (repeat), F6 / Shift+F6, F8 / Shift+F8, F11, End mode | same | help, Paste Name, Repeat, pane cycling, extend/add mode, chart sheet | missing (no such feature yet) | +| F8, Shift+F8 | same | Extend Selection (arrows, Page keys, Ctrl+arrows, Home and clicks extend from the anchor) and Add or Remove Selection (arrows move the active cell and keep the areas, Shift+arrows grow a new area, a click adds or removes an area); the status bar names the mode; the key again, Esc or editing a cell ends it (`ui.selectionMode`) | **added** | +| F1, F3, F4 (repeat), F6 / Shift+F6, F11, End mode | same | help, Paste Name, Repeat, pane cycling, chart sheet | missing (no such feature yet) | | Ctrl+6, Ctrl+8, Ctrl+Q, Ctrl+Shift+A, Ctrl+A after a function name, Ctrl+Shift+U, Ctrl+Alt+P | same | objects, outline symbols, Quick Analysis, argument names, Function Arguments, formula bar height, tooltips | missing | | Ctrl+Shift+Page Up / Down, Ctrl+Alt+5, Ctrl+Shift+F1, Ctrl+F5–F10, Alt+F8 / F11 / F12 | same | group sheets, shape cycling, full screen, window keys, macros, VBA, Power Query | missing | | — | Cmd+= (calculate), Cmd+T (references while editing; F4 works), Shift+F7, Cmd+Shift+L | Mac-only extras | missing (Cmd+= is egui's zoom key; no thesaurus or Modify Cell Style) | @@ -160,6 +161,7 @@ scrollbar bugs 2–4 · pixel/feel pass against observed Excel 7–12. ## Revision history | Date | Change | Summary | +| 2026-10-15 | minor | F8 Extend Selection and Shift+F8 Add or Remove Selection modes, shown in the status bar (`ui.selectionMode`) | |---|---|---| | 2026-10-12 | minor | The File view's recent list tells when each workbook was last changed, read off the UI thread | | 2026-10-13 | minor | Horizontal scrollbar in the sheet tab bar: drag, track click pages, frozen columns excluded from the page (#840) | From 5a72aff0c5be9cc94edecbf0719ff51fd8fe5e08 Mon Sep 17 00:00:00 2001 From: Harrison Booth Date: Thu, 15 Oct 2026 05:08:00 -0500 Subject: [PATCH 03/55] Resize Table: refuse another table, merged cells, a PivotTable or an array; keep header names in step table.resize grew a table over a neighbouring table without checking, leaving two overlapping tables that Excel refuses to open as is. It now refuses, as Excel does, a new range that takes in another table, a merged area, a PivotTable report or a multi-cell array formula. A spilled formula is still allowed (Excel allows it too). The columns a resize added were named by position ("Column{i+1}"), which could repeat a name already in the header row (a table whose third column is Column3, resized to start there, got a second Column3). The header row and the column names then drifted apart and the reader made the name unique on reopen ("Column32"). New columns are now named the way Excel names them (observed): an empty header continues a ColumnN on its left, otherwise takes the lowest free ColumnN, and a repeated header gets the next free suffix. The names are written into the header row as text. A table without a header row keeps its column names by position. Co-Authored-By: Claude Opus 5.5 --- crates/engine/src/cmd/extra.rs | 131 +++++++++++++++--- crates/engine/tests/table_resize_overlap.rs | 139 ++++++++++++++++++++ 2 files changed, 255 insertions(+), 15 deletions(-) diff --git a/crates/engine/src/cmd/extra.rs b/crates/engine/src/cmd/extra.rs index 01e2ac6e63..a939e227c3 100644 --- a/crates/engine/src/cmd/extra.rs +++ b/crates/engine/src/cmd/extra.rs @@ -826,27 +826,78 @@ fn table_resize(s: &mut Session, p: &Json) -> Result { } .ok_or_else(|| bad("table.resize", "select a cell in a table"))?; edit(s, |cx| { - let sheet = cx.sheet_mut(si)?; - let headers: Vec = (r.start.col..=r.end.col).map(|c| sheet.value(CellRef::new(r.start.row, c)).display()).collect(); - let t = sheet.tables.get_mut(ti).ok_or_else(|| bad("table", "gone"))?; + let wb = &cx.wb; + let sheet = wb.sheet(si).ok_or(EngineError::NoDocument)?; + let t = sheet.tables.get(ti).ok_or_else(|| bad("table", "gone"))?; if r.start.row != t.range.start.row || !r.intersects(&t.range) { return Err(EngineError::Other( "The headers must remain in the same row, and the resulting table range must overlap the original table range.".into(), )); } - let mut cols = Vec::new(); - for (i, h) in headers.iter().enumerate() { - let name = if h.is_empty() { format!("Column{}", i + 1) } else { h.clone() }; - let existing = t.columns.iter().find(|c| c.name.eq_ignore_ascii_case(&name)).cloned(); - cols.push(existing.unwrap_or(TableColumn { - name, - totals: TotalsFn::None, - totals_label: None, - formula: None, - unique_name: None, - xml: None, - })); + // Like Excel, the new range can't take in another table, a merged area, a PivotTable or a + // multi-cell array formula (a spill is fine: it shows #SPILL! inside the table). + if sheet.tables.iter().enumerate().any(|(i, o)| i != ti && o.range.intersects(&r)) { + return Err(EngineError::Other("A table can't overlap another table.".into())); } + if sheet.merges.iter().any(|m| m.intersects(&r)) { + return Err(EngineError::Other("A table can't overlap merged cells.".into())); + } + if sheet.pivots.iter().any(|pt| pt.last_range.unwrap_or_else(|| RangeRef::new(pt.anchor, pt.anchor)).intersects(&r)) { + return Err(EngineError::Other("A table can't overlap a PivotTable report.".into())); + } + if sheet.cells.iter().any(|(_, x)| x.formula.as_ref().and_then(|f| f.array).is_some_and(|a| !a.is_single() && a.intersects(&r))) { + return Err(EngineError::Other("Multi-cell array formulas aren't allowed in tables.".into())); + } + // Header text per new column (`None`: empty). Without a header row, a column that stays + // keeps its name. + let texts: Vec> = (r.start.col..=r.end.col) + .map(|c| { + if !t.header_row { + return c.checked_sub(t.range.start.col).and_then(|i| t.columns.get(i as usize)).map(|x| x.name.clone()); + } + let at = CellRef::new(r.start.row, c); + let v = sheet.value(at); + let text = match v.as_text() { + Some(x) => x.to_string(), + None => crate::display::cell_text(wb, sheet, at), + }; + (!text.trim().is_empty()).then_some(text) + }) + .collect(); + let names = resized_column_names(&texts); + let old = t.range; + let old_cols = t.columns.clone(); + let header_row = t.header_row; + let mut cols = Vec::with_capacity(names.len()); + for (c, name) in (r.start.col..=r.end.col).zip(&names) { + // A column that stays keeps its settings (totals, calculated formula): with a header + // row it's found by name, without one by position. + let existing = if header_row { + old_cols.iter().find(|x| x.name.eq_ignore_ascii_case(name)) + } else if c >= old.start.col && c <= old.end.col { + old_cols.get((c - old.start.col) as usize) + } else { + None + }; + cols.push(match existing { + Some(x) => TableColumn { name: name.clone(), ..x.clone() }, + None => TableColumn { name: name.clone(), totals: TotalsFn::None, totals_label: None, formula: None, unique_name: None, xml: None }, + }); + } + let sheet = cx.sheet_mut(si)?; + if header_row { + // Headers hold constant text: a generated or de-duplicated name is written into its + // cell, so the header row and the column names never disagree. + for (c, col) in (r.start.col..=r.end.col).zip(&cols) { + let at = CellRef::new(r.start.row, c); + let constant_text = sheet.value(at).as_text() == Some(col.name.as_str()) && sheet.cell(at).is_some_and(|x| x.formula.is_none()); + if !constant_text { + let style = sheet.style_id(at); + sheet.cells.set(at, Cell { value: Value::text(col.name.as_str()), style, ..Default::default() }); + } + } + } + let t = sheet.tables.get_mut(ti).ok_or_else(|| bad("table", "gone"))?; t.columns = cols; t.range = r; cx.structural = true; @@ -854,6 +905,56 @@ fn table_resize(s: &mut Session, p: &Json) -> Result { }) } +/// Unique column names for a resized table, from each column's header text (`None` = empty), the +/// way Excel names them: a repeated header gets the lowest free suffix (`Qty`, `Qty2`, `Qty3`, +/// compared without case), and an empty header continues a `ColumnN` neighbour on its left +/// (`Column3` → `Column4`, or `Column32` when `Column4` is taken) or else takes the lowest free +/// `ColumnN`. +fn resized_column_names(texts: &[Option]) -> Vec { + use std::collections::{HashMap, HashSet}; + let mut taken: HashSet = HashSet::new(); + let mut next_suffix: HashMap = HashMap::new(); + // The lowest `ColumnN` not yet tried, so many empty headers stay linear. + let mut lowest = 1u64; + let mut names: Vec = Vec::with_capacity(texts.len()); + let dedupe = |base: &str, taken: &HashSet, next_suffix: &mut HashMap| { + let k = next_suffix.entry(base.to_lowercase()).or_insert(2); + let mut n = base.to_string(); + while taken.contains(&n.to_lowercase()) { + n = format!("{base}{k}"); + *k = k.saturating_add(1); + } + n + }; + for text in texts { + let name = match text { + Some(t) => dedupe(t, &taken, &mut next_suffix), + None => { + let left = names.last().and_then(|l| { + l.strip_prefix("Column") + .filter(|d| !d.starts_with('0') && !d.is_empty() && d.bytes().all(|b| b.is_ascii_digit())) + .and_then(|d| d.parse::().ok()) + }); + match left { + Some(n) => { + let cand = format!("Column{}", n.saturating_add(1)); + if taken.contains(&cand.to_lowercase()) { dedupe(&format!("Column{n}"), &taken, &mut next_suffix) } else { cand } + } + None => { + while taken.contains(&format!("column{lowest}")) { + lowest = lowest.saturating_add(1); + } + format!("Column{lowest}") + } + } + } + }; + taken.insert(name.to_lowercase()); + names.push(name); + } + names +} + fn from_csv(s: &mut Session, p: &Json) -> Result { let bytes = if let Some(t) = str_param(p, "text") { t.as_bytes().to_vec() diff --git a/crates/engine/tests/table_resize_overlap.rs b/crates/engine/tests/table_resize_overlap.rs index f8442cc016..31738024ae 100644 --- a/crates/engine/tests/table_resize_overlap.rs +++ b/crates/engine/tests/table_resize_overlap.rs @@ -27,3 +27,142 @@ fn resize_to_overlapping_range_still_works() { s.execute("table.resize", json!({"table":"T", "range":"B1:C2"})).unwrap(); assert_eq!(table_range(&s), "B1:C2"); } + +fn sheet(s: &Session) -> &gridcraft_engine::model::Sheet { + s.doc().unwrap().wb.active().unwrap() +} + +fn names(s: &Session, table: usize) -> Vec { + sheet(s).tables[table].columns.iter().map(|c| c.name.clone()).collect() +} + +fn headers(s: &Session, table: usize) -> Vec { + let sh = sheet(s); + let r = sh.tables[table].range; + (r.start.col..=r.end.col).map(|c| sh.value(gridcraft_core::CellRef::new(r.start.row, c)).display()).collect() +} + +fn with_headers(range: &str, row: &[&str]) -> Session { + let mut s = Session::new(); + s.new_workbook(); + let rows = vec![row.iter().map(|h| json!(h)).collect::>(), row.iter().map(|_| json!(1)).collect(), row.iter().map(|_| json!(2)).collect()]; + s.execute("range.setValues", json!({"range": range, "values": rows})).unwrap(); + s.execute("insert.table", json!({"range": range, "header": true, "name": "T"})).unwrap(); + s +} + +#[test] +fn resize_onto_another_table_is_rejected() { + // ft-3ir.10.23: from the sales sample, growing Table2 over Table1 left two overlapping tables. + let mut s = Session::new(); + s.execute("file.new", json!({"sample": "sales"})).unwrap(); + s.execute("insert.table", json!({"header": true, "range": "M2:N5"})).unwrap(); + s.execute("insert.table", json!({"header": true, "range": "P2:Q5"})).unwrap(); + let e = s.execute("table.resize", json!({"range": "M2:Q5", "table": "Table2"})).unwrap_err().to_string(); + assert!(e.contains("overlap another table"), "{e}"); + let ranges: Vec = sheet(&s).tables.iter().map(|t| t.range.a1()).collect(); + assert!(ranges.contains(&"M2:N5".to_string()) && ranges.contains(&"P2:Q5".to_string()), "{ranges:?}"); + // Down over a table below, or around a whole table, is refused too; next to it is fine. + let mut s = table(); + s.execute("range.setValues", json!({"range": "A5", "values": [["c"], ["1"]]})).unwrap(); + s.execute("insert.table", json!({"range": "A5:A6", "header": true, "name": "U"})).unwrap(); + assert!(s.execute("table.resize", json!({"table": "T", "range": "A1:B5"})).is_err()); + assert!(s.execute("table.resize", json!({"table": "T", "range": "A1:C9"})).is_err()); + s.execute("table.resize", json!({"table": "T", "range": "A1:B4"})).unwrap(); + assert_eq!(table_range(&s), "A1:B4"); +} + +#[test] +fn resize_onto_merged_cells_pivot_or_array_is_rejected() { + let mut s = table(); + s.execute("home.mergeCenter", json!({"range": "D2:E2"})).unwrap(); + let e = s.execute("table.resize", json!({"table": "T", "range": "A1:D2"})).unwrap_err().to_string(); + assert!(e.contains("merged"), "{e}"); + assert_eq!(table_range(&s), "A1:B2"); + + let mut s = table(); + s.execute("selection.set", json!({"range": "D1:D2"})).unwrap(); + s.execute("cell.set", json!({"cell": "D1", "input": "=ROW(1:2)", "array": true})).unwrap(); + let e = s.execute("table.resize", json!({"table": "T", "range": "A1:D2"})).unwrap_err().to_string(); + assert!(e.contains("array"), "{e}"); + assert_eq!(table_range(&s), "A1:B2"); + + let mut s = table(); + s.execute("range.setValues", json!({"range": "H1", "values": [["k", "v"], ["x", "1"], ["y", "2"]]})).unwrap(); + s.execute("insert.pivotTable", json!({"source": "Sheet1!$H$1:$I$3", "destination": "Sheet1!D1", "rows": ["k"], "values": ["v"]})).unwrap(); + assert!(!sheet(&s).pivots.is_empty()); + let e = s.execute("table.resize", json!({"table": "T", "range": "A1:E2"})).unwrap_err().to_string(); + assert!(e.contains("PivotTable"), "{e}"); + assert_eq!(table_range(&s), "A1:B2"); +} + +#[test] +fn resize_onto_a_spill_is_allowed() { + // Excel lets a table take in a spilled formula (the spill then shows #SPILL!). + let mut s = table(); + s.execute("cell.set", json!({"cell": "D2", "input": "=SEQUENCE(1,2)"})).unwrap(); + s.execute("table.resize", json!({"table": "T", "range": "A1:D2"})).unwrap(); + assert_eq!(table_range(&s), "A1:D2"); +} + +#[test] +fn resized_in_columns_get_excel_names_written_into_the_header_row() { + // ft-3ir.10.26: a resize whose new columns repeated a name left the header row and the column + // names out of step ("Column3" in memory, "Column32" after reopening). + let mut s = Session::new(); + s.execute("file.new", json!({"sample": "grades"})).unwrap(); + s.execute("home.formatAsTable", json!({"header": "x", "range": "I3:K9", "style": false})).unwrap(); + s.execute("table.resize", json!({"range": "K3:N7", "table": "Table1"})).unwrap(); + let ti = sheet(&s).tables.iter().position(|t| t.name == "Table1").unwrap(); + assert_eq!(names(&s, ti), headers(&s, ti)); + let mut seen = std::collections::HashSet::new(); + assert!(names(&s, ti).iter().all(|n| seen.insert(n.to_lowercase())), "{:?}", names(&s, ti)); + let bytes = gridcraft_engine::io::save_bytes(&s.doc().unwrap().wb, "t.xlsx").unwrap(); + let (back, _) = gridcraft_engine::io::open_bytes("t.xlsx", &bytes).unwrap(); + let t = back.active().unwrap().tables.iter().find(|t| t.name == "Table1").unwrap(); + assert_eq!(t.columns.iter().map(|c| c.name.clone()).collect::>(), names(&s, ti)); + + // Names Excel gives (observed): an empty header continues a ColumnN on its left, else takes + // the lowest free ColumnN; a repeated header gets the next free suffix. + let cases: [(&str, &[&str], &str, &[&str]); 5] = [ + ("A1:B3", &["a", "b"], "A1:E3", &["a", "b", "Column1", "Column2", "Column3"]), + ("A1:C3", &["Column2", "b", "c"], "A1:F3", &["Column2", "b", "c", "Column1", "Column12", "Column13"]), + ("A1:B3", &["Column3", "b"], "A1:E3", &["Column3", "b", "Column1", "Column2", "Column22"]), + ("A1:B3", &["Column1", "b"], "A1:D3", &["Column1", "b", "Column2", "Column3"]), + ("A1:C3", &["Column1", "Column2", "Column3"], "C1:F3", &["Column3", "Column4", "Column5", "Column6"]), + ]; + for (range, row, to, want) in cases { + let mut s = with_headers(range, row); + s.execute("table.resize", json!({"table": "T", "range": to})).unwrap(); + assert_eq!(names(&s, 0), want.iter().map(|w| w.to_string()).collect::>(), "{row:?} -> {to}"); + assert_eq!(headers(&s, 0), names(&s, 0), "{row:?} -> {to}"); + } + + // Headers already in the new columns are kept, made unique and turned into text. + let mut s = with_headers("A1:B3", &["x", "y"]); + s.execute("range.setValues", json!({"range": "C1", "values": [["X", "x", 5]]})).unwrap(); + s.execute("cell.set", json!({"cell": "F1", "input": "=1+1"})).unwrap(); + s.execute("table.resize", json!({"table": "T", "range": "A1:F3"})).unwrap(); + assert_eq!(names(&s, 0), ["x", "y", "X2", "x3", "5", "2"]); + assert_eq!(headers(&s, 0), names(&s, 0)); + assert!(sheet(&s).cell(gridcraft_core::CellRef::new(0, 5)).is_some_and(|c| c.formula.is_none())); +} + +#[test] +fn resizing_a_table_without_a_header_row_keeps_its_names_and_data() { + let mut s = with_headers("A1:B3", &["a", "b"]); + // As a file can have it: the table starts at its first data row (A2:B3), with no header row. + { + let wb = std::sync::Arc::make_mut(&mut s.doc_mut().unwrap().wb); + let t = &mut std::sync::Arc::make_mut(&mut wb.sheets[0]).tables[0]; + t.header_row = false; + t.range.start.row = 1; + } + let r = sheet(&s).tables[0].range; + assert!(!sheet(&s).tables[0].header_row); + let to = gridcraft_core::RangeRef::new(r.start, gridcraft_core::CellRef::new(r.end.row, r.end.col + 1)); + let first = sheet(&s).value(r.start).display(); + s.execute("table.resize", json!({"table": "T", "range": to.a1()})).unwrap(); + assert_eq!(names(&s, 0), ["a", "b", "Column1"]); + assert_eq!(sheet(&s).value(r.start).display(), first); +} 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 04/55] 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 cd28cfbfa3..2619f59bdc 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 aa250b9b0d..14d9549cae 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 46e981d0aa..6679af1d4b 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 83955ee1fe..71600c920a 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 daac03daaa..ba499b765c 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 0294f378f4..d9396bfef3 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 5b79438dbb..0f66119923 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 ceaf3e26d3..363715d5dd 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 2aa18069f6..d624f44c84 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 cf567f8bd6..668f54c40d 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 07797d70d0..3ea4097d59 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 744c6cde44ba1b9ab65b630d0946eae139e0a88d Mon Sep 17 00:00:00 2001 From: Vedran Dobos <19259909+vedran-dobos@users.noreply.github.com> Date: Thu, 22 Oct 2026 07:51:50 +0200 Subject: [PATCH 05/55] Tests: the table-filter AutoFit test measures the heading with the grid's font `table_filter_autofit_works_through_command_and_header_double_click` checked the fitted column against the engine's text estimate, but AutoFit measures with the font the grid draws (#1316). Where that font is installed (seen on Windows 11) it is narrower than the estimate, so the test failed there at 50% zoom; on Linux CI the font is missing and both fall back to the estimate. The test now measures the heading the way AutoFit and the grid do. Co-Authored-By: Claude Opus 5.5 --- crates/ui-egui/tests/header_autofit.rs | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/crates/ui-egui/tests/header_autofit.rs b/crates/ui-egui/tests/header_autofit.rs index 5e123809fb..1dbf7d2751 100644 --- a/crates/ui-egui/tests/header_autofit.rs +++ b/crates/ui-egui/tests/header_autofit.rs @@ -183,7 +183,9 @@ fn table_filter_autofit_works_through_command_and_header_double_click() { let rect = geo.cell_rect(sheet, cell); let button = gridcraft_ui_egui::grid::filter_button_rect(&geo, sheet, cell); let style = app.session.active().unwrap().wb.styles.get(sheet.style_id(cell)); - let text_width = gridcraft_engine::cmd::format::approx_text_width("Quarterly Revenue", style.font.size, style.font.bold) * geo.z; + // The heading as the grid draws it: AutoFit measures with that font too (#1316), which + // is narrower than the engine's estimate wherever the font is installed. + let text_width = gridcraft_ui_egui::theme::cell_text_width(&h.ctx, "Quarterly Revenue", &style.font, true) * geo.z; assert!(rect.left() + text_width + 2.5 * geo.z < button.left(), "heading overlaps filter: zoom={zoom}, double_click={double_click}"); assert_eq!(app.session.active().unwrap().undo.len(), 1); h.state_mut().session.execute("edit.undo", json!({})).unwrap(); 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 06/55] 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 2619f59bdc..f6b92562c9 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 a9428fa23a..2d17ca1334 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 d624f44c84..1535230406 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 3ea4097d59..bb02254f57 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 07/55] 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 f6b92562c9..ad089f1dfd 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 81e523e431d487acfe0892345eecfee673a609db Mon Sep 17 00:00:00 2001 From: Vedran Dobos <19259909+vedran-dobos@users.noreply.github.com> Date: Thu, 22 Oct 2026 23:27:53 +0200 Subject: [PATCH 08/55] AutoFit: a table's header is measured in the table style's bold font AutoFit Column Width measured every cell in its own style, but the grid draws a table's cells in the table style, which makes the header row bold, so a bold heading could be fitted too narrow. AutoFit now measures a table cell in the font the table gives it. (Found by CodeRabbit on #2269.) The table-filter AutoFit test checked the fitted column against the engine's text estimate, while AutoFit measures with the font the grid draws (#1316); where that font is installed the estimate is wider, so the test failed off Linux. It now measures the heading as the grid draws it, in the table style's font. Co-Authored-By: Claude Opus 5.5 --- crates/engine/src/cmd/format.rs | 27 ++++++++++++++++--- crates/engine/tests/autofit_filter_buttons.rs | 3 +++ crates/ui-egui/tests/header_autofit.rs | 12 ++++++--- docs/ui-parity.md | 3 ++- 4 files changed, 36 insertions(+), 9 deletions(-) diff --git a/crates/engine/src/cmd/format.rs b/crates/engine/src/cmd/format.rs index cd28cfbfa3..2bdb6df96a 100644 --- a/crates/engine/src/cmd/format.rs +++ b/crates/engine/src/cmd/format.rs @@ -1123,7 +1123,8 @@ fn autofit_cols(s: &mut Session, p: &Json) -> Result { edit(s, |cx| { let Some(sh) = cx.wb.sheet(si) else { return Ok(Json::Null) }; let mut widths = Vec::new(); - let mut measured: std::collections::HashMap> = Default::default(); + // Keyed by style and boldness: a table's style can make a cell bold (its header row). + let mut measured: std::collections::HashMap<(StyleId, bool), std::collections::HashMap> = Default::default(); let mut distinct = 0usize; let used = sh.used_range(); for (a, b) in lines { @@ -1137,22 +1138,26 @@ fn autofit_cols(s: &mut Session, p: &Json) -> Result { } let id = sh.style_id(cell); let st = cx.wb.styles.get(id); + // The font as the grid draws the cell: in a table, the table style's (a bold + // header row), not only the cell's own. + let table_font = sh.table_at(cell).map(|t| crate::tables::table_cell_style(&cx.wb, si, t, cell).font); + let font = table_font.as_ref().unwrap_or(&st.font); let text = crate::display::cell_text(&cx.wb, sh, cell); for line in text.lines() { let w = match &measure { Some(m) => { - let known = measured.entry(id).or_default(); + let known = measured.entry((id, font.bold)).or_default(); match known.get(line) { Some(w) => *w, None => { - let w = m(line, &st.font, distinct < EXACT_TEXT_WIDTHS); + let w = m(line, font, distinct < EXACT_TEXT_WIDTHS); known.insert(line.to_owned(), w); distinct += 1; w } } } - None => approx_text_width(line, st.font.size, st.font.bold), + None => approx_text_width(line, font.size, font.bold), }; max = max.max(w + 6.0 + st.align.indent as f32 * 9.0 + sh.filter_button_space(cell)); } @@ -1274,6 +1279,20 @@ mod tests { assert_eq!(s.execute("cell.get", json!({"cell": "A1"})).unwrap()["style"]["num_fmt"], "0.00"); } + /// A table draws its header row bold; AutoFit measures that, not the cell's own plain font. + #[test] + fn autofit_measures_a_table_header_in_the_table_style_font() { + let mut s = crate::Session::new(); + s.new_workbook(); + let heading = "Quarterly Revenue by Region"; + s.execute("range.setValues", json!({"range": "A1", "values": [[heading, heading], [1, 1]]})).unwrap(); + s.execute("insert.table", json!({"range": "A1:A2", "header": true})).unwrap(); + s.execute("home.autofitColumnWidth", json!({"cols": "A:B"})).unwrap(); + let sh = s.active().unwrap().wb.active().unwrap(); + let (table, plain) = (sh.col_width(0) - sh.filter_button_space(CellRef::new(0, 0)), sh.col_width(1)); + assert!(table > plain, "the bold table header is wider than the same plain text: {table} vs {plain}"); + } + #[test] fn width_units() { assert_eq!(chars_to_points(8.43), 64.0); diff --git a/crates/engine/tests/autofit_filter_buttons.rs b/crates/engine/tests/autofit_filter_buttons.rs index dbf25eced0..2b27ad2b8a 100644 --- a/crates/engine/tests/autofit_filter_buttons.rs +++ b/crates/engine/tests/autofit_filter_buttons.rs @@ -7,6 +7,9 @@ fn table() -> Session { s.new_workbook(); s.execute("range.setValues", json!({"range":"A1", "values":[["Quarterly Revenue"], ["1"]]})).unwrap(); s.execute("insert.table", json!({"range":"A1:A2", "header":true})).unwrap(); + // Bold in its own style too, so the table style's bold header row changes nothing here and + // these tests compare only the filter button's room, with or without the table. + s.execute("home.bold", json!({"range":"A1", "on": true})).unwrap(); s } diff --git a/crates/ui-egui/tests/header_autofit.rs b/crates/ui-egui/tests/header_autofit.rs index 1dbf7d2751..57e621c57c 100644 --- a/crates/ui-egui/tests/header_autofit.rs +++ b/crates/ui-egui/tests/header_autofit.rs @@ -182,10 +182,14 @@ fn table_filter_autofit_works_through_command_and_header_double_click() { let cell = gridcraft_engine::core::CellRef::new(0, 0); let rect = geo.cell_rect(sheet, cell); let button = gridcraft_ui_egui::grid::filter_button_rect(&geo, sheet, cell); - let style = app.session.active().unwrap().wb.styles.get(sheet.style_id(cell)); - // The heading as the grid draws it: AutoFit measures with that font too (#1316), which - // is narrower than the engine's estimate wherever the font is installed. - let text_width = gridcraft_ui_egui::theme::cell_text_width(&h.ctx, "Quarterly Revenue", &style.font, true) * geo.z; + // The heading as the grid draws it: in the table style's font, bold in the header row, + // measured as AutoFit measures (#1316), which is narrower than the engine's estimate + // wherever the font is installed. + let wb = &app.session.active().unwrap().wb; + let table = sheet.table_at(cell).expect("A1 is the table's header"); + let font = gridcraft_engine::tables::table_cell_style(wb, wb.active_sheet, table, cell).font; + assert!(font.bold, "the table style draws its header bold"); + let text_width = gridcraft_ui_egui::theme::cell_text_width(&h.ctx, "Quarterly Revenue", &font, true) * geo.z; assert!(rect.left() + text_width + 2.5 * geo.z < button.left(), "heading overlaps filter: zoom={zoom}, double_click={double_click}"); assert_eq!(app.session.active().unwrap().undo.len(), 1); h.state_mut().session.execute("edit.undo", json!({})).unwrap(); diff --git a/docs/ui-parity.md b/docs/ui-parity.md index 07797d70d0..27ac154e50 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 (AutoFit Column Width measures a table's header in the table style's bold font; 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 | AutoFit Column Width measures a table's cells in the font the table style draws them in, so a bold header row is fitted bold; it measured the cell's own, plain font and could leave a bold heading too 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 a6bedd5153a3b2787eee35b5769e58cab2ab8efc Mon Sep 17 00:00:00 2001 From: Harrison Booth <73434116+Harrison-Booth@users.noreply.github.com> Date: Fri, 23 Oct 2026 16:41:30 -0500 Subject: [PATCH 09/55] Docs: keep the UI parity revision table well-formed --- docs/ui-parity.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/docs/ui-parity.md b/docs/ui-parity.md index 75b7903dd9..d51d556b82 100644 --- a/docs/ui-parity.md +++ b/docs/ui-parity.md @@ -174,8 +174,8 @@ scrollbar bugs 2–4 · pixel/feel pass against observed Excel 7–12. ## Revision history -| Date | Change | Summary | | 2026-10-15 | minor | F8 Extend Selection and Shift+F8 Add or Remove Selection modes, shown in the status bar (`ui.selectionMode`) | +| Date | Change | Summary | |---|---|---| | 2026-10-23 | minor | Frozen panes: Page Up, Ctrl+Up and Shift variants that move from the scrolled rows into the frozen ones bring the scrolled rows back to the top, so the rows in between are seen again (Page Up from far down used to end on row 1 with the view still a page down); Ctrl+Left and Alt+Page Up do the same for frozen columns. Other ways of selecting a frozen cell (click, Find, Go To, Undo, formula pointing) leave the view where it is | | 2026-10-23 | minor | After a left-drag of the fill handle an Auto Fill Options button sits below the filled cells; its menu redoes the fill as Copy Cells, Fill Series, Fill Formatting Only or Fill Without Formatting (undoes the drag's fill, then `edit.autoFill` in that mode). It goes away when the workbook changes or the selection moves (#1403) | From a4309846b2f7d44b08385027c47dbdd0e9788eb0 Mon Sep 17 00:00:00 2001 From: Harrison Booth <73434116+Harrison-Booth@users.noreply.github.com> Date: Fri, 23 Oct 2026 16:58:55 -0500 Subject: [PATCH 10/55] Keyboard: Add-mode header drags keep earlier areas; Shift-click ends a pending area --- crates/ui-egui/src/grid.rs | 23 +++++++++++++++++++---- docs/ui-parity.md | 2 +- 2 files changed, 20 insertions(+), 5 deletions(-) diff --git a/crates/ui-egui/src/grid.rs b/crates/ui-egui/src/grid.rs index 415bb40805..ab478b5875 100644 --- a/crates/ui-egui/src/grid.rs +++ b/crates/ui-egui/src/grid.rs @@ -185,6 +185,8 @@ pub struct GridState { /// Add mode: the last area is the cell an arrow key moved to, not yet extended, so the next /// arrow moves it again instead of keeping it. pub add_pending: bool, + /// Add mode header drag: the areas kept from before the drag, which the dragged range joins. + pub header_drag_base: Vec, } /// Excel's keyboard selection modes, shown in the status bar. In Extend mode (F8) arrow keys and @@ -2369,6 +2371,7 @@ fn interact(app: &mut SheetApp, ui: &mut egui::Ui, resp: &egui::Response, geo: & return; } let range = if sel_mods.shift { RangeRef::cols(sel.anchor.col.min(c), sel.anchor.col.max(c)) } else { RangeRef::cols(c, c) }; + app.grid.header_drag_base = add_mode_base(app); select_ranges(app, range, sel_mods.command, CellRef::new(geo.row_at(sh, geo.cells.top() + 1.0), c)); app.grid.drag = Drag::Cols(if sel_mods.shift { sel.anchor.col } else { c }); return; @@ -2383,6 +2386,7 @@ fn interact(app: &mut SheetApp, ui: &mut egui::Ui, resp: &egui::Response, geo: & return; } let range = if sel_mods.shift { RangeRef::rows(sel.anchor.row.min(r), sel.anchor.row.max(r)) } else { RangeRef::rows(r, r) }; + app.grid.header_drag_base = add_mode_base(app); select_ranges(app, range, sel_mods.command, CellRef::new(r, geo.col_at(sh, geo.cells.left() + 1.0))); app.grid.drag = Drag::Rows(if sel_mods.shift { sel.anchor.row } else { r }); return; @@ -2475,6 +2479,7 @@ fn interact(app: &mut SheetApp, ui: &mut egui::Ui, resp: &egui::Response, geo: & } app.grid.last_click = Some((c, now)); if sel_mods.shift { + app.grid.add_pending = false; let _ = app.session.run("selection.set", json!({"range": RangeRef::new(sel.anchor, c).a1(), "active": sel.active.a1()})); if let Some(d) = app.session.active_mut() { d.selection.anchor = sel.anchor; @@ -2549,14 +2554,16 @@ fn interact(app: &mut SheetApp, ui: &mut egui::Ui, resp: &egui::Response, geo: & } Drag::Rows(anchor) => { let r = geo.row_at(sh, p.y); - let _ = - app.session.run("selection.set", json!({"range": RangeRef::rows(anchor.min(r), anchor.max(r)).a1(), "active": sel.active.a1()})); + let range = RangeRef::rows(anchor.min(r), anchor.max(r)).a1(); + let ranges = app.grid.header_drag_base.iter().map(String::as_str).chain([range.as_str()]).collect::>().join(","); + let _ = app.session.run("selection.set", json!({"range": ranges, "active": sel.active.a1()})); scroll_by(app, vec2(0.0, auto.y)); } Drag::Cols(anchor) => { let c = geo.col_at(sh, p.x); - let _ = - app.session.run("selection.set", json!({"range": RangeRef::cols(anchor.min(c), anchor.max(c)).a1(), "active": sel.active.a1()})); + let range = RangeRef::cols(anchor.min(c), anchor.max(c)).a1(); + let ranges = app.grid.header_drag_base.iter().map(String::as_str).chain([range.as_str()]).collect::>().join(","); + let _ = app.session.run("selection.set", json!({"range": ranges, "active": sel.active.a1()})); scroll_by(app, vec2(auto.x, 0.0)); } Drag::MoveCols { source, .. } => { @@ -3047,6 +3054,14 @@ fn add_mode_move(app: &mut SheetApp, dr: i64, dc: i64, shift: bool, jump: bool) app.grid.add_pending = !kept; } +/// The active sheet's areas in Add mode, as `selection.set` takes them; empty in other modes. +fn add_mode_base(app: &SheetApp) -> Vec { + if app.grid.selection_mode != SelectionMode::Add { + return Vec::new(); + } + app.session.active().map(|d| d.selection.ranges.iter().map(|x| x.a1()).collect()).unwrap_or_default() +} + fn select_ranges(app: &mut SheetApp, r: RangeRef, add: bool, active: CellRef) { // A clicked area is kept: the next Add mode arrow starts a new one. app.grid.add_pending = false; diff --git a/docs/ui-parity.md b/docs/ui-parity.md index d51d556b82..f62a30d5be 100644 --- a/docs/ui-parity.md +++ b/docs/ui-parity.md @@ -174,9 +174,9 @@ scrollbar bugs 2–4 · pixel/feel pass against observed Excel 7–12. ## Revision history -| 2026-10-15 | minor | F8 Extend Selection and Shift+F8 Add or Remove Selection modes, shown in the status bar (`ui.selectionMode`) | | Date | Change | Summary | |---|---|---| +| 2026-10-15 | minor | F8 Extend Selection and Shift+F8 Add or Remove Selection modes, shown in the status bar (`ui.selectionMode`) | | 2026-10-23 | minor | Frozen panes: Page Up, Ctrl+Up and Shift variants that move from the scrolled rows into the frozen ones bring the scrolled rows back to the top, so the rows in between are seen again (Page Up from far down used to end on row 1 with the view still a page down); Ctrl+Left and Alt+Page Up do the same for frozen columns. Other ways of selecting a frozen cell (click, Find, Go To, Undo, formula pointing) leave the view where it is | | 2026-10-23 | minor | After a left-drag of the fill handle an Auto Fill Options button sits below the filled cells; its menu redoes the fill as Copy Cells, Fill Series, Fill Formatting Only or Fill Without Formatting (undoes the drag's fill, then `edit.autoFill` in that mode). It goes away when the workbook changes or the selection moves (#1403) | | 2026-10-22 | minor | Show Outline Symbols (`view.showOutlineSymbols`, Ctrl+8): a sheet can hide the outline's level buttons and brackets while keeping its outline, as Excel saves with `showOutlineSymbols="0"` (read and written); the grid then gives the bands no room | From 41a1a3f8bc8611be25f853e70350fecb97e87a35 Mon Sep 17 00:00:00 2001 From: Harrison Booth <73434116+Harrison-Booth@users.noreply.github.com> Date: Sat, 24 Oct 2026 15:21:08 -0500 Subject: [PATCH 11/55] Keyboard: Add-mode Shift-click keeps earlier areas; Dutch status labels --- crates/ui-egui/src/grid.rs | 8 +++++++- crates/ui-egui/src/i18n/nl.rs | 2 ++ 2 files changed, 9 insertions(+), 1 deletion(-) diff --git a/crates/ui-egui/src/grid.rs b/crates/ui-egui/src/grid.rs index 81d3b19298..4d13eee49b 100644 --- a/crates/ui-egui/src/grid.rs +++ b/crates/ui-egui/src/grid.rs @@ -2492,8 +2492,14 @@ fn interact(app: &mut SheetApp, ui: &mut egui::Ui, resp: &egui::Response, geo: & } app.grid.last_click = Some((c, now)); if sel_mods.shift { + // Add mode keeps the areas already selected and drops only the provisional area it made itself. + let mut ranges = add_mode_base(app); + if app.grid.add_pending { + ranges.pop(); + } app.grid.add_pending = false; - let _ = app.session.run("selection.set", json!({"range": RangeRef::new(sel.anchor, c).a1(), "active": sel.active.a1()})); + ranges.push(RangeRef::new(sel.anchor, c).a1()); + let _ = app.session.run("selection.set", json!({"range": ranges.join(","), "active": sel.active.a1()})); if let Some(d) = app.session.active_mut() { d.selection.anchor = sel.anchor; } diff --git a/crates/ui-egui/src/i18n/nl.rs b/crates/ui-egui/src/i18n/nl.rs index c1f952357f..1f35904ddb 100644 --- a/crates/ui-egui/src/i18n/nl.rs +++ b/crates/ui-egui/src/i18n/nl.rs @@ -278,6 +278,8 @@ pub(super) fn translate(text: &str) -> Option<&'static str> { "Point" => "Aanwijzen", "Calculate" => "Berekenen", "Select destination and press Enter or choose Paste" => "Selecteer de bestemming en druk op Enter of kies Plakken", + "Extend Selection" => "Selectie uitbreiden", + "Add or Remove Selection" => "Selectie toevoegen of verwijderen", "General" => "Algemeen", "Number" => "Getal", "Currency" => "Valuta", From bf9531954df1cbbe55c5a61f7af1ddd2ab8bed11 Mon Sep 17 00:00:00 2001 From: Harrison Booth <73434116+Harrison-Booth@users.noreply.github.com> Date: Sat, 24 Oct 2026 15:25:47 -0500 Subject: [PATCH 12/55] Keyboard: test that an Add-mode header drag keeps the earlier areas --- crates/ui-egui/tests/it/keyboard_shortcuts.rs | 32 +++++++++++++++++++ 1 file changed, 32 insertions(+) diff --git a/crates/ui-egui/tests/it/keyboard_shortcuts.rs b/crates/ui-egui/tests/it/keyboard_shortcuts.rs index 2c8a863fee..6a75c5f5ac 100644 --- a/crates/ui-egui/tests/it/keyboard_shortcuts.rs +++ b/crates/ui-egui/tests/it/keyboard_shortcuts.rs @@ -218,6 +218,38 @@ fn clicks_extend_or_add_in_the_selection_modes() { assert_eq!(selection_a1(&h), "B2:D4,H8,H9"); } +/// A point in the column header band, above `col`'s cells. +fn column_header_point(h: &Harness, col: &str) -> egui::Pos2 { + let app = h.state(); + let sheet = app.session.active().unwrap().wb.active().unwrap(); + let geo = Geo::new(sheet, app.grid.rect.unwrap(), app.view().scroll); + let x = geo.cell_rect(sheet, CellRef::parse(&format!("{col}1")).unwrap()).center().x; + egui::pos2(x, geo.head_top() + 4.0) +} + +fn drag(h: &mut Harness, from: egui::Pos2, to: egui::Pos2) { + h.input_mut().events.push(Event::PointerMoved(from)); + h.run_steps(1); + h.input_mut().events.push(Event::PointerButton { pos: from, button: PointerButton::Primary, pressed: true, modifiers: Modifiers::NONE }); + h.run_steps(1); + h.input_mut().events.push(Event::PointerMoved(to)); + h.run_steps(2); + h.input_mut().events.push(Event::PointerButton { pos: to, button: PointerButton::Primary, pressed: false, modifiers: Modifiers::NONE }); + h.run_steps(2); +} + +#[test] +fn add_mode_header_drag_keeps_the_earlier_areas() { + let mut h = harness(book("B2")); + key(&mut h, Key::F8, Modifiers::SHIFT); + click(&mut h, "F6"); + assert_eq!(selection_a1(&h), "B2,F6"); + h.state_mut().grid.last_click = None; + let (from, to) = (column_header_point(&h, "H"), column_header_point(&h, "J")); + drag(&mut h, from, to); + assert_eq!(selection_a1(&h), "B2,F6,H:J", "a header drag in Add mode adds its columns and keeps the areas already selected"); +} + #[test] fn selection_mode_command_sets_and_reports_without_a_dialog() { let mut h = harness(book("A1")); From 8471ccace5a2a05b6a312b13021cbe0589ed248e Mon Sep 17 00:00:00 2001 From: Harrison Booth <73434116+Harrison-Booth@users.noreply.github.com> Date: Sat, 24 Oct 2026 15:33:04 -0500 Subject: [PATCH 13/55] Keyboard: Add mode keeps areas for Home and End; a click inside a larger area removes it --- crates/ui-egui/src/grid.rs | 21 ++++++++++++++++++--- 1 file changed, 18 insertions(+), 3 deletions(-) diff --git a/crates/ui-egui/src/grid.rs b/crates/ui-egui/src/grid.rs index 4d13eee49b..fc4fb8176d 100644 --- a/crates/ui-egui/src/grid.rs +++ b/crates/ui-egui/src/grid.rs @@ -3089,10 +3089,15 @@ fn add_mode_base(app: &SheetApp) -> Vec { fn select_ranges(app: &mut SheetApp, r: RangeRef, add: bool, active: CellRef) { // A clicked area is kept: the next Add mode arrow starts a new one. app.grid.add_pending = false; - let current: Vec = - if add { app.session.active().map(|d| d.selection.ranges.iter().map(|x| x.a1()).collect()).unwrap_or_default() } else { vec![] }; + let current: Vec = if add { app.session.active().map(|d| d.selection.ranges.clone()).unwrap_or_default() } else { vec![] }; let clicked = r.a1(); - let ranges = toggled_ranges(current, clicked.clone(), add); + // A click on a cell inside a larger kept area removes that area, as a click on a single-cell area does. + let inside = + (add && current.len() > 1 && r.start == r.end).then(|| current.iter().position(|x| x.a1() != clicked && x.contains(r.start))).flatten(); + let ranges: Vec = match inside { + Some(i) => current.iter().enumerate().filter(|(j, _)| *j != i).map(|(_, x)| x.a1()).collect(), + None => toggled_ranges(current.iter().map(|x| x.a1()).collect(), clicked.clone(), add), + }; // A removed area takes the active cell with it; `selection.set` then puts it at the start of the last area. let params = if ranges.contains(&clicked) { json!({"range": ranges.join(","), "active": active.a1()}) } else { json!({"range": ranges.join(",")}) }; @@ -3191,6 +3196,16 @@ fn keyboard(app: &mut SheetApp, ctx: &egui::Context, resp: &egui::Response, geo: Key::PageUp if !cmd => mv(app, -page, 0), Key::PageDown => app.run_or_alert("sheet.next", json!({})), Key::PageUp => app.run_or_alert("sheet.previous", json!({})), + // Add mode: Home and End move the active cell as arrows do, keeping the selected areas. + Key::Home | Key::End if app.grid.selection_mode == SelectionMode::Add && (cmd || key == Key::Home) => { + let a = app.session.active().map(|d| d.selection.active).unwrap_or_default(); + let to = match key { + Key::Home if cmd => CellRef::new(sh.freeze.map(|f| f.0).unwrap_or(0), sh.freeze.map(|f| f.1).unwrap_or(0)), + Key::End => sh.used_range().map(|u| u.end).unwrap_or_default(), + _ => CellRef::new(a.row, 0), + }; + add_mode_move(app, i64::from(to.row) - i64::from(a.row), i64::from(to.col) - i64::from(a.col), false, false); + } Key::Home if cmd => { let r = sh.freeze.map(|f| f.0).unwrap_or(0); let c = sh.freeze.map(|f| f.1).unwrap_or(0); From ec77c810f80ee08a74a7046b295c0af7432cbc1e Mon Sep 17 00:00:00 2001 From: Harrison Booth <73434116+Harrison-Booth@users.noreply.github.com> Date: Sat, 24 Oct 2026 15:35:54 -0500 Subject: [PATCH 14/55] XLSX: report sheet extensions with unmodelled children as dropped; consolidate xlsx parity rows --- crates/xlsx/src/extlist.rs | 4 ++++ crates/xlsx/src/tests/extlist.rs | 23 +++++++++++++++++++++++ docs/file-format-parity.md | 10 +--------- 3 files changed, 28 insertions(+), 9 deletions(-) diff --git a/crates/xlsx/src/extlist.rs b/crates/xlsx/src/extlist.rs index ce9bc6e3fc..9bd27eddc7 100644 --- a/crates/xlsx/src/extlist.rs +++ b/crates/xlsx/src/extlist.rs @@ -169,6 +169,10 @@ pub(crate) fn keep_workbook(cx: &mut Ctx<'_>, ext_lst: Option<&El>, p: &mut Pres /// sheet reader. pub(crate) fn read_sheet_ext(cx: &mut Ctx<'_>, ext: &El) { if ext.children.iter().any(|c| SHEET_MODELLED.contains(&c.name.as_str())) { + // The sheet reader keeps its modelled children; any other child of this extension is lost. + if ext.children.iter().any(|c| !SHEET_MODELLED.contains(&c.name.as_str())) { + dropped(&mut cx.sheet_exts_dropped, uri(ext)); + } return; } let u = uri(ext); diff --git a/crates/xlsx/src/tests/extlist.rs b/crates/xlsx/src/tests/extlist.rs index 79c49c50c9..cbd6aa780f 100644 --- a/crates/xlsx/src/tests/extlist.rs +++ b/crates/xlsx/src/tests/extlist.rs @@ -108,6 +108,29 @@ fn a_sheet_with_only_kept_extensions_gets_an_ext_list() { assert!(!part(&saved, "xl/workbook.xml").contains("extLst")); } +#[test] +fn a_modelled_extension_with_an_unmodelled_child_is_reported_dropped() { + let sheet = format!( + r#""# + ); + let rels = format!( + r#""# + ); + let workbook = format!( + r#""# + ); + let bytes = make_zip(&[ + ("[Content_Types].xml", CT.as_bytes()), + ("_rels/.rels", ROOT_RELS.as_bytes()), + ("xl/workbook.xml", workbook.as_bytes()), + ("xl/_rels/workbook.xml.rels", rels.as_bytes()), + ("xl/worksheets/sheet1.xml", sheet.as_bytes()), + ]); + let (_, report) = read_xlsx(&bytes).unwrap(); + let w = report.warnings.iter().find(|w| w.starts_with("sheet \"A\":")).unwrap_or_else(|| panic!("{:?}", report.warnings)); + assert!(w.contains("{05C60535-1F16-4fd2-B633-F4F36F0B64E0}"), "{w}"); +} + #[test] fn a_new_workbook_has_no_ext_lists() { let saved = write_xlsx(&gridcraft_model::Workbook::new()).unwrap(); diff --git a/docs/file-format-parity.md b/docs/file-format-parity.md index 97ad580265..df967ad52f 100644 --- a/docs/file-format-parity.md +++ b/docs/file-format-parity.md @@ -41,15 +41,7 @@ values) is still dropped. | Format | Excel | GridCraft read | GridCraft write | Fidelity / notes | Tests | |---|---|---|---|---|---| -| `.xlsx` Excel Workbook (transitional) | R/W, native | yes | yes | Cells, shared/array/dynamic formulas, shared strings (with their Japanese phonetic runs — ふりがな — kept through open + save: `` offsets and readings and `` are written back next to the same string; the table holds each text once, so duplicate `` items whose text is the same but whose readings differ keep only the first reading, with a warning on open), styles, themes, merges, CF, validation, tables, comments and notes, hyperlinks, names, freeze panes, outline, print settings, pictures, shapes, charts (simplified, see [chart-parity.md](chart-parity.md)), sparklines, PivotTables (caches and tables), protection, calc settings, show objects (`workbookPr showObjects`). **Kept unchanged on save (pass-through, `passthrough.rs`):** custom document properties, ribbon customisation and add-in task panes, custom XML, links to external workbooks (never followed or refreshed), data connections, sheet query tables, printer settings (#324), form controls, ActiveX controls, OLE objects and sheet backgrounds (with their VML shapes), and chart sheets (#727: the sheet, drawing, chart, style and colour parts are written back unchanged in their place, and left out when a sheet they plot was deleted or renamed or a worksheet took their name; they can't be edited or created); dropped when their sheet is deleted or their parts point at content GridCraft rewrites. Self-contained `extLst` entries (`extlist.rs`, an allowlist of single attribute-only elements, rebuilt in source order): the workbook's calcFeatures, x15 and x14 `workbookPr`, `xlwcv:version` and Excel for Mac `mx:ArchID`, and the sheet's Excel for Mac `mx:PLV`. **Not preserved:** slicers and slicer caches, timelines, data model, query tables attached to tables, other sheet and workbook `extLst` entries we don't model (each dropped URI is named in an open warning), chart details; Strict Open XML files keep nothing. Never checked in Excel across a corpus: repair prompts unknown. 100 MB files fail (#175) A picture used on several sheets is written once (#985). | `roundtrip.rs`, `fixtures.rs`, `malformed.rs`, `pivot_tests.rs` | -| `.xlsx` Excel Workbook (transitional) | R/W, native | yes | yes | Cells, shared/array/dynamic formulas, shared strings (with their Japanese phonetic runs — ふりがな — kept through open + save: `` offsets and readings and `` are written back next to the same string; the table holds each text once, so duplicate `` items whose text is the same but whose readings differ keep only the first reading, with a warning on open), styles, themes, merges, CF, validation, tables, notes (with their shown/hidden state) and threaded comments with replies, resolved state and timestamps (`threadedComments` and `persons` parts, #300), hyperlinks, names, freeze panes, outline, print settings, pictures, shapes, charts (simplified, see [chart-parity.md](chart-parity.md)), sparklines, PivotTables (caches and tables), protection, calc settings, show objects (`workbookPr showObjects`). **Not preserved:** unmodelled parts and extensions (form controls, slicer caches, timelines, external links, OLE objects, custom XML, data model, query tables, chart details). Never checked in Excel across a corpus: repair prompts unknown. 100 MB files fail (#175) A picture used on several sheets is written once (#985). | `roundtrip.rs`, `fixtures.rs`, `malformed.rs`, `pivot_tests.rs` | -| `.xlsx` Excel Workbook (transitional) | R/W, native | yes | yes | Cells, shared/array/dynamic formulas, shared strings (with their Japanese phonetic runs — ふりがな — kept through open + save: `` offsets and readings and `` are written back next to the same string; the table holds each text once, so duplicate `` items whose text is the same but whose readings differ keep only the first reading, with a warning on open), styles, themes, merges, CF, validation, tables, comments and notes, hyperlinks, names, freeze panes, outline, print settings, pictures, shapes, charts (simplified, see [chart-parity.md](chart-parity.md)), sparklines, PivotTables (caches and tables), protection, Allow Edit Ranges (`protectedRanges` with their password hashes, #307), calc settings, show objects (`workbookPr showObjects`). **Not preserved:** unmodelled parts and extensions (form controls, slicer caches, timelines, external links, OLE objects, custom XML, data model, query tables, chart details). Never checked in Excel across a corpus: repair prompts unknown. 100 MB files fail (#175) A picture used on several sheets is written once (#985). | `roundtrip.rs`, `fixtures.rs`, `malformed.rs`, `pivot_tests.rs` | -| `.xlsx` Excel Workbook (transitional) | R/W, native | yes | yes | Cells, shared/array/dynamic formulas, styles, themes (the major/minor `latin`, East Asian `ea` and complex-script `cs` typefaces and the per-script `` lists are kept through a save), merges, CF, validation, tables, comments and notes, hyperlinks, names, freeze panes, outline, print settings, pictures, shapes, charts (simplified, see [chart-parity.md](chart-parity.md)), sparklines, PivotTables (caches and tables), protection, calc settings. **Kept unchanged on save (pass-through, `passthrough.rs`):** custom document properties, ribbon customisation and add-in task panes, custom XML, links to external workbooks (never followed or refreshed), data connections, sheet query tables, printer settings (#324), form controls, ActiveX controls, OLE objects and sheet backgrounds (with their VML shapes), pictures in headers and footers (`&G`, #1257: their VML drawing and images are written back unchanged; they are not shown, and can't be inserted), and chart sheets (#727: the sheet, drawing, chart, style and colour parts are written back unchanged in their place, and left out when a sheet they plot was deleted or renamed or a worksheet took their name; they can't be edited or created); dropped when their sheet is deleted or their parts point at content GridCraft rewrites. Self-contained `extLst` entries (`extlist.rs`, an allowlist of single attribute-only elements, rebuilt in source order): the workbook's calcFeatures, x15 and x14 `workbookPr`, `xlwcv:version` and Excel for Mac `mx:ArchID`, and the sheet's Excel for Mac `mx:PLV`. **Not preserved:** slicers and slicer caches, timelines, data model, query tables attached to tables, other sheet and workbook `extLst` entries we don't model (each dropped URI is named in an open warning), chart details; Strict Open XML files keep nothing. Never checked in Excel across a corpus: repair prompts unknown. 100 MB files fail (#175) | `roundtrip.rs`, `fixtures.rs`, `malformed.rs`, `pivot_tests.rs` | -| `.xlsx` Excel Workbook (transitional) | R/W, native | yes | yes | Cells, shared/array/dynamic formulas, styles, themes (the major/minor `latin`, East Asian `ea` and complex-script `cs` typefaces and the per-script `` lists are kept through a save), merges, CF, validation, tables, notes (with their shown/hidden state) and threaded comments with replies, resolved state and timestamps (`threadedComments` and `persons` parts, #300), hyperlinks, names, freeze panes, outline, print settings, pictures, shapes, charts (simplified, see [chart-parity.md](chart-parity.md)), sparklines, PivotTables (caches and tables), protection, calc settings. **Not preserved:** unmodelled parts and extensions (form controls, slicer caches, timelines, external links, OLE objects, custom XML, data model, query tables, chart details). Never checked in Excel across a corpus: repair prompts unknown. 100 MB files fail (#175) | `roundtrip.rs`, `fixtures.rs`, `malformed.rs`, `pivot_tests.rs` | -| `.xlsx` Excel Workbook (transitional) | R/W, native | yes | yes | Cells, shared/array/dynamic formulas, styles, themes (the major/minor `latin`, East Asian `ea` and complex-script `cs` typefaces and the per-script `` lists are kept through a save), merges, CF, validation, tables, comments and notes, hyperlinks, names, freeze panes, outline, print settings, pictures, shapes, charts (simplified, see [chart-parity.md](chart-parity.md)), sparklines, PivotTables (caches and tables), protection, Allow Edit Ranges (`protectedRanges` with their password hashes, #307), calc settings. **Not preserved:** unmodelled parts and extensions (form controls, slicer caches, timelines, external links, OLE objects, custom XML, data model, query tables, chart details). Never checked in Excel across a corpus: repair prompts unknown. 100 MB files fail (#175) | `roundtrip.rs`, `fixtures.rs`, `malformed.rs`, `pivot_tests.rs` | -| `.xlsx` Excel Workbook (transitional) | R/W, native | yes | yes | Cells, shared/array/dynamic formulas, styles, themes, merges, CF, validation, tables, comments and notes, hyperlinks, names, freeze panes, outline, print settings, pictures, shapes, charts (simplified, see [chart-parity.md](chart-parity.md)), sparklines, PivotTables (caches and tables), protection, calc settings. **Kept unchanged on save (pass-through, `passthrough.rs`):** custom document properties, ribbon customisation and add-in task panes, custom XML, links to external workbooks (never followed or refreshed), data connections, sheet query tables, printer settings (#324), form controls, ActiveX controls, OLE objects and sheet backgrounds (with their VML shapes), and chart sheets (#727: the sheet, drawing, chart, style and colour parts are written back unchanged in their place, and left out when a sheet they plot was deleted or renamed or a worksheet took their name; they can't be edited or created); dropped when their sheet is deleted or their parts point at content GridCraft rewrites. Self-contained `extLst` entries (`extlist.rs`, an allowlist of single attribute-only elements, rebuilt in source order): the workbook's calcFeatures, x15 and x14 `workbookPr`, `xlwcv:version` and Excel for Mac `mx:ArchID`, and the sheet's Excel for Mac `mx:PLV`. **Not preserved:** slicers and slicer caches, timelines, data model, query tables attached to tables, other sheet and workbook `extLst` entries we don't model (each dropped URI is named in an open warning), chart details; Strict Open XML files keep nothing. Never checked in Excel across a corpus: repair prompts unknown. 100 MB files fail (#175) | `roundtrip.rs`, `fixtures.rs`, `malformed.rs`, `pivot_tests.rs` | -| `.xlsx` Excel Workbook (transitional) | R/W, native | yes | yes | Cells, shared/array/dynamic formulas, styles, themes, merges, CF, validation, tables, notes (with their shown/hidden state and their box's place and size, #1608) and threaded comments with replies, resolved state and timestamps (`threadedComments` and `persons` parts, #300), hyperlinks, names, freeze panes, outline, print settings, pictures, shapes, charts (simplified, see [chart-parity.md](chart-parity.md)), sparklines, PivotTables (caches and tables), protection, calc settings. **Not preserved:** unmodelled parts and extensions (form controls, slicer caches, timelines, external links, OLE objects, custom XML, data model, query tables, chart details). Never checked in Excel across a corpus: repair prompts unknown. 100 MB files fail (#175) | `roundtrip.rs`, `fixtures.rs`, `malformed.rs`, `pivot_tests.rs` | -| `.xlsx` Excel Workbook (transitional) | R/W, native | yes | yes | Cells, shared/array/dynamic formulas, styles, themes, merges, CF, validation, tables, comments and notes, hyperlinks, names, freeze panes, outline, print settings, pictures, shapes, charts (simplified, see [chart-parity.md](chart-parity.md)), sparklines, PivotTables (caches and tables), protection, Allow Edit Ranges (`protectedRanges` with their password hashes, #307), calc settings. **Not preserved:** unmodelled parts and extensions (form controls, slicer caches, timelines, external links, OLE objects, custom XML, data model, query tables, chart details). Never checked in Excel across a corpus: repair prompts unknown. 100 MB files fail (#175) | `roundtrip.rs`, `fixtures.rs`, `malformed.rs`, `pivot_tests.rs` | +| `.xlsx` Excel Workbook (transitional) | R/W, native | yes | yes | Cells, shared/array/dynamic formulas, shared strings (with their Japanese phonetic runs — ふりがな — kept through open + save: `` offsets and readings and `` are written back next to the same string; the table holds each text once, so duplicate `` items whose text is the same but whose readings differ keep only the first reading, with a warning on open), styles, themes (the major/minor `latin`, East Asian `ea` and complex-script `cs` typefaces and the per-script `` lists are kept through a save), merges, CF, validation, tables, notes (with their shown/hidden state and their box's place and size, #1608) and threaded comments with replies, resolved state and timestamps (`threadedComments` and `persons` parts, #300), hyperlinks, names, freeze panes, outline, print settings, pictures, shapes, charts (simplified, see [chart-parity.md](chart-parity.md)), sparklines, PivotTables (caches and tables), protection, Allow Edit Ranges (`protectedRanges` with their password hashes, #307), calc settings, show objects (`workbookPr showObjects`). **Kept unchanged on save (pass-through, `passthrough.rs`):** custom document properties, ribbon customisation and add-in task panes, custom XML, links to external workbooks (never followed or refreshed), data connections, sheet query tables, printer settings (#324), form controls, ActiveX controls, OLE objects and sheet backgrounds (with their VML shapes), pictures in headers and footers (`&G`, #1257: their VML drawing and images are written back unchanged; they are not shown, and can't be inserted), and chart sheets (#727: the sheet, drawing, chart, style and colour parts are written back unchanged in their place, and left out when a sheet they plot was deleted or renamed or a worksheet took their name; they can't be edited or created); dropped when their sheet is deleted or their parts point at content GridCraft rewrites. Self-contained `extLst` entries (`extlist.rs`, an allowlist of single attribute-only elements, rebuilt in source order): the workbook's calcFeatures, x15 and x14 `workbookPr`, `xlwcv:version` and Excel for Mac `mx:ArchID`, and the sheet's Excel for Mac `mx:PLV`. **Not preserved:** slicers and slicer caches, timelines, data model, query tables attached to tables, other sheet and workbook `extLst` entries we don't model (the first five dropped URIs are named in an open warning, with a count for the rest), chart details; Strict Open XML files keep nothing. Never checked in Excel across a corpus: repair prompts unknown. 100 MB files fail (#175). A picture used on several sheets is written once (#985). | `roundtrip.rs`, `fixtures.rs`, `malformed.rs`, `pivot_tests.rs` | | `.xlsx` Strict Open XML | R/W | yes | no (writes transitional) | Excel also saves transitional by default | fixtures | | `.xlsm` Macro-Enabled Workbook | R/W | yes | yes, macros kept, not run | The VBA project is kept byte-for-byte and written back only into `.xlsm`/`.xltm` (#6); macros never run. Saved with the macro-enabled workbook content type | `roundtrip.rs` (`vba_project_roundtrip`, `package_kind_sets_workbook_content_type`), engine `io.rs` (`macros_are_saved_only_into_xlsm`) | | `.xltx` / `.xltm` templates | R/W | yes | partial | Saved with the template (and macro-enabled template) content type, chosen by extension; `.xltm` keeps a VBA project, `.xltx` drops it; "new from template" behaviour missing | `roundtrip.rs` (`package_kind_sets_workbook_content_type`), engine `io.rs` | From 9b7c5ca1f604d7162c44700670686d4096a38572 Mon Sep 17 00:00:00 2001 From: Harrison Booth <73434116+Harrison-Booth@users.noreply.github.com> Date: Sat, 24 Oct 2026 15:41:13 -0500 Subject: [PATCH 15/55] Keyboard: Add mode drops only its own provisional area; selection commands go through app.run --- crates/ui-egui/src/grid.rs | 26 +++++++++++++++----------- 1 file changed, 15 insertions(+), 11 deletions(-) diff --git a/crates/ui-egui/src/grid.rs b/crates/ui-egui/src/grid.rs index fc4fb8176d..6aff68e5fa 100644 --- a/crates/ui-egui/src/grid.rs +++ b/crates/ui-egui/src/grid.rs @@ -184,7 +184,7 @@ pub struct GridState { pub selection_mode: SelectionMode, /// Add mode: the last area is the cell an arrow key moved to, not yet extended, so the next /// arrow moves it again instead of keeping it. - pub add_pending: bool, + pub add_pending: Option, /// Add mode header drag: the areas kept from before the drag, which the dragged range joins. pub header_drag_base: Vec, } @@ -239,7 +239,7 @@ impl GridState { pub fn set_selection_mode(&mut self, mode: SelectionMode) { self.selection_mode = mode; - self.add_pending = false; + self.add_pending = None; } } @@ -2494,10 +2494,11 @@ fn interact(app: &mut SheetApp, ui: &mut egui::Ui, resp: &egui::Response, geo: & if sel_mods.shift { // Add mode keeps the areas already selected and drops only the provisional area it made itself. let mut ranges = add_mode_base(app); - if app.grid.add_pending { + if let Some(p) = app.grid.add_pending.take() + && ranges.last() == Some(&p.a1()) + { ranges.pop(); } - app.grid.add_pending = false; ranges.push(RangeRef::new(sel.anchor, c).a1()); let _ = app.session.run("selection.set", json!({"range": ranges.join(","), "active": sel.active.a1()})); if let Some(d) = app.session.active_mut() { @@ -3058,24 +3059,27 @@ fn add_mode_move(app: &mut SheetApp, dr: i64, dc: i64, shift: bool, jump: bool) app.grid.ensure_visible = true; app.grid.reveal_moving_end = shift; if shift { - let _ = app.session.run("selection.move", json!({"dr": dr, "dc": dc, "extend": true, "jump": jump})); - app.grid.add_pending = false; + let _ = app.run("selection.move", json!({"dr": dr, "dc": dc, "extend": true, "jump": jump})); + app.grid.add_pending = None; return; } let Some(mut keep) = app.session.active().map(|d| d.selection.ranges.clone()) else { return }; - if app.grid.add_pending { + // Only the provisional area this mode made is dropped, and only while it is still the last area. + if let Some(p) = app.grid.add_pending.take() + && keep.last() == Some(&p) + { keep.pop(); } // The engine works out where the cell lands (hidden rows, merged cells, Ctrl+arrow jumps). - let _ = app.session.run("selection.move", json!({"dr": dr, "dc": dc, "extend": false, "jump": jump})); + let _ = app.run("selection.move", json!({"dr": dr, "dc": dc, "extend": false, "jump": jump})); let Some((area, active)) = app.session.active().map(|d| (d.selection.current(), d.selection.active)) else { return }; // Landing on an area already kept leaves it kept: the next arrow doesn't drop it. let kept = keep.contains(&area); keep.retain(|r| *r != area); keep.push(area); let range = keep.iter().map(|r| r.a1()).collect::>().join(","); - let _ = app.session.run("selection.set", json!({"range": range, "active": active.a1()})); - app.grid.add_pending = !kept; + let _ = app.run("selection.set", json!({"range": range, "active": active.a1()})); + app.grid.add_pending = (!kept).then_some(area); } /// The active sheet's areas in Add mode, as `selection.set` takes them; empty in other modes. @@ -3088,7 +3092,7 @@ fn add_mode_base(app: &SheetApp) -> Vec { fn select_ranges(app: &mut SheetApp, r: RangeRef, add: bool, active: CellRef) { // A clicked area is kept: the next Add mode arrow starts a new one. - app.grid.add_pending = false; + app.grid.add_pending = None; let current: Vec = if add { app.session.active().map(|d| d.selection.ranges.clone()).unwrap_or_default() } else { vec![] }; let clicked = r.a1(); // A click on a cell inside a larger kept area removes that area, as a click on a single-cell area does. From d2506c03d98f3fa04d4f6339ab75bc8888a1eb99 Mon Sep 17 00:00:00 2001 From: Harrison Booth <73434116+Harrison-Booth@users.noreply.github.com> Date: Sat, 24 Oct 2026 16:56:45 -0500 Subject: [PATCH 16/55] Resize Table: a normalized header keeps the settings of its own column With a header row, a resized column found its settings by name. A blank header that took a generated name could pick up the settings of another column with that name. A header that was normalized now keeps the column at its address. --- crates/engine/src/cmd/extra.rs | 9 ++++++++- 1 file changed, 8 insertions(+), 1 deletion(-) diff --git a/crates/engine/src/cmd/extra.rs b/crates/engine/src/cmd/extra.rs index 77dd21db67..ccdf087704 100644 --- a/crates/engine/src/cmd/extra.rs +++ b/crates/engine/src/cmd/extra.rs @@ -903,7 +903,14 @@ fn table_resize(s: &mut Session, p: &Json) -> Result { // A column that stays keeps its settings (totals, calculated formula): with a header // row it's found by name, without one by position. let existing = if header_row { - old_cols.iter().find(|x| x.name.eq_ignore_ascii_case(name)) + // A header that was normalized into a generated name keeps the settings of the + // column at its address, not of whichever column already has that name. + let raw = texts.get((c - r.start.col) as usize).and_then(|x| x.as_deref()); + if c >= old.start.col && c <= old.end.col && raw != Some(name.as_str()) { + old_cols.get((c - old.start.col) as usize) + } else { + old_cols.iter().find(|x| x.name.eq_ignore_ascii_case(name)) + } } else if c >= old.start.col && c <= old.end.col { old_cols.get((c - old.start.col) as usize) } else { From 79324b6c171f114bd7015d096124ec9f08db7da5 Mon Sep 17 00:00:00 2001 From: Harrison Booth <73434116+Harrison-Booth@users.noreply.github.com> Date: Sat, 24 Oct 2026 17:03:49 -0500 Subject: [PATCH 17/55] Resize Table test: the PivotTable fixture anchors outside the resize range The filter report starts above its anchor and overlaps the resize range, so the test checks the report's extent rather than only the anchor cell. --- crates/engine/tests/it/table_resize_overlap.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/crates/engine/tests/it/table_resize_overlap.rs b/crates/engine/tests/it/table_resize_overlap.rs index 58d52444c2..a80282aa46 100644 --- a/crates/engine/tests/it/table_resize_overlap.rs +++ b/crates/engine/tests/it/table_resize_overlap.rs @@ -116,7 +116,7 @@ fn resize_onto_merged_cells_pivot_or_array_is_rejected() { let mut s = table(); s.execute("range.setValues", json!({"range": "H1", "values": [["k", "v"], ["x", "1"], ["y", "2"]]})).unwrap(); - s.execute("insert.pivotTable", json!({"source": "Sheet1!$H$1:$I$3", "destination": "Sheet1!D1", "rows": ["k"], "values": ["v"]})).unwrap(); + s.execute("insert.pivotTable", json!({"source": "Sheet1!$H$1:$I$3", "destination": "Sheet1!D3", "filters": ["k"], "values": ["v"]})).unwrap(); assert!(!sheet(&s).pivots.is_empty()); let e = s.execute("table.resize", json!({"table": "T", "range": "A1:E2"})).unwrap_err().to_string(); assert!(e.contains("PivotTable"), "{e}"); From 707ce9e14cb85f34ead23b3d43ad556be58c56bc Mon Sep 17 00:00:00 2001 From: Harrison Booth <73434116+Harrison-Booth@users.noreply.github.com> Date: Sat, 24 Oct 2026 17:26:54 -0500 Subject: [PATCH 18/55] Resize Table: name formula headers by value and clear pictures under normalized headers A formula header with formulas shown was named by its source text, so the header became constant text like "=1+1". Use the value text instead. Header normalization wrote through cells.set, which left a picture at that address in place. Use Sheet::set_cell so the picture is removed with it. --- crates/engine/src/cmd/extra.rs | 4 +-- .../engine/tests/it/table_resize_overlap.rs | 26 +++++++++++++++++++ 2 files changed, 28 insertions(+), 2 deletions(-) diff --git a/crates/engine/src/cmd/extra.rs b/crates/engine/src/cmd/extra.rs index ccdf087704..6a4551210e 100644 --- a/crates/engine/src/cmd/extra.rs +++ b/crates/engine/src/cmd/extra.rs @@ -889,7 +889,7 @@ fn table_resize(s: &mut Session, p: &Json) -> Result { let v = sheet.value(at); let text = match v.as_text() { Some(x) => x.to_string(), - None => crate::display::cell_text(wb, sheet, at), + None => crate::display::value_text(wb, sheet, at), }; (!text.trim().is_empty()).then_some(text) }) @@ -930,7 +930,7 @@ fn table_resize(s: &mut Session, p: &Json) -> Result { let constant_text = sheet.value(at).as_text() == Some(col.name.as_str()) && sheet.cell(at).is_some_and(|x| x.formula.is_none()); if !constant_text { let style = sheet.style_id(at); - sheet.cells.set(at, Cell { value: Value::text(col.name.as_str()), style, ..Default::default() }); + sheet.set_cell(at, Cell { value: Value::text(col.name.as_str()), style, ..Default::default() }); } } } diff --git a/crates/engine/tests/it/table_resize_overlap.rs b/crates/engine/tests/it/table_resize_overlap.rs index a80282aa46..7bdae2ebbc 100644 --- a/crates/engine/tests/it/table_resize_overlap.rs +++ b/crates/engine/tests/it/table_resize_overlap.rs @@ -193,3 +193,29 @@ fn resizing_a_table_without_a_header_row_keeps_its_names_and_data() { assert_eq!(names(&s, 0), ["a", "b", "Column1"]); assert_eq!(sheet(&s).value(r.start).display(), first); } + +#[test] +fn resized_formula_header_is_named_by_its_value_when_formulas_show() { + let mut s = with_headers("A1:B3", &["x", "y"]); + s.execute("cell.set", json!({"cell": "C1", "input": "=1+1"})).unwrap(); + { + let wb = std::sync::Arc::make_mut(&mut s.doc_mut().unwrap().wb); + std::sync::Arc::make_mut(&mut wb.sheets[0]).show_formulas = true; + } + s.execute("table.resize", json!({"table": "T", "range": "A1:C3"})).unwrap(); + assert_eq!(names(&s, 0), ["x", "y", "2"]); + assert_eq!(headers(&s, 0), names(&s, 0)); +} + +#[test] +fn resized_picture_header_is_replaced_and_its_picture_removed() { + let mut s = with_headers("A1:B3", &["x", "y"]); + { + let wb = std::sync::Arc::make_mut(&mut s.doc_mut().unwrap().wb); + let picture = gridcraft_engine::model::CellPicture { data: vec![1, 2, 3], mime: "image/png".into(), alt: String::new() }; + std::sync::Arc::make_mut(&mut wb.sheets[0]).set_picture(gridcraft_core::CellRef::new(0, 2), std::sync::Arc::new(picture)); + } + s.execute("table.resize", json!({"table": "T", "range": "A1:C3"})).unwrap(); + assert!(!sheet(&s).cell_pictures.contains_key(&gridcraft_core::CellRef::new(0, 2))); + assert_eq!(headers(&s, 0), names(&s, 0)); +} From c693db2b9fa3539bab7ec2f84e7269ba98b0802e Mon Sep 17 00:00:00 2001 From: alosslessdev Date: Fri, 23 Oct 2026 01:09:08 -0500 Subject: [PATCH 19/55] Conditional formatting: colour-scale editor and New Rule list (part of #1165) New Formatting Rule offers Excel's six rule types. The colour-scale branch edits per-stop type, value and colour, and Manage Rules edits a rule in place. Formula rules refuse an empty or unparseable formula: the dialog keeps OK disabled until a formula is typed, and the command rejects both an empty rule and a formula that does not parse (#1999), so neither a rule that never applies nor a workbook Excel cannot open is written. Percent and percentile stops are clamped to 0-100, and an edit past the last rule names home.manageRules and leaves no undo step. --- ROADMAP.md | 1 + crates/engine/src/cmd/insert.rs | 423 ++++++++++++++++++----- crates/ui-egui/src/dialogs.rs | 319 ++++++++++++++++- crates/ui-egui/src/i18n/cs.rs | 25 ++ crates/ui-egui/src/i18n/de.rs | 24 ++ crates/ui-egui/src/i18n/es.rs | 24 ++ crates/ui-egui/src/i18n/fr.rs | 24 ++ crates/ui-egui/src/i18n/ja.rs | 21 ++ crates/ui-egui/src/i18n/ko.rs | 24 ++ crates/ui-egui/src/i18n/pt.rs | 22 ++ crates/ui-egui/src/i18n/ru.rs | 24 ++ crates/ui-egui/src/i18n/sr.rs | 24 ++ crates/ui-egui/src/i18n/zh.rs | 24 ++ crates/ui-egui/src/ribbon.rs | 34 +- crates/ui-egui/tests/color_scale_rule.rs | 249 +++++++++++++ docs/gaps.md | 1 + docs/target-app-parity.md | 3 +- docs/ui-parity.md | 2 + 18 files changed, 1179 insertions(+), 89 deletions(-) create mode 100644 crates/ui-egui/tests/color_scale_rule.rs diff --git a/ROADMAP.md b/ROADMAP.md index 48b3cf9bc7..8f7cf001b0 100644 --- a/ROADMAP.md +++ b/ROADMAP.md @@ -245,6 +245,7 @@ Ranked; estimates in Opus 5.5 agent-hours. Detail and the full beta-gate list in | 2026-10-20 | minor | Dutch (nl) listed under other shipped languages; progress log row | | 2026-10-19 | minor | Progress log: long flat operator chains (#916) | | 2026-10-19 | trivial | Progress log: desktop theme portal read timeout | +| 2026-10-17 | minor | Conditional formatting: 2-/3-colour scale editor with per-stop type/value/colour, and in-place rule editing (part of #1165) | | 2026-10-16 | minor | Progress log: undo steps share picture and macro bytes | | 2026-10-16 | minor | Progress log: floating pictures' textures bounded and kept per workbook | | 2026-10-16 | trivial | Progress log: web preferences kept between visits (#1562) | diff --git a/crates/engine/src/cmd/insert.rs b/crates/engine/src/cmd/insert.rs index 9719bf451b..1634cf32b0 100644 --- a/crates/engine/src/cmd/insert.rs +++ b/crates/engine/src/cmd/insert.rs @@ -190,7 +190,7 @@ pub fn specs() -> Vec { "Conditional Formatting", ["Home", "Styles"], None, - "{range?, rule: {type: cellIs|expression|containsText|beginsWith|endsWith|blanks|noBlanks|errors|noErrors|duplicate|unique|top10|aboveAverage|timePeriod|colorScale|dataBar|iconSet, operator?, value?, value2?, formula?, text?, rank?, bottom?, percent?, below?, period?, colors?: [..], color?, set?, style?: {font?: {bold?, italic?, color?}, fill?: \"#FFC7CE\" | {pattern?, fg?, bg?}, borders?, num_fmt?} (colours \"#RRGGBB\") | preset?: lightRedFill|redText|yellowFill|greenFill|redBorder|lightRedFillDarkRedText…}; a text `value` is matched as text, or kept when already a quoted literal}", + "{range?, rule: {type: cellIs|expression|containsText|beginsWith|endsWith|blanks|noBlanks|errors|noErrors|duplicate|unique|top10|aboveAverage|timePeriod|colorScale|dataBar|iconSet, operator?, value?, value2?, formula?, text?, rank?, bottom?, percent?, below?, period?, colors?: [..], stops?: [{type: min|max|num|percent|percentile|formula, value?, color}], color?, set?, style?: {font?: {bold?, italic?, color?}, fill?: \"#FFC7CE\" | {pattern?, fg?, bg?}, borders?, num_fmt?} (colours \"#RRGGBB\") | preset?: lightRedFill|redText|yellowFill|greenFill|redBorder|lightRedFillDarkRedText…}; a text `value` is matched as text, or kept when already a quoted literal}", has_doc, add_cf ), @@ -200,7 +200,7 @@ pub fn specs() -> Vec { "Manage Rules…", ["Home", "Styles", "Conditional Formatting"], None, - "{delete?: index, moveUp?: index, moveDown?: index}", + "{delete?: index, moveUp?: index, moveDown?: index, edit?: index, rule?: {...} (with edit)}", has_doc, manage_cf ), @@ -1493,36 +1493,40 @@ fn cf_style_json(st: &Json) -> Result { fn check_cf_formula(cmd: &str, what: &str, formula: &str) -> Result<()> { // Strip exactly one leading '=', the way the XLSX writer does: a value like '===A1' // only parses after several strips and would still be saved unparseable. (#1999 review) - if gridcraft_formula::parse(formula.strip_prefix('=').unwrap_or(formula)).is_err() { + let parsed = formula.strip_prefix('=').unwrap_or(formula); + // A rule with no formula never applies; the dialog also keeps OK disabled for it. + if parsed.trim().is_empty() { + return Err(bad(cmd, format!("the {what} formula is empty"))); + } + if gridcraft_formula::parse(parsed).is_err() { return Err(bad(cmd, format!("invalid {what} formula `{formula}` — it does not parse; Excel would reject the saved file"))); } Ok(()) } -fn check_cf_value(what: &str, v: &gridcraft_model::features::CfValueKind) -> Result<()> { +fn check_cf_value(cmd: &str, what: &str, v: &gridcraft_model::features::CfValueKind) -> Result<()> { if let gridcraft_model::features::CfValueKind::Formula(f) = v { - check_cf_formula("home.conditionalFormat", what, f)?; + check_cf_formula(cmd, what, f)?; } Ok(()) } -fn check_cf_rule(rule: &CfRule) -> Result<()> { - const CMD: &str = "home.conditionalFormat"; +fn check_cf_rule(cmd: &str, rule: &CfRule) -> Result<()> { match rule { CfRule::CellIs { a, b, .. } => { - check_cf_formula(CMD, "comparison value", a)?; + check_cf_formula(cmd, "comparison value", a)?; if let Some(b) = b { - check_cf_formula(CMD, "second comparison value", b)?; + check_cf_formula(cmd, "second comparison value", b)?; } } - CfRule::Expression { formula, .. } => check_cf_formula(CMD, "rule", formula)?, + CfRule::Expression { formula, .. } => check_cf_formula(cmd, "rule", formula)?, CfRule::DataBar { min, max, .. } => { - check_cf_value("data bar minimum", min)?; - check_cf_value("data bar maximum", max)?; + check_cf_value(cmd, "data bar minimum", min)?; + check_cf_value(cmd, "data bar maximum", max)?; } CfRule::ColorScale { stops } => { for (kind, _) in stops { - check_cf_value("color scale threshold", kind)?; + check_cf_value(cmd, "color scale threshold", kind)?; } } _ => {} @@ -1530,41 +1534,50 @@ fn check_cf_rule(rule: &CfRule) -> Result<()> { Ok(()) } -fn add_cf(s: &mut Session, p: &Json) -> Result { - let ranges = target_ranges(s, p)?; - let sheet = target_sheet(s, p)?; - let Some(rule) = p.get("rule") else { - s.ui_requests.push(crate::UiRequest::Dialog("newFormattingRule".into(), json!({}))); - return ok(); - }; +fn cf_style(rule: &Json, cmd: &str) -> Result