From 921405fa02a60ef883412a0eb630ea19ddf54d57 Mon Sep 17 00:00:00 2001 From: Harrison Booth Date: Wed, 14 Oct 2026 21:18:25 -0500 Subject: [PATCH 01/21] SORT, SORTBY and Data > Sort order numbers exactly, like Excel sort_compare compared numbers at 15 significant digits, so 0.3 and =0.1+0.2 (0.30000000000000004) tied and kept their input order. Excel 365 orders them exactly in SORT, SORTBY, Data > Sort, the AutoFilter sort and table sort: 0.3 first ascending, last descending, in either input order. Numbers now compare with partial_cmp in sort_compare (0 and -0 still tie). = and COUNTIF keep their 15-digit comparison; UNIQUE, RANK, LARGE, SMALL and MODE were already exact, as observed. Co-Authored-By: Claude Opus 5.5 --- ROADMAP.md | 4 ++- crates/calc/src/tests.rs | 59 +++++++++++++++++++++++++++++++++ crates/core/src/value.rs | 17 ++++++++++ crates/engine/src/tests.rs | 21 ++++++++++++ crates/functions/src/dynamic.rs | 15 +++++++++ docs/function-parity.md | 3 +- 6 files changed, 117 insertions(+), 2 deletions(-) diff --git a/ROADMAP.md b/ROADMAP.md index 070552d07e..357f1bf8d5 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:** minor (SORT, SORTBY and Data > Sort order numbers exactly, like Excel) · **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 | SORT, SORTBY and Data > Sort (with the AutoFilter and table sorts) order numbers exactly like Excel, so 0.3 sorts before `=0.1+0.2` whatever the input order; `=` and COUNTIF keep their 15-digit comparison | | 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 | minor | Progress log: sorts order numbers exactly | | 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/calc/src/tests.rs b/crates/calc/src/tests.rs index 196c57de78..ff13374fc8 100644 --- a/crates/calc/src/tests.rs +++ b/crates/calc/src/tests.rs @@ -1266,3 +1266,62 @@ fn offset_extreme_arguments_return_ref() { assert_eq!(crate::evaluate(&wb, 0, c("D1"), formula), Value::Number(expected), "{formula}"); } } + +/// Sorting and ranking compare numbers exactly while `=` and COUNTIF compare them at 15 +/// significant digits. Every expectation was observed in Excel 365 with these fixtures +/// (`=0.1+0.2` is 0.30000000000000004): 0.3 sorts first whatever the input order. +#[test] +fn sorts_and_ranks_compare_numbers_exactly() { + let mut t = T::new(); + for (at, input) in [ + // The noisy value first, then the exact one first. + ("A1", "=0.1+0.2"), + ("B1", "e"), + ("A2", "0.3"), + ("B2", "t"), + ("D1", "0.3"), + ("E1", "t"), + ("D2", "=0.1+0.2"), + ("E2", "e"), + ("G1", "=100+1E-14"), + ("H1", "e"), + ("G2", "100"), + ("H2", "t"), + ] { + t.set(at, input); + } + let e = 0.1 + 0.2; + let n = Value::Number; + let s = |x: &str| Value::from(x); + let cases: Vec<(&str, Value)> = vec![ + ("=A1=A2", Value::Bool(true)), + ("=COUNTIF(A1:A2,0.3)", n(2.0)), + ("=INDEX(SORT(A1:B2),1,2)", s("t")), + ("=INDEX(SORT(D1:E2),1,2)", s("t")), + ("=INDEX(SORT(A1:B2,1,-1),1,2)", s("e")), + ("=INDEX(SORT(D1:E2,1,-1),1,2)", s("e")), + ("=INDEX(SORT(G1:H2),1,2)", s("t")), + ("=INDEX(SORT(G1:H2,1,-1),1,2)", s("e")), + ("=INDEX(SORTBY(B1:B2,A1:A2),1,1)", s("t")), + ("=INDEX(SORTBY(E1:E2,D1:D2),1,1)", s("t")), + ("=INDEX(SORTBY(B1:B2,A1:A2,-1),1,1)", s("e")), + ("=INDEX(SORTBY(E1:E2,D1:D2,-1),1,1)", s("e")), + // Already exact: UNIQUE, RANK, LARGE/SMALL, MODE. + ("=ROWS(UNIQUE(A1:A2))", n(2.0)), + ("=RANK.EQ(0.3,A1:A2)", n(2.0)), + ("=RANK.EQ(0.3,A1:A2,1)", n(1.0)), + ("=RANK.AVG(0.3,A1:A2)", n(2.0)), + ("=RANK.EQ(0.3,A1)", Value::Error(CellError::NA)), + ("=LARGE(A1:A2,1)", n(e)), + ("=SMALL(A1:A2,1)", n(0.3)), + ("=MODE.SNGL(A1:A2,5)", Value::Error(CellError::NA)), + ]; + let mut wrong = Vec::new(); + for (formula, expected) in cases { + let got = crate::evaluate(&t.wb, 0, c("Z1"), formula); + if got != expected { + wrong.push(format!("{formula}: got {got:?}, Excel {expected:?}")); + } + } + assert!(wrong.is_empty(), "{}", wrong.join("\n")); +} diff --git a/crates/core/src/value.rs b/crates/core/src/value.rs index cfef7ac57d..70c05036e2 100644 --- a/crates/core/src/value.rs +++ b/crates/core/src/value.rs @@ -339,12 +339,16 @@ pub fn compare_text(a: &str, b: &str) -> Ordering { } /// Sorting order used by Sort (ascending): numbers, text, booleans, errors, then blanks last. +/// Numbers compare exactly, not at the 15 digits of [`compare`]. Observed in Excel 365: SORT, +/// SORTBY, Data > Sort, the AutoFilter sort and table sort all put 0.3 before `=0.1+0.2` +/// (0.30000000000000004) ascending and after it descending, whatever the input order. pub fn sort_compare(a: &Value, b: &Value) -> Ordering { match (a, b) { (Value::Empty, Value::Empty) => Ordering::Equal, (Value::Empty, _) => Ordering::Greater, (_, Value::Empty) => Ordering::Less, (Value::Error(_), Value::Error(_)) => Ordering::Equal, + (Value::Number(x), Value::Number(y)) => x.partial_cmp(y).unwrap_or(Ordering::Equal), _ => compare(a, b), } } @@ -442,6 +446,19 @@ mod tests { assert_eq!(compare(&num(1.0), &num(2.0)), Ordering::Less); } + #[test] + fn sort_orders_numbers_exactly() { + let num = Value::Number; + let e = 0.1 + 0.2; + assert_eq!(sort_compare(&num(0.3), &num(e)), Ordering::Less); + assert_eq!(sort_compare(&num(e), &num(0.3)), Ordering::Greater); + assert_eq!(sort_compare(&num(100.0), &num(100.0 + 1e-14)), Ordering::Less); + assert_eq!(sort_compare(&num(0.0), &num(-0.0)), Ordering::Equal); + assert_eq!(sort_compare(&num(1.0), &Value::from("a")), Ordering::Less); + // `=` keeps its 15-digit comparison. + assert_eq!(compare(&num(0.3), &num(e)), Ordering::Equal); + } + #[test] fn arrays() { let a = Array::new(2, 2, vec![1.0.into(), 2.0.into(), 3.0.into(), 4.0.into()]).unwrap(); diff --git a/crates/engine/src/tests.rs b/crates/engine/src/tests.rs index ae499a1895..ee21430fd7 100644 --- a/crates/engine/src/tests.rs +++ b/crates/engine/src/tests.rs @@ -1027,6 +1027,27 @@ fn case_sensitive_sort_puts_lowercase_first() { assert_eq!(col, ["a", "A", "aB", "Ab", "b", "B"].map(Value::from)); } +/// Data > Sort orders numbers exactly, like Excel 365: 0.3 sorts before `=0.1+0.2` +/// (0.30000000000000004) ascending and after it descending, whatever the input order. +#[test] +fn sort_orders_numbers_exactly() { + for first_noisy in [true, false] { + let mut s = s(); + let (a1, a2, b1, b2) = if first_noisy { ("=0.1+0.2", "0.3", "e", "t") } else { ("0.3", "=0.1+0.2", "t", "e") }; + for (cell, input) in [("A1", a1), ("A2", a2), ("B1", b1), ("B2", b2)] { + s.execute("cell.set", json!({"cell": cell, "input": input})).unwrap(); + } + let labels = |s: &Session| [v(s, "B1"), v(s, "B2")]; + s.execute("data.sort", json!({"range": "A1:B2", "header": false, "keys": [{"column": "A"}]})).unwrap(); + assert_eq!(labels(&s), ["t", "e"].map(Value::from), "ascending, noisy first: {first_noisy}"); + s.execute("data.sort", json!({"range": "A1:B2", "header": false, "keys": [{"column": "A", "order": "desc"}]})).unwrap(); + assert_eq!(labels(&s), ["e", "t"].map(Value::from), "descending, noisy first: {first_noisy}"); + s.execute("selection.set", json!({"range": "A1:B2"})).unwrap(); + s.execute("data.sortAscending", json!({"range": "A1:B2", "column": "A"})).unwrap(); + assert_eq!(labels(&s), ["t", "e"].map(Value::from), "quick sort, noisy first: {first_noisy}"); + } +} + #[test] fn remove_duplicates_compares_shown_text() { let mut s = s(); diff --git a/crates/functions/src/dynamic.rs b/crates/functions/src/dynamic.rs index 2e29b416ca..d983bc2d33 100644 --- a/crates/functions/src/dynamic.rs +++ b/crates/functions/src/dynamic.rs @@ -1102,6 +1102,21 @@ mod tests { is_err(ev("SORTBY", vec![av(col(&[1.0, 2.0])), av(col(&[1.0, 2.0])), n(0.0)]), CellError::Value); } + /// SORT and SORTBY order numbers exactly, not at 15 digits (observed in Excel 365). + #[test] + fn sort_orders_numbers_exactly() { + for (t, e) in [(0.3, 0.1 + 0.2), (100.0, 100.0 + 1e-14), (3.3, 1.1 * 3.0)] { + for input in [[e, t], [t, e]] { + let asc = vec![vec![nv(t)], vec![nv(e)]]; + let desc = vec![vec![nv(e)], vec![nv(t)]]; + assert_eq!(rows_of(&ev("SORT", vec![av(col(&input))])), asc); + assert_eq!(rows_of(&ev("SORT", vec![av(col(&input)), n(1.0), n(-1.0)])), desc); + assert_eq!(rows_of(&ev("SORTBY", vec![av(col(&input)), av(col(&input))])), asc); + assert_eq!(rows_of(&ev("SORTBY", vec![av(col(&input)), av(col(&input)), n(-1.0)])), desc); + } + } + } + #[test] fn unique() { let v = arr(vec![vec![tv("a")], vec![tv("B")], vec![tv("A")], vec![tv("c")], vec![tv("b")]]); diff --git a/docs/function-parity.md b/docs/function-parity.md index 760ffd6ac3..e35ef547f7 100644 --- a/docs/function-parity.md +++ b/docs/function-parity.md @@ -1,6 +1,6 @@ # Function parity: worksheet functions and formulas -> **Last reviewed:** 2026-10-11 · **Last updated:** 2026-10-12 · **Change:** minor (USDOLLAR added as a compatibility function; MIRR, COUNTIF and INDIRECT edge cases match Excel 365) · **Target:** Microsoft Excel (Microsoft 365), Excel for Mac 16.113.4 +> **Last reviewed:** 2026-10-11 · **Last updated:** 2026-10-14 · **Change:** minor (SORT and SORTBY order numbers exactly, like Excel 365) · **Target:** Microsoft Excel (Microsoft 365), Excel for Mac 16.113.4 Excel's worksheet functions, category by category, against GridCraft's function library. Part of [target-app-parity.md](target-app-parity.md); gaps feed [gaps.md](gaps.md). @@ -108,6 +108,7 @@ workbooks; results checked in as data, not Excel files) and fixing what it finds | Date | Change | Summary | |---|---|---| +| 2026-10-14 | minor | SORT, SORTBY and Data > Sort (including the AutoFilter and table sorts) order numbers exactly, as Excel 365 does: 0.3 sorts before `=0.1+0.2` (0.30000000000000004) ascending and after it descending, in either input order. UNIQUE, RANK / RANK.EQ / RANK.AVG, LARGE, SMALL and MODE were already exact, also as observed; `=` and COUNTIF keep comparing at 15 significant digits | | 2026-10-12 | minor | USDOLLAR added as a Compatibility function (not on Microsoft's list, so the counts don't change); MIRR with no positive flow is -1, COUNTIF's bare `"<="` / `">="` skip empty strings, INDIRECT with `a1` = FALSE gives `#REF!` for A1-style text (#738) | | 2026-10-11 | minor | TEXT / number formats fixed against Excel-cached results: fraction literals and zero fractions, `0` denominators zero padded, `?` pads the thousands separator, booleans use the text section (226 mismatches → 0 in 352 TEXT cells) | | 2026-10-11 | minor | Iterative calculation: circular references iterate up to Maximum Iterations / Maximum Change when enabled | From 4215f07bb34cac01e1c377ee0ef941238ea3b9f7 Mon Sep 17 00:00:00 2001 From: kezmdor <15539254+kezmdor@users.noreply.github.com> Date: Tue, 20 Oct 2026 07:24:25 +0200 Subject: [PATCH 02/21] Formula entry: a leading + or - starts a formula, like Excel (fixes #2023) Typing `+5+4` entered the text `+5+4`: a leading sign started a formula only when a letter or `(` came next. Now any entry that starts with `+` or `-` and isn't a number on its own is a formula, as in Excel, so `+5+4` enters `=+5+4`. `+5`, `-5` and a lone sign are unchanged. The rule lives in `gridcraft_core::parse::starts_formula`, shared by the engine's entry and the Spanish formula-locale path in the UI, where a signed decimal-comma number (`-1,5`) stays a number. Text to Columns keeps a part that isn't a valid formula as text instead of emptying its cell, as paste and Replace already do. Co-Authored-By: Claude Opus 5.5 --- crates/core/src/parse.rs | 20 +++++++++++++ crates/engine/src/cmd/data.rs | 3 +- crates/engine/src/cmd/edit.rs | 7 +---- crates/engine/src/tests.rs | 42 ++++++++++++++++++++++++++ crates/ui-egui/src/formula_locale.rs | 44 +++++++++++++++++++++------- docs/ui-parity.md | 5 ++-- 6 files changed, 102 insertions(+), 19 deletions(-) diff --git a/crates/core/src/parse.rs b/crates/core/src/parse.rs index b465beaf9e..33127c5e0a 100644 --- a/crates/core/src/parse.rs +++ b/crates/core/src/parse.rs @@ -49,6 +49,13 @@ pub fn parse_number_text_in(s: &str, sys: DateSystem) -> Option { parse_numeric(s.trim(), sys).map(|(n, _)| n) } +/// Whether typed cell input is a formula: it starts with `=`, or, as Lotus 1-2-3 users type it, +/// with `+` or `-` and isn't a number on its own. `+5+4` is the formula `=+5+4`, `-5` the number +/// -5, and a lone `+` or `-` is text. A leading space or apostrophe makes the input text. +pub fn starts_formula(input: &str) -> bool { + input.starts_with('=') || (input.len() > 1 && input.starts_with(['+', '-']) && parse_number_text(input).is_none()) +} + fn parse_numeric(t: &str, sys: DateSystem) -> Option<(f64, Option<&'static str>)> { if t.is_empty() { return None; @@ -363,6 +370,19 @@ mod tests { assert_eq!(p("1.2.3.4").value, Value::text("1.2.3.4")); } + #[test] + fn a_leading_sign_starts_a_formula_unless_the_entry_is_a_number() { + // #2023: Excel reads `+5+4` as `=+5+4`, as Lotus 1-2-3 did. + for s in ["=1", "=", "+5+4", "-5+4", "--5", "+-5", "-.5*2", "-3/4", "+A1", "-SUM(1,2)", "+(5+4)", "-abc", "--"] { + assert!(starts_formula(s), "{s}"); + } + // Signed numbers, percentages and currency stay numbers; a lone sign, a leading space or + // apostrophe and other text stay text. + for s in ["+5", "-5", "+5%", "-$5", "-1e3", "+.5", "-1,234.5", "+", "-", " +5+4", "'+5+4", "5+4", "", "a-b"] { + assert!(!starts_formula(s), "{s}"); + } + } + #[test] fn dates_and_times() { assert_eq!(p("10/7/2026").value, Value::Number(46302.0)); diff --git a/crates/engine/src/cmd/data.rs b/crates/engine/src/cmd/data.rs index 24bd043f7d..7b77953e1b 100644 --- a/crates/engine/src/cmd/data.rs +++ b/crates/engine/src/cmd/data.rs @@ -839,7 +839,8 @@ fn text_to_columns(s: &mut Session, p: &Json) -> Result { } } for (c, t) in out { - let cell = super::edit::input_to_cell(&t, sheet, c, &mut cx.wb).unwrap_or(None); + // A part that isn't a valid formula (`--`) stays text, as it does when pasted. + let cell = super::edit::input_to_cell(&t, sheet, c, &mut cx.wb).unwrap_or_else(|_| Some(Cell::value(Value::text(t.as_str())))); let shm = cx.sheet_mut(sheet)?; match cell { Some(x) => shm.set_cell(c, x), diff --git a/crates/engine/src/cmd/edit.rs b/crates/engine/src/cmd/edit.rs index fe7f1fe8bc..86b0eeeec7 100644 --- a/crates/engine/src/cmd/edit.rs +++ b/crates/engine/src/cmd/edit.rs @@ -131,12 +131,7 @@ pub(crate) fn input_to_cell(input: &str, sheet: usize, at: CellRef, wb: &mut gri if fmt_is_text { return Ok(Some(Cell { value: Value::text(input), formula: None, style })); } - let is_formula = input.starts_with('=') - || (input.len() > 1 - && (input.starts_with('+') || input.starts_with('-')) - && gridcraft_core::parse::parse_number_text(input).is_none() - && input.chars().nth(1).is_some_and(|c| c.is_ascii_alphabetic() || c == '(')); - if is_formula { + if gridcraft_core::parse::starts_formula(input) { let body = input.strip_prefix('=').unwrap_or(input); // Excel closes missing parentheses for you. let mut text = body.to_string(); diff --git a/crates/engine/src/tests.rs b/crates/engine/src/tests.rs index 2ac2906548..506bd01915 100644 --- a/crates/engine/src/tests.rs +++ b/crates/engine/src/tests.rs @@ -202,6 +202,48 @@ fn enter_values_and_formulas() { assert_eq!(crate::display::cell_text(&d.wb, sh, CellRef::parse("B1").unwrap()), "12%"); } +#[test] +fn a_leading_plus_or_minus_starts_a_formula() { + // #2023: like Excel (and Lotus 1-2-3 before it), typing `+5+4` enters the formula `=+5+4`. + let mut s = s(); + let input = |s: &Session, a: &str| s.doc().unwrap().wb.active().unwrap().cell(CellRef::parse(a).unwrap()).map(|c| c.input_text()); + for (cell, typed, value) in + [("A1", "+5+4", 9.0), ("A2", "-5+4", -1.0), ("A3", "--5", 5.0), ("A4", "-3/4", -0.75), ("A5", "+A1*2", 18.0), ("A6", "-(A1)", -9.0)] + { + s.execute("cell.set", json!({"cell": cell, "input": typed})).unwrap_or_else(|e| panic!("{typed}: {e}")); + assert_eq!(input(&s, cell), Some(format!("={typed}")), "{typed}"); + assert_eq!(v(&s, cell), Value::Number(value), "{typed}"); + } + // A signed number is a number, a lone sign is text, and an apostrophe keeps the text. + for (typed, value) in [ + ("+5", Value::Number(5.0)), + ("-5", Value::Number(-5.0)), + ("-12%", Value::Number(-0.12)), + ("-$5", Value::Number(-5.0)), + ("-", Value::text("-")), + ("+", Value::text("+")), + ("'+5+4", Value::text("+5+4")), + ] { + s.execute("cell.set", json!({"cell": "B1", "input": typed})).unwrap(); + assert_eq!(v(&s, "B1"), value, "{typed}"); + assert!(!input(&s, "B1").is_some_and(|t| t.starts_with('=')), "{typed}"); + } + // Typed, a sign that doesn't start a valid formula is refused like `=--` and the cell keeps + // its value; pasted or split by Text to Columns it stays text. + s.execute("cell.set", json!({"cell": "C1", "input": "kept"})).unwrap(); + for typed in ["--", "+5+", "+49 170 1234567"] { + let e = s.execute("cell.set", json!({"cell": "C1", "input": typed})).unwrap_err().to_string(); + assert!(e.contains("problem with this formula"), "{typed}: {e}"); + assert_eq!(v(&s, "C1"), Value::text("kept"), "{typed}"); + } + s.execute("edit.paste", json!({"at": "D1", "text": "--\t-5+4\n"})).unwrap(); + assert_eq!(v(&s, "D1"), Value::text("--")); + assert_eq!(v(&s, "E1"), Value::Number(-1.0)); + s.execute("cell.set", json!({"cell": "F1", "input": "a,--,b"})).unwrap(); + s.execute("data.textToColumns", json!({"range": "F1", "delimiters": [","]})).unwrap(); + assert_eq!([v(&s, "F1"), v(&s, "G1"), v(&s, "H1")], [Value::text("a"), Value::text("--"), Value::text("b")]); +} + #[test] fn formulas_with_the_wrong_argument_count_are_refused_on_entry() { // #363: =DATEDIF(start, end) was stored and showed #VALUE!. Like Excel, entry refuses it and diff --git a/crates/ui-egui/src/formula_locale.rs b/crates/ui-egui/src/formula_locale.rs index 6e833b95db..26b7ac007d 100644 --- a/crates/ui-egui/src/formula_locale.rs +++ b/crates/ui-egui/src/formula_locale.rs @@ -20,14 +20,16 @@ pub(crate) fn canonical( if locale == FormulaLocale::En || wb.sheet(sheet).is_some_and(|sh| wb.styles.get(sh.style_id(cell)).num_fmt.as_str() == "@") { return Ok(text.to_string()); } - // Same formula detection as the engine's `input_to_cell` (no trimming: " =1" is text). - let body = text; - if body.starts_with('=') - || ((body.starts_with('+') || body.starts_with('-')) && body.chars().nth(1).is_some_and(|c| c.is_ascii_alphabetic() || c == '(')) - { + // Decimal-comma number entry follows the same preference, without rewriting text or dates. + let normalized = text.trim().replace(locale.decimal_separator(), "."); + let number = normalized.strip_suffix('%').unwrap_or(&normalized); + let is_number = number.parse::().is_ok_and(f64::is_finite); + // Same formula detection as the engine's `input_to_cell` (no trimming: " =1" is text), except + // that a signed number in this locale (`-1,5`) is a number, not a formula. + if !is_number && gridcraft_engine::core::parse::starts_formula(text) { let known = |name: &str| wb.name(name, sheet).is_some() || wb.table(name).is_some(); // Match the engine's existing convenience for missing closing parentheses. - let mut body = body.to_string(); + let mut body = text.to_string(); let mut expr = formula::parse_input(&body, locale, known); for _ in 0..8 { if expr.is_ok() { @@ -38,10 +40,7 @@ pub(crate) fn canonical( } return Ok(format!("={}", formula::print(&expr?))); } - // Decimal-comma number entry follows the same preference, without rewriting text or dates. - let normalized = body.trim().replace(locale.decimal_separator(), "."); - let number = normalized.strip_suffix('%').unwrap_or(&normalized); - if number.parse::().is_ok_and(f64::is_finite) { + if is_number { return Ok(normalized); } Ok(text.to_string()) @@ -138,3 +137,28 @@ pub(crate) fn display_template(text: &str, locale: FormulaLocale, wb: &Workbook, } display(text, locale, wb, sheet) } + +#[cfg(test)] +mod tests { + use gridcraft_engine::core::CellRef; + use gridcraft_engine::formula::FormulaLocale; + use gridcraft_engine::model::Workbook; + + use super::canonical; + + #[test] + fn a_leading_sign_starts_a_formula_in_spanish_too() { + // #2023: `+5+4` is a formula in every formula language; in Spanish `-1,5` stays the + // number -1.5 rather than becoming a formula. + let wb = Workbook::new(); + let at = CellRef::parse("A1").unwrap(); + let entry = |text: &str| canonical(text, FormulaLocale::Es, &wb, 0, at).ok(); + assert_eq!(entry("+5+4").as_deref(), Some("=+5+4")); + assert_eq!(entry("-5+4").as_deref(), Some("=-5+4")); + assert_eq!(entry("-SUMA(1;2)").as_deref(), Some("=-SUM(1,2)")); + assert_eq!(entry("-1,5").as_deref(), Some("-1.5")); + assert_eq!(entry("+2,5%").as_deref(), Some("+2.5%")); + assert_eq!(entry("-").as_deref(), Some("-")); + assert_eq!(entry("--"), None); + } +} diff --git a/docs/ui-parity.md b/docs/ui-parity.md index 34cb502f54..64cf2810e1 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-19 · **Change:** minor (Ctrl+Enter fill gives each cell the automatic number format typing gives it; keytip letters typed with Alt held, #1846) · **Target:** Microsoft Excel (Microsoft 365), Excel for Mac 16.113.4 +> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-10-20 · **Change:** minor (a leading + or - starts a formula, #2023) · **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 @@ -47,7 +47,7 @@ this logic, with one undo step. | Selection outline glides to a new selection (Excel: "Provide feedback with animation") | done (10-11): 0.12 s, decelerating, with the fill and fill handle; View ▸ Animations (`view.animations`) turns it off. The timing is an estimate, not yet measured against Excel; the system's reduced-motion setting isn't followed yet | | Fill handle: drag to fill series, double-click to fill down, right-drag menu | fill done (Ctrl+drag swaps copy and series); right-drag menu missing | | Drag-move and drag-copy cells (border drag, Ctrl/Option, Shift to insert) | done (M3) | -| In-cell editing, Enter/Tab movement, Alt/Option+Enter line breaks | done | +| In-cell editing, Enter/Tab movement, Alt/Option+Enter line breaks | done; a leading `+` or `-` starts a formula, as in Excel (`+5+4` enters `=+5+4`, #2023) | | Point mode (click/drag/arrow references), reference colouring, F4 | done | | AutoComplete in columns, function autocomplete and argument tips | done; cell helpers clip to the worksheet and hide when the editor scrolls out (#200) | | Header resize and double-click AutoFit | done (#42, #88 for header dividers) | @@ -161,6 +161,7 @@ scrollbar bugs 2–4 · pixel/feel pass against observed Excel 7–12. | Date | Change | Summary | |---|---|---| +| 2026-10-20 | minor | Typing a leading `+` or `-` starts a formula whenever the entry isn't a number on its own, as in Excel: `+5+4` enters `=+5+4` and `-5+4` enters `=-5+4` (they stayed text; only a letter or `(` after the sign started one). `+5`, `-5` and `-$5` stay numbers, a lone `+` or `-` stays text, and an entry like `--` that isn't a valid formula is refused like `=--`; pasted or split by Text to Columns it stays text (#2023) | | 2026-10-19 | minor | Ctrl+Enter (`range.fill`) gives each cell what typing the input there gives: a General cell gets the automatic number format (`5%`, `$5`, `3/4/2026`, `=TODAY()`) even when it already held a value, and a cell with its own format, a formatted row or column, or Text keeps it. Cells that held a value used to keep General (`5%` showed 0.05), and empty cells took the active cell's format | | 2026-10-18 | minor | Keytip letters typed with left Alt held continue the sequence (Alt+H, O, A / Alt+H, O, I ran nothing before: Alt+letter cancelled keytips); other Alt combinations, AltGr and macOS Option are unchanged (#1846) | | 2026-10-12 | minor | The File view's recent list tells when each workbook was last changed, read off the UI thread | From 1af4d38e716f926781d36af7b09976a177964c09 Mon Sep 17 00:00:00 2001 From: kezmdor <15539254+kezmdor@users.noreply.github.com> Date: Tue, 20 Oct 2026 07:45:49 +0200 Subject: [PATCH 03/21] Formula entry: keep canonical's body binding, so the diff stays small Co-Authored-By: Claude Opus 5.5 --- crates/ui-egui/src/formula_locale.rs | 7 ++++--- 1 file changed, 4 insertions(+), 3 deletions(-) diff --git a/crates/ui-egui/src/formula_locale.rs b/crates/ui-egui/src/formula_locale.rs index 26b7ac007d..132aef258a 100644 --- a/crates/ui-egui/src/formula_locale.rs +++ b/crates/ui-egui/src/formula_locale.rs @@ -20,16 +20,17 @@ pub(crate) fn canonical( if locale == FormulaLocale::En || wb.sheet(sheet).is_some_and(|sh| wb.styles.get(sh.style_id(cell)).num_fmt.as_str() == "@") { return Ok(text.to_string()); } + let body = text; // Decimal-comma number entry follows the same preference, without rewriting text or dates. - let normalized = text.trim().replace(locale.decimal_separator(), "."); + let normalized = body.trim().replace(locale.decimal_separator(), "."); let number = normalized.strip_suffix('%').unwrap_or(&normalized); let is_number = number.parse::().is_ok_and(f64::is_finite); // Same formula detection as the engine's `input_to_cell` (no trimming: " =1" is text), except // that a signed number in this locale (`-1,5`) is a number, not a formula. - if !is_number && gridcraft_engine::core::parse::starts_formula(text) { + if !is_number && gridcraft_engine::core::parse::starts_formula(body) { let known = |name: &str| wb.name(name, sheet).is_some() || wb.table(name).is_some(); // Match the engine's existing convenience for missing closing parentheses. - let mut body = text.to_string(); + let mut body = body.to_string(); let mut expr = formula::parse_input(&body, locale, known); for _ in 0..8 { if expr.is_ok() { From 0c78ddf79f5300c7e2df33da40ab567c9eaf05c4 Mon Sep 17 00:00:00 2001 From: kezmdor <15539254+kezmdor@users.noreply.github.com> Date: Tue, 20 Oct 2026 08:04:50 +0200 Subject: [PATCH 04/21] Formula entry: a + or - entry that isn't a valid formula stays text Observed in Excel for the web: `--`, `-----`, `+5+` and `+49 170 1234567` stay text, and `- item` is #NAME?. Only `=` entries are refused. Entry now tries a `+`/`-` entry as `=` followed by the entry and, when that doesn't parse, reads it as a number or text as before; the Spanish formula path does the same with its parser. Text to Columns no longer needs its own text fallback, so that change is dropped. Co-Authored-By: Claude Opus 5.5 --- crates/core/src/parse.rs | 7 ++++--- crates/engine/src/cmd/data.rs | 3 +-- crates/engine/src/cmd/edit.rs | 10 +++++++++- crates/engine/src/tests.rs | 19 ++++++++++++------- crates/ui-egui/src/formula_locale.rs | 16 ++++++++++++---- docs/ui-parity.md | 2 +- 6 files changed, 39 insertions(+), 18 deletions(-) diff --git a/crates/core/src/parse.rs b/crates/core/src/parse.rs index 33127c5e0a..949f9909f9 100644 --- a/crates/core/src/parse.rs +++ b/crates/core/src/parse.rs @@ -49,9 +49,10 @@ pub fn parse_number_text_in(s: &str, sys: DateSystem) -> Option { parse_numeric(s.trim(), sys).map(|(n, _)| n) } -/// Whether typed cell input is a formula: it starts with `=`, or, as Lotus 1-2-3 users type it, -/// with `+` or `-` and isn't a number on its own. `+5+4` is the formula `=+5+4`, `-5` the number -/// -5, and a lone `+` or `-` is text. A leading space or apostrophe makes the input text. +/// Whether typed cell input is meant as a formula: it starts with `=`, or, as Lotus 1-2-3 users +/// type it, with `+` or `-` and isn't a number on its own (`+5+4` is `=+5+4`, `-5` the number -5, +/// a lone `+` or `-` text). A leading space or apostrophe makes the input text. Callers parse +/// the formula; a `+` or `-` entry that doesn't parse (`--`) stays text, as in Excel. pub fn starts_formula(input: &str) -> bool { input.starts_with('=') || (input.len() > 1 && input.starts_with(['+', '-']) && parse_number_text(input).is_none()) } diff --git a/crates/engine/src/cmd/data.rs b/crates/engine/src/cmd/data.rs index 7b77953e1b..24bd043f7d 100644 --- a/crates/engine/src/cmd/data.rs +++ b/crates/engine/src/cmd/data.rs @@ -839,8 +839,7 @@ fn text_to_columns(s: &mut Session, p: &Json) -> Result { } } for (c, t) in out { - // A part that isn't a valid formula (`--`) stays text, as it does when pasted. - let cell = super::edit::input_to_cell(&t, sheet, c, &mut cx.wb).unwrap_or_else(|_| Some(Cell::value(Value::text(t.as_str())))); + let cell = super::edit::input_to_cell(&t, sheet, c, &mut cx.wb).unwrap_or(None); let shm = cx.sheet_mut(sheet)?; match cell { Some(x) => shm.set_cell(c, x), diff --git a/crates/engine/src/cmd/edit.rs b/crates/engine/src/cmd/edit.rs index 86b0eeeec7..cfdd1abeba 100644 --- a/crates/engine/src/cmd/edit.rs +++ b/crates/engine/src/cmd/edit.rs @@ -131,7 +131,15 @@ pub(crate) fn input_to_cell(input: &str, sheet: usize, at: CellRef, wb: &mut gri if fmt_is_text { return Ok(Some(Cell { value: Value::text(input), formula: None, style })); } - if gridcraft_core::parse::starts_formula(input) { + // As in Excel, a `+` or `-` entry is a formula when it reads as one (`+5+4` enters `=+5+4`) + // and text when it doesn't (`--`, `+49 170 1234567`); only `=` entries are refused. + if !input.starts_with('=') + && gridcraft_core::parse::starts_formula(input) + && let Ok(cell) = input_to_cell(&format!("={input}"), sheet, at, wb) + { + return Ok(cell); + } + if input.starts_with('=') { let body = input.strip_prefix('=').unwrap_or(input); // Excel closes missing parentheses for you. let mut text = body.to_string(); diff --git a/crates/engine/src/tests.rs b/crates/engine/src/tests.rs index 506bd01915..7af82fbfc4 100644 --- a/crates/engine/src/tests.rs +++ b/crates/engine/src/tests.rs @@ -228,14 +228,19 @@ fn a_leading_plus_or_minus_starts_a_formula() { assert_eq!(v(&s, "B1"), value, "{typed}"); assert!(!input(&s, "B1").is_some_and(|t| t.starts_with('=')), "{typed}"); } - // Typed, a sign that doesn't start a valid formula is refused like `=--` and the cell keeps - // its value; pasted or split by Text to Columns it stays text. - s.execute("cell.set", json!({"cell": "C1", "input": "kept"})).unwrap(); - for typed in ["--", "+5+", "+49 170 1234567"] { - let e = s.execute("cell.set", json!({"cell": "C1", "input": typed})).unwrap_err().to_string(); - assert!(e.contains("problem with this formula"), "{typed}: {e}"); - assert_eq!(v(&s, "C1"), Value::text("kept"), "{typed}"); + // As observed in Excel for the web, an entry that doesn't read as a formula stays text, and + // one that does but names nothing known is #NAME?. Only `=` entries are refused. + for typed in ["--", "-----", "+5+", "+49 170 1234567"] { + s.execute("cell.set", json!({"cell": "C1", "input": typed})).unwrap_or_else(|e| panic!("{typed}: {e}")); + assert_eq!(v(&s, "C1"), Value::text(typed), "{typed}"); + assert_eq!(input(&s, "C1").as_deref(), Some(typed), "{typed}"); } + s.execute("cell.set", json!({"cell": "C2", "input": "- item"})).unwrap(); + assert_eq!(v(&s, "C2"), Value::Error(gridcraft_core::CellError::Name)); + let e = s.execute("cell.set", json!({"cell": "C1", "input": "=--"})).unwrap_err().to_string(); + assert!(e.contains("problem with this formula"), "{e}"); + assert_eq!(v(&s, "C1"), Value::text("+49 170 1234567"), "a refused entry keeps the cell"); + // Pasted or split by Text to Columns, the same rule applies. s.execute("edit.paste", json!({"at": "D1", "text": "--\t-5+4\n"})).unwrap(); assert_eq!(v(&s, "D1"), Value::text("--")); assert_eq!(v(&s, "E1"), Value::Number(-1.0)); diff --git a/crates/ui-egui/src/formula_locale.rs b/crates/ui-egui/src/formula_locale.rs index 132aef258a..dcc4d6db50 100644 --- a/crates/ui-egui/src/formula_locale.rs +++ b/crates/ui-egui/src/formula_locale.rs @@ -25,9 +25,14 @@ pub(crate) fn canonical( let normalized = body.trim().replace(locale.decimal_separator(), "."); let number = normalized.strip_suffix('%').unwrap_or(&normalized); let is_number = number.parse::().is_ok_and(f64::is_finite); - // Same formula detection as the engine's `input_to_cell` (no trimming: " =1" is text), except - // that a signed number in this locale (`-1,5`) is a number, not a formula. - if !is_number && gridcraft_engine::core::parse::starts_formula(body) { + // Same formula detection as the engine's `input_to_cell` (no trimming: " =1" is text): a `+` + // or `-` entry is a formula when it reads as one and text when it doesn't, and a signed number + // in this locale (`-1,5`) is a number. The apostrophe keeps the engine from reading such text + // again in English syntax. + if !body.starts_with('=') && !is_number && gridcraft_engine::core::parse::starts_formula(body) { + return Ok(canonical(&format!("={body}"), locale, wb, sheet, cell).unwrap_or_else(|_| format!("'{body}"))); + } + if body.starts_with('=') { let known = |name: &str| wb.name(name, sheet).is_some() || wb.table(name).is_some(); // Match the engine's existing convenience for missing closing parentheses. let mut body = body.to_string(); @@ -160,6 +165,9 @@ mod tests { assert_eq!(entry("-1,5").as_deref(), Some("-1.5")); assert_eq!(entry("+2,5%").as_deref(), Some("+2.5%")); assert_eq!(entry("-").as_deref(), Some("-")); - assert_eq!(entry("--"), None); + // An entry that doesn't read as a formula stays text; only `=` entries are refused. + assert_eq!(entry("--").as_deref(), Some("'--")); + assert_eq!(entry("+34 612 345 678").as_deref(), Some("'+34 612 345 678")); + assert_eq!(entry("=--"), None); } } diff --git a/docs/ui-parity.md b/docs/ui-parity.md index 64cf2810e1..06e2039841 100644 --- a/docs/ui-parity.md +++ b/docs/ui-parity.md @@ -161,7 +161,7 @@ scrollbar bugs 2–4 · pixel/feel pass against observed Excel 7–12. | Date | Change | Summary | |---|---|---| -| 2026-10-20 | minor | Typing a leading `+` or `-` starts a formula whenever the entry isn't a number on its own, as in Excel: `+5+4` enters `=+5+4` and `-5+4` enters `=-5+4` (they stayed text; only a letter or `(` after the sign started one). `+5`, `-5` and `-$5` stay numbers, a lone `+` or `-` stays text, and an entry like `--` that isn't a valid formula is refused like `=--`; pasted or split by Text to Columns it stays text (#2023) | +| 2026-10-20 | minor | Typing a leading `+` or `-` starts a formula whenever the entry isn't a number on its own, as in Excel: `+5+4` enters `=+5+4` and `-5+4` enters `=-5+4` (they stayed text; only a letter or `(` after the sign started one). `+5`, `-5` and `-$5` stay numbers, and a lone `+` or `-` and an entry that doesn't read as a formula (`--`, `+49 170 1234567`) stay text, as observed in Excel for the web; only `=` entries are refused (#2023) | | 2026-10-19 | minor | Ctrl+Enter (`range.fill`) gives each cell what typing the input there gives: a General cell gets the automatic number format (`5%`, `$5`, `3/4/2026`, `=TODAY()`) even when it already held a value, and a cell with its own format, a formatted row or column, or Text keeps it. Cells that held a value used to keep General (`5%` showed 0.05), and empty cells took the active cell's format | | 2026-10-18 | minor | Keytip letters typed with left Alt held continue the sequence (Alt+H, O, A / Alt+H, O, I ran nothing before: Alt+letter cancelled keytips); other Alt combinations, AltGr and macOS Option are unchanged (#1846) | | 2026-10-12 | minor | The File view's recent list tells when each workbook was last changed, read off the UI thread | From fdad356fd25aa95166c5150a6e6aca5cb877f13a Mon Sep 17 00:00:00 2001 From: kezmdor <15539254+kezmdor@users.noreply.github.com> Date: Tue, 20 Oct 2026 08:39:07 +0200 Subject: [PATCH 05/21] AutoSum on one cell proposes its range in the editor, like Excel (fixes #1834) AutoSum from the ribbon or keyboard entered `=SUM(range)` at once, so the range could only be changed by editing the formula afterwards. On one cell it now runs with `enter: false` and leaves `=SUM(B2:B4)` in the editor with `B2:B4` pointed and selected: a click, drag, arrow key or typing replaces it, and Enter enters the formula. With nothing to sum the caret waits between the parentheses of `=SUM()`. A block still gets its totals at once, and programmatic `formulas.autoSum` (control channel, CLI, MCP) is unchanged. Co-Authored-By: Claude Opus 5.5 --- crates/ui-egui/src/editor.rs | 43 ++++++ crates/ui-egui/src/formula_bar.rs | 6 +- crates/ui-egui/src/lib.rs | 22 +++ crates/ui-egui/tests/autosum_edit.rs | 149 +++++++++++++++++++++ crates/ui-egui/tests/keyboard_shortcuts.rs | 7 +- docs/ui-parity.md | 5 +- 6 files changed, 226 insertions(+), 6 deletions(-) create mode 100644 crates/ui-egui/tests/autosum_edit.rs diff --git a/crates/ui-egui/src/editor.rs b/crates/ui-egui/src/editor.rs index 799109f890..64fa3627d5 100644 --- a/crates/ui-egui/src/editor.rs +++ b/crates/ui-egui/src/editor.rs @@ -41,6 +41,8 @@ pub struct EditState { pub completion: Option, /// Move the caret to the end on the next frame. pub caret_to_end: bool, + /// Select from this char index to `caret` when the caret is next pushed into the widget. + pub select_from: Option, } impl EditState { @@ -62,6 +64,7 @@ impl EditState { sync_caret: true, caret_to_end: true, completion: None, + select_from: None, } } @@ -107,6 +110,23 @@ impl EditState { self.sync_caret = true; } + /// Points and selects the argument of the call that ends the text, as AutoSum proposes it + /// (`=SUM(B1:B3)`): a click, drag, arrow key or typing replaces `B1:B3`. An arrow key moves + /// from the range's first cell, as in Excel: ↑ on `=SUM(A2:A4)` gives `=SUM(A1)`. With no + /// argument (`=SUM()`) the caret goes between the parentheses. + pub fn point_last_argument(&mut self) { + let Some(open) = self.text.rfind('(') else { return }; + let Some(close) = self.text.len().checked_sub(1).filter(|&c| c > open && self.text.ends_with(')')) else { return }; + let chars = |byte: usize| self.text.get(..byte).map_or(0, |t| t.chars().count()); + let (start, end) = (open + 1, close); + self.caret = chars(end); + self.point = (start < end).then_some((start, end)); + self.select_from = (start < end).then(|| chars(start)); + self.point_cell = self.text.get(start..end).and_then(RangeRef::parse).map(|r| r.start); + self.caret_to_end = false; + self.sync_caret = true; + } + /// Updates function autocomplete for the word before the caret. pub fn update_autocomplete(&mut self, names: &[String]) { self.autocomplete.clear(); @@ -316,6 +336,29 @@ mod tests { assert!(!e2.can_point()); } + #[test] + fn autosum_points_and_selects_its_proposed_range() { + // #1834: Excel leaves AutoSum's range ready to be replaced by pointing or typing. + let mut e = EditState::new(0, CellRef::new(3, 0), "=SUM(A1:A3)".into(), true, false); + e.point_last_argument(); + assert!(e.can_point()); + assert_eq!((e.caret, e.select_from, e.point), (10, Some(5), Some((5, 10)))); + assert_eq!(e.point_cell, Some(CellRef::new(0, 0)), "arrow keys move from the range's first cell"); + e.insert_ref("A2"); + assert_eq!(e.text, "=SUM(A2)"); + // No proposal: the caret waits between the parentheses. + let mut e = EditState::new(0, CellRef::new(3, 0), "=SUMA()".into(), true, false); + e.point_last_argument(); + assert!(e.can_point()); + assert_eq!((e.caret, e.select_from, e.point), (6, None, None)); + e.insert_ref("B2"); + assert_eq!(e.text, "=SUMA(B2)"); + // Text without a closing call is left alone. + let mut e = EditState::new(0, CellRef::new(3, 0), "=SUM(".into(), true, false); + e.point_last_argument(); + assert_eq!((e.caret, e.point), (5, None)); + } + #[test] fn autocomplete_and_hints() { let names: Vec = ["SUM", "SUMIF", "SUMPRODUCT", "AVERAGE"].iter().map(|s| s.to_string()).collect(); diff --git a/crates/ui-egui/src/formula_bar.rs b/crates/ui-egui/src/formula_bar.rs index 7f1ad87fc1..012a570d01 100644 --- a/crates/ui-egui/src/formula_bar.rs +++ b/crates/ui-egui/src/formula_bar.rs @@ -298,7 +298,11 @@ pub fn editor_widget(app: &mut SheetApp, ui: &mut egui::Ui, id: egui::Id, font: ed.request_focus = false; ed.sync_caret = false; let cursor = egui::text::CCursor::new(ed.caret); - output.state.cursor.set_char_range(Some(egui::text::CCursorRange::one(cursor))); + let range = match ed.select_from.take() { + Some(from) => egui::text::CCursorRange::two(egui::text::CCursor::new(from), cursor), + None => egui::text::CCursorRange::one(cursor), + }; + output.state.cursor.set_char_range(Some(range)); output.state.store(ui.ctx(), id); } else if resp.clicked() || resp.gained_focus() { // Clicking into the other editor moves editing there. diff --git a/crates/ui-egui/src/lib.rs b/crates/ui-egui/src/lib.rs index f549aec2b5..4704ef20d2 100644 --- a/crates/ui-egui/src/lib.rs +++ b/crates/ui-egui/src/lib.rs @@ -528,11 +528,33 @@ impl SheetApp { if id == "file.exportPdf" && self.services.pick_save.is_some() && params.get("path").and_then(Json::as_str).is_none_or(str::is_empty) { return self.export_pdf_with_picker(params); } + // Menu-style AutoSum on one cell proposes its formula in the editor with the range + // pointed and selected, so a click, drag, arrow key or typing replaces it, as in Excel. + // Programmatic callers use `run` and get the total entered. + if id == "formulas.autoSum" && params.get("range").is_none() && self.session.active().is_some_and(|d| d.selection.current().is_single()) { + return self.auto_sum_in_editor(params); + } if let Err(e) = self.run(id, params) { self.alert(e); } } + fn auto_sum_in_editor(&mut self, params: Json) { + let mut params = if params.is_object() { params } else { json!({}) }; + if let Some(map) = params.as_object_mut() { + map.insert("enter".into(), Json::Bool(false)); + } + if let Err(e) = self.run("formulas.autoSum", params) { + return self.alert(e); + } + if let Some(ed) = self.editor.as_mut() { + ed.point_last_argument(); + if ed.can_point() { + self.session.mode = gridcraft_engine::Mode::Point; + } + } + } + /// Asks for a `.pdf` path with the save picker, then re-runs `file.exportPdf` with it. Other /// params (range, sheets, fitToPage) are kept. A cancelled picker does nothing. fn export_pdf_with_picker(&mut self, mut params: Json) { diff --git a/crates/ui-egui/tests/autosum_edit.rs b/crates/ui-egui/tests/autosum_edit.rs new file mode 100644 index 0000000000..eae1da4079 --- /dev/null +++ b/crates/ui-egui/tests/autosum_edit.rs @@ -0,0 +1,149 @@ +//! AutoSum from the ribbon or keyboard on one cell proposes its formula in the editor, with the +//! range ready to be replaced by pointing or typing, as in Excel (#1834). + +use egui::{Event, Key, Modifiers, PointerButton, Pos2}; +use gridcraft_engine::core::{CellRef, Value}; +use gridcraft_engine::{Mode, Session}; +use gridcraft_ui_egui::{SheetApp, grid::Geo}; +use serde_json::json; + +type Harness = egui_kittest::Harness<'static, SheetApp>; + +/// 1, 2, 3 in A1:A3 and `selected` selected. +fn harness(selected: &str) -> Harness { + harness_at("A1", selected) +} + +/// 1, 2, 3 down from `first` and `selected` selected. +fn harness_at(first: &str, selected: &str) -> Harness { + let mut session = Session::new(); + session.new_workbook(); + session.execute("range.setValues", json!({"range": first, "values": [[1], [2], [3]]})).unwrap(); + session.execute("selection.set", json!({"range": selected})).unwrap(); + let mut h = egui_kittest::Harness::builder().with_size(egui::vec2(1200.0, 800.0)).build_ui_state( + |ui, app: &mut SheetApp| { + app.logic(ui.ctx()); + app.ui(ui); + }, + SheetApp::new(session, Default::default()), + ); + h.run_steps(4); + h +} + +/// The AutoSum button: a menu-style run. +fn auto_sum(h: &mut Harness) { + h.state_mut().run_or_alert("formulas.autoSum", json!({})); + h.run_steps(2); +} + +fn editing(h: &Harness) -> Option { + h.state().editor.as_ref().map(|e| e.text.clone()) +} + +fn input(h: &Harness, cell: &str) -> String { + h.state().session.active().unwrap().wb.active().unwrap().input_text(CellRef::parse(cell).unwrap()) +} + +fn cell_center(h: &Harness, cell: &str) -> 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); + geo.cell_rect(sheet, CellRef::parse(cell).unwrap()).center() +} + +fn pointer(h: &mut Harness, cell: &str, pressed: bool) { + let pos = cell_center(h, cell); + h.input_mut() + .events + .extend([Event::PointerMoved(pos), Event::PointerButton { pos, button: PointerButton::Primary, pressed, modifiers: Modifiers::NONE }]); + h.run_steps(2); +} + +fn enter(h: &mut Harness) { + for pressed in [true, false] { + h.input_mut().events.push(Event::Key { key: Key::Enter, physical_key: None, pressed, repeat: false, modifiers: Modifiers::NONE }); + } + h.run_steps(2); +} + +#[test] +fn autosum_on_one_cell_proposes_its_range_in_the_editor() { + let mut h = harness("A4"); + auto_sum(&mut h); + assert_eq!(editing(&h).as_deref(), Some("=SUM(A1:A3)")); + assert_eq!(h.state().session.mode, Mode::Point); + assert_eq!(input(&h, "A4"), "", "nothing is entered before Enter"); + enter(&mut h); + assert_eq!(input(&h, "A4"), "=SUM(A1:A3)"); + assert_eq!(h.state().session.active().unwrap().wb.active().unwrap().value(CellRef::parse("A4").unwrap()), Value::Number(6.0)); +} + +#[test] +fn a_click_or_drag_replaces_the_proposed_range() { + let mut h = harness("A4"); + auto_sum(&mut h); + pointer(&mut h, "A2", true); + pointer(&mut h, "A2", false); + assert_eq!(editing(&h).as_deref(), Some("=SUM(A2)")); + + let mut h = harness("A4"); + auto_sum(&mut h); + pointer(&mut h, "A1", true); + let to = cell_center(&h, "A2"); + for pos in [to, to + egui::vec2(1.0, 0.0)] { + h.input_mut().events.push(Event::PointerMoved(pos)); + h.step(); + } + pointer(&mut h, "A2", false); + assert_eq!(editing(&h).as_deref(), Some("=SUM(A1:A2)")); + enter(&mut h); + assert_eq!(input(&h, "A4"), "=SUM(A1:A2)"); +} + +#[test] +fn an_arrow_key_points_from_the_proposed_range() { + // Observed in Excel for the web: ↑ after AutoSum moves from the range's first cell. + let mut h = harness_at("A2", "A5"); + auto_sum(&mut h); + assert_eq!(editing(&h).as_deref(), Some("=SUM(A2:A4)")); + for pressed in [true, false] { + h.input_mut().events.push(Event::Key { key: Key::ArrowUp, physical_key: None, pressed, repeat: false, modifiers: Modifiers::NONE }); + } + h.run_steps(2); + assert_eq!(editing(&h).as_deref(), Some("=SUM(A1)")); +} + +#[test] +fn typing_replaces_the_proposed_range() { + let mut h = harness("A4"); + auto_sum(&mut h); + h.input_mut().events.push(Event::Text("A2:A3".into())); + h.run_steps(2); + assert_eq!(editing(&h).as_deref(), Some("=SUM(A2:A3)")); +} + +#[test] +fn with_nothing_to_sum_the_caret_waits_between_the_parentheses() { + let mut h = harness("C10"); + auto_sum(&mut h); + assert_eq!(editing(&h).as_deref(), Some("=SUM()")); + pointer(&mut h, "A1", true); + pointer(&mut h, "A1", false); + assert_eq!(editing(&h).as_deref(), Some("=SUM(A1)")); +} + +#[test] +fn a_block_and_programmatic_calls_enter_the_totals_at_once() { + let mut h = harness("A1:A4"); + auto_sum(&mut h); + assert!(h.state().editor.is_none()); + assert_eq!(input(&h, "A4"), "=SUM(A1:A3)"); + + // The control channel, CLI and MCP run commands with `run`: no editor. + let mut h = harness("A4"); + h.state_mut().run("formulas.autoSum", json!({})).unwrap(); + h.run_steps(2); + assert!(h.state().editor.is_none()); + assert_eq!(input(&h, "A4"), "=SUM(A1:A3)"); +} diff --git a/crates/ui-egui/tests/keyboard_shortcuts.rs b/crates/ui-egui/tests/keyboard_shortcuts.rs index 78bc966f51..5fc62f1e0f 100644 --- a/crates/ui-egui/tests/keyboard_shortcuts.rs +++ b/crates/ui-egui/tests/keyboard_shortcuts.rs @@ -235,9 +235,10 @@ fn alt_equals_autosum_does_not_also_type_the_equals_sign() { for (selected, cell, formula) in [("A4", "A4", "=SUM(A1:A3)"), ("C3", "C3", "=SUM(A3:B3)"), ("A1:B3", "B4", "=SUM(B1:B3)")] { let mut h = harness(book(selected)); alt_equals(&mut h); - assert_eq!(input(&h, cell), formula, "Alt+= on {selected}"); - assert!(h.state().editor.is_none(), "Alt+= on {selected} started an edit"); - // Enter moves on: there is no stray `=` edit to commit. + // One cell: the formula waits in the editor for Enter, as in Excel (#1834); a block gets + // its totals at once. Either way without a stray `=`. + let editing = h.state().editor.as_ref().map(|e| e.text.clone()); + assert_eq!(editing.as_deref(), (!selected.contains(':')).then_some(formula), "Alt+= on {selected}"); key(&mut h, Key::Enter, Modifiers::NONE); assert!(h.state().message.is_none(), "Alt+= on {selected}: {:?}", h.state().message); assert_eq!(input(&h, cell), formula); diff --git a/docs/ui-parity.md b/docs/ui-parity.md index 34cb502f54..2de457262c 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-19 · **Change:** minor (Ctrl+Enter fill gives each cell the automatic number format typing gives it; keytip letters typed with Alt held, #1846) · **Target:** Microsoft Excel (Microsoft 365), Excel for Mac 16.113.4 +> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-10-20 · **Change:** minor (AutoSum on one cell proposes its range in the editor, #1834) · **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 @@ -48,7 +48,7 @@ this logic, with one undo step. | Fill handle: drag to fill series, double-click to fill down, right-drag menu | fill done (Ctrl+drag swaps copy and series); right-drag menu missing | | Drag-move and drag-copy cells (border drag, Ctrl/Option, Shift to insert) | done (M3) | | In-cell editing, Enter/Tab movement, Alt/Option+Enter line breaks | done | -| Point mode (click/drag/arrow references), reference colouring, F4 | done | +| Point mode (click/drag/arrow references), reference colouring, F4 | done; AutoSum on one cell leaves its proposed range pointed and selected (#1834) | | AutoComplete in columns, function autocomplete and argument tips | done; cell helpers clip to the worksheet and hide when the editor scrolls out (#200) | | Header resize and double-click AutoFit | done (#42, #88 for header dividers) | | Outline symbols for grouped rows / columns (band beside the headers, brackets, − / +, level buttons 1…n+1) | done (#373): clicks run `data.hideDetail` / `data.showDetail` / `data.showLevels`, frozen panes and right-to-left sheets included; summary rows/columns are always below/right (the "Summary rows below detail" setting isn't modelled), no "Show outline symbols" option yet, and a block of cells still groups rows without the Rows / Columns dialog | @@ -161,6 +161,7 @@ scrollbar bugs 2–4 · pixel/feel pass against observed Excel 7–12. | Date | Change | Summary | |---|---|---| +| 2026-10-20 | minor | AutoSum from the ribbon or keyboard on one cell proposes `=SUM(range)` in the editor instead of entering it, with the range pointed and selected: a click, drag, arrow key or typing replaces it and Enter enters it, as in Excel. With nothing to sum the caret waits inside `=SUM()`. A block still gets its totals at once, and programmatic `formulas.autoSum` is unchanged (#1834) | | 2026-10-19 | minor | Ctrl+Enter (`range.fill`) gives each cell what typing the input there gives: a General cell gets the automatic number format (`5%`, `$5`, `3/4/2026`, `=TODAY()`) even when it already held a value, and a cell with its own format, a formatted row or column, or Text keeps it. Cells that held a value used to keep General (`5%` showed 0.05), and empty cells took the active cell's format | | 2026-10-18 | minor | Keytip letters typed with left Alt held continue the sequence (Alt+H, O, A / Alt+H, O, I ran nothing before: Alt+letter cancelled keytips); other Alt combinations, AltGr and macOS Option are unchanged (#1846) | | 2026-10-12 | minor | The File view's recent list tells when each workbook was last changed, read off the UI thread | From 132bd4e9a8fa99befcae74ef8b7af1910dd6c98f Mon Sep 17 00:00:00 2001 From: kezmdor <15539254+kezmdor@users.noreply.github.com> Date: Tue, 20 Oct 2026 08:59:30 +0200 Subject: [PATCH 06/21] AutoSum: test the menu functions; keep the new editor method clear of #1056 MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Home › AutoSum ▾ Average proposes `=AVERAGE(range)` the same way (and so will Formulas › AutoSum once it has the menu, #658). `point_last_argument` moves to the end of `impl EditState`, so this PR no longer touches the lines #1056 and #1838 change after `insert_ref`. Co-Authored-By: Claude Opus 5.5 --- crates/ui-egui/src/editor.rs | 34 ++++++++++++++-------------- crates/ui-egui/tests/autosum_edit.rs | 12 ++++++++++ 2 files changed, 29 insertions(+), 17 deletions(-) diff --git a/crates/ui-egui/src/editor.rs b/crates/ui-egui/src/editor.rs index 64fa3627d5..2061a0dbda 100644 --- a/crates/ui-egui/src/editor.rs +++ b/crates/ui-egui/src/editor.rs @@ -110,23 +110,6 @@ impl EditState { self.sync_caret = true; } - /// Points and selects the argument of the call that ends the text, as AutoSum proposes it - /// (`=SUM(B1:B3)`): a click, drag, arrow key or typing replaces `B1:B3`. An arrow key moves - /// from the range's first cell, as in Excel: ↑ on `=SUM(A2:A4)` gives `=SUM(A1)`. With no - /// argument (`=SUM()`) the caret goes between the parentheses. - pub fn point_last_argument(&mut self) { - let Some(open) = self.text.rfind('(') else { return }; - let Some(close) = self.text.len().checked_sub(1).filter(|&c| c > open && self.text.ends_with(')')) else { return }; - let chars = |byte: usize| self.text.get(..byte).map_or(0, |t| t.chars().count()); - let (start, end) = (open + 1, close); - self.caret = chars(end); - self.point = (start < end).then_some((start, end)); - self.select_from = (start < end).then(|| chars(start)); - self.point_cell = self.text.get(start..end).and_then(RangeRef::parse).map(|r| r.start); - self.caret_to_end = false; - self.sync_caret = true; - } - /// Updates function autocomplete for the word before the caret. pub fn update_autocomplete(&mut self, names: &[String]) { self.autocomplete.clear(); @@ -211,6 +194,23 @@ impl EditState { } None } + + /// Points and selects the argument of the call that ends the text, as AutoSum proposes it + /// (`=SUM(B1:B3)`): a click, drag, arrow key or typing replaces `B1:B3`. An arrow key moves + /// from the range's first cell, as in Excel: ↑ on `=SUM(A2:A4)` gives `=SUM(A1)`. With no + /// argument (`=SUM()`) the caret goes between the parentheses. + pub fn point_last_argument(&mut self) { + let Some(open) = self.text.rfind('(') else { return }; + let Some(close) = self.text.len().checked_sub(1).filter(|&c| c > open && self.text.ends_with(')')) else { return }; + let chars = |byte: usize| self.text.get(..byte).map_or(0, |t| t.chars().count()); + let (start, end) = (open + 1, close); + self.caret = chars(end); + self.point = (start < end).then_some((start, end)); + self.select_from = (start < end).then(|| chars(start)); + self.point_cell = self.text.get(start..end).and_then(RangeRef::parse).map(|r| r.start); + self.caret_to_end = false; + self.sync_caret = true; + } } /// References in formula text with their byte spans and colour index (same reference text ⇒ diff --git a/crates/ui-egui/tests/autosum_edit.rs b/crates/ui-egui/tests/autosum_edit.rs index eae1da4079..a1bc0342bf 100644 --- a/crates/ui-egui/tests/autosum_edit.rs +++ b/crates/ui-egui/tests/autosum_edit.rs @@ -79,6 +79,18 @@ fn autosum_on_one_cell_proposes_its_range_in_the_editor() { assert_eq!(h.state().session.active().unwrap().wb.active().unwrap().value(CellRef::parse("A4").unwrap()), Value::Number(6.0)); } +#[test] +fn the_autosum_menu_functions_propose_theirs_the_same_way() { + // Home › AutoSum ▾ Average (and Formulas › AutoSum ▾ once it has the menu, #658). + let mut h = harness("A4"); + h.state_mut().run_or_alert("formulas.autoSum", json!({"function": "AVERAGE"})); + h.run_steps(2); + assert_eq!(editing(&h).as_deref(), Some("=AVERAGE(A1:A3)")); + pointer(&mut h, "A2", true); + pointer(&mut h, "A2", false); + assert_eq!(editing(&h).as_deref(), Some("=AVERAGE(A2)")); +} + #[test] fn a_click_or_drag_replaces_the_proposed_range() { let mut h = harness("A4"); From 601cc60cfcaf15e8f3db0526cbdf26083b4fa4ac Mon Sep 17 00:00:00 2001 From: kezmdor <15539254+kezmdor@users.noreply.github.com> Date: Tue, 20 Oct 2026 09:17:48 +0200 Subject: [PATCH 07/21] AutoSum: a `range` that isn't text counts as no range, as in the engine `formulas.autoSum` reads `range` with `str_param`, so `{"range": null}` means the selection; the UI's check for the editor proposal now reads it the same way (CodeRabbit review). Co-Authored-By: Claude Opus 5.5 --- crates/ui-egui/src/lib.rs | 7 ++++++- crates/ui-egui/tests/autosum_edit.rs | 6 ++++++ 2 files changed, 12 insertions(+), 1 deletion(-) diff --git a/crates/ui-egui/src/lib.rs b/crates/ui-egui/src/lib.rs index 4704ef20d2..1606a85473 100644 --- a/crates/ui-egui/src/lib.rs +++ b/crates/ui-egui/src/lib.rs @@ -531,7 +531,10 @@ impl SheetApp { // Menu-style AutoSum on one cell proposes its formula in the editor with the range // pointed and selected, so a click, drag, arrow key or typing replaces it, as in Excel. // Programmatic callers use `run` and get the total entered. - if id == "formulas.autoSum" && params.get("range").is_none() && self.session.active().is_some_and(|d| d.selection.current().is_single()) { + if id == "formulas.autoSum" + && params.get("range").and_then(Json::as_str).is_none() + && self.session.active().is_some_and(|d| d.selection.current().is_single()) + { return self.auto_sum_in_editor(params); } if let Err(e) = self.run(id, params) { @@ -539,6 +542,8 @@ impl SheetApp { } } + /// Runs AutoSum on the active cell without entering it (`enter: false`) and points the + /// proposed range in the editor that opens. fn auto_sum_in_editor(&mut self, params: Json) { let mut params = if params.is_object() { params } else { json!({}) }; if let Some(map) = params.as_object_mut() { diff --git a/crates/ui-egui/tests/autosum_edit.rs b/crates/ui-egui/tests/autosum_edit.rs index a1bc0342bf..9f76bf8a8d 100644 --- a/crates/ui-egui/tests/autosum_edit.rs +++ b/crates/ui-egui/tests/autosum_edit.rs @@ -77,6 +77,12 @@ fn autosum_on_one_cell_proposes_its_range_in_the_editor() { enter(&mut h); assert_eq!(input(&h, "A4"), "=SUM(A1:A3)"); assert_eq!(h.state().session.active().unwrap().wb.active().unwrap().value(CellRef::parse("A4").unwrap()), Value::Number(6.0)); + + // A `range` that isn't text is no range, for the engine and here alike. + let mut h = harness("A4"); + h.state_mut().run_or_alert("formulas.autoSum", json!({"range": null})); + h.run_steps(2); + assert_eq!(editing(&h).as_deref(), Some("=SUM(A1:A3)")); } #[test] From edd64e9afc0965320868f113afa6404f5739c63d Mon Sep 17 00:00:00 2001 From: Marco Arnulfo Date: Fri, 23 Oct 2026 00:47:02 +0200 Subject: [PATCH 08/21] View: zooming is not an undo step (fixes #2313) --- crates/engine/src/cmd/edit.rs | 2 + crates/engine/src/cmd/view.rs | 71 +++++++++++++++++++- crates/engine/tests/command_sequence_fuzz.rs | 5 +- 3 files changed, 73 insertions(+), 5 deletions(-) diff --git a/crates/engine/src/cmd/edit.rs b/crates/engine/src/cmd/edit.rs index e537407127..21421902f0 100644 --- a/crates/engine/src/cmd/edit.rs +++ b/crates/engine/src/cmd/edit.rs @@ -660,6 +660,7 @@ fn undo(s: &mut Session, p: &Json) -> Result { crate::push_history(&mut d.redo, label.clone(), cur_wb, &d.wb, cur_selection); } super::extra::keep_watch_list(&now, &mut d.wb); + super::view::keep_zoom(d, &now); d.calc.rebuild(&d.wb); d.revision += 1; Ok(json!({"undone": label})) @@ -680,6 +681,7 @@ fn redo(s: &mut Session, p: &Json) -> Result { crate::push_history(&mut d.undo, label.clone(), cur_wb, &d.wb, cur_selection); } super::extra::keep_watch_list(&now, &mut d.wb); + super::view::keep_zoom(d, &now); d.calc.rebuild(&d.wb); d.revision += 1; Ok(json!({"redone": label})) diff --git a/crates/engine/src/cmd/view.rs b/crates/engine/src/cmd/view.rs index f0b2f77d39..9af8941852 100644 --- a/crates/engine/src/cmd/view.rs +++ b/crates/engine/src/cmd/view.rs @@ -37,13 +37,13 @@ pub fn specs() -> Vec { cmd!("view.showZeros", "Show Zeros", [], None, "{on?}", has_doc, |s, p| sheet_flag(s, p, "zeros")), cmd!("view.showObjects", "Show Objects", [], Some("Ctrl+6"), "{on?}", has_doc, show_objects), cmd!("view.rightToLeft", "Sheet Right-to-Left", ["Page Layout", "Sheet Options"], None, "{on?}", has_doc, |s, p| sheet_flag(s, p, "rtl")), - cmd!("view.zoom", "Zoom", ["View", "Zoom"], None, "{percent: 10..400}", has_doc, zoom), - cmd!("view.zoom100", "100%", ["View", "Zoom"], None, "{}", has_doc, |s, _| zoom(s, &json!({"percent": 100}))), + cmd!(noundo "view.zoom", "Zoom", ["View", "Zoom"], None, "{percent: 10..400}", has_doc, zoom), + cmd!(noundo "view.zoom100", "100%", ["View", "Zoom"], None, "{}", has_doc, |s, _| zoom(s, &json!({"percent": 100}))), cmd!(query "view.formulaBar", "Formula Bar", ["View", "Show"], None, "{on?: bool}", always, |s, p| { s.prefs.formula_bar = bool_param(p, "on").unwrap_or(!s.prefs.formula_bar); Ok(json!({"on": s.prefs.formula_bar})) }), - cmd!("view.zoomToSelection", "Zoom to Selection", ["View", "Zoom"], None, "{viewWidth?, viewHeight?}", has_doc, zoom_selection), + cmd!(noundo "view.zoomToSelection", "Zoom to Selection", ["View", "Zoom"], None, "{viewWidth?, viewHeight?}", has_doc, zoom_selection), cmd!("pageLayout.orientation", "Orientation", ["Page Layout", "Page Setup"], None, "{orientation: portrait|landscape}", has_doc, orientation), cmd!( "pageLayout.size", @@ -200,6 +200,28 @@ fn zoom(s: &mut Session, p: &Json) -> Result { Ok(json!({"zoom": z})) } +/// Zoom belongs to the window, not to the edits (Excel doesn't undo it, #2313): undo and redo keep +/// each sheet's current zoom when they swap in another snapshot of the workbook. Back at the saved +/// state, the zoom alone doesn't make the workbook dirty, as with `view.zoom`. +pub(crate) fn keep_zoom(d: &mut crate::DocState, now: &Workbook) { + let current = |name: &str| now.sheets.iter().find(|sh| sh.name == name).map(|sh| sh.zoom); + let changed: Vec<(usize, u16)> = + d.wb.sheets.iter().enumerate().filter_map(|(i, sh)| current(&sh.name).filter(|z| *z != sh.zoom).map(|z| (i, z))).collect(); + if changed.is_empty() { + return; + } + let saved = std::sync::Arc::ptr_eq(&d.wb, &d.saved); + let wb = std::sync::Arc::make_mut(&mut d.wb); + for (i, z) in changed { + if let Some(sh) = wb.sheet_mut(i) { + sh.zoom = z; + } + } + if saved { + d.saved = d.wb.clone(); + } +} + fn zoom_selection(s: &mut Session, p: &Json) -> Result { let d = s.doc()?; let sh = d.wb.active().ok_or(EngineError::NoDocument)?; @@ -466,6 +488,49 @@ mod tests { assert_eq!(s.doc().unwrap().wb.active().unwrap().zoom, 100); } + #[test] + fn zooming_is_not_an_undo_step() { + // Excel keeps zoom on the window, not in the edit history (#2313): wheel, slider, dialog, + // 100% and Zoom to Selection leave Undo and Redo alone. + let mut s = Session::new(); + s.new_workbook(); + s.execute("cell.set", json!({"cell": "A1", "input": "x"})).unwrap(); + s.execute("cell.set", json!({"cell": "A2", "input": "y"})).unwrap(); + s.execute("edit.undo", json!({})).unwrap(); + let (undo, redo) = s.doc().map(|d| (d.undo.len(), d.redo.len())).unwrap(); + for (id, params, zoom) in [ + ("view.zoom", json!({"percent": 150}), 150), + ("view.zoomToSelection", json!({"viewWidth": 1200, "viewHeight": 700}), 400), + ("view.zoom100", json!({}), 100), + ] { + s.execute(id, params).unwrap(); + let d = s.doc().unwrap(); + assert_eq!(d.wb.active().unwrap().zoom, zoom, "{id}"); + assert_eq!((d.undo.len(), d.redo.len()), (undo, redo), "{id} touched the history"); + } + let a1 = CellRef::parse("A1").unwrap(); + s.execute("edit.undo", json!({})).unwrap(); + assert!(s.doc().unwrap().wb.active().unwrap().value(a1).is_empty(), "Ctrl+Z after zooming undoes the last edit"); + } + + #[test] + fn undo_and_redo_keep_the_current_zoom() { + let mut s = Session::new(); + s.new_workbook(); + let zoom = |s: &Session| s.doc().unwrap().wb.active().unwrap().zoom; + s.execute("cell.set", json!({"cell": "A1", "input": "x"})).unwrap(); + s.execute("view.zoom", json!({"percent": 200})).unwrap(); + s.execute("edit.undo", json!({})).unwrap(); + assert!(s.doc().unwrap().wb.active().unwrap().value(CellRef::parse("A1").unwrap()).is_empty()); + assert_eq!(zoom(&s), 200, "undo keeps the zoom"); + // Back at the state on disk: the zoom alone doesn't make the workbook dirty, as in `zoom`. + assert!(!s.doc().unwrap().is_dirty()); + s.execute("view.zoom", json!({"percent": 50})).unwrap(); + s.execute("edit.redo", json!({})).unwrap(); + assert!(!s.doc().unwrap().wb.active().unwrap().value(CellRef::parse("A1").unwrap()).is_empty()); + assert_eq!(zoom(&s), 50, "redo keeps the zoom"); + } + #[test] fn formula_bar_toggles_without_a_workbook_and_defaults_to_shown() { let mut s = Session::new(); diff --git a/crates/engine/tests/command_sequence_fuzz.rs b/crates/engine/tests/command_sequence_fuzz.rs index f8cb603cba..4ed7dc0428 100644 --- a/crates/engine/tests/command_sequence_fuzz.rs +++ b/crates/engine/tests/command_sequence_fuzz.rs @@ -485,8 +485,8 @@ fn watch_list(wb: &Workbook) -> Option<&str> { wb.names.iter().find(|n| n.name == WATCH_NAME).map(|n| n.formula.as_str()) } -/// The workbook with view state (active sheet, scroll, active cell) and the Watch Window list -/// reset: undo restores view state as it was, but switching sheets isn't an undoable edit. +/// The workbook with view state (active sheet, scroll, active cell, zoom) and the Watch Window list +/// reset: undo restores view state as it was, but switching sheets or zooming isn't an undoable edit. fn canonical(wb: &Workbook) -> Workbook { let mut wb = wb.clone(); wb.active_sheet = 0; @@ -495,6 +495,7 @@ fn canonical(wb: &Workbook) -> Workbook { let sh = Arc::make_mut(sh); sh.view_active = CellRef::default(); sh.view_top_left = CellRef::default(); + sh.zoom = 100; } wb } From b9324d91796fc91b53c7e4042de021dcc2cddafc Mon Sep 17 00:00:00 2001 From: kezmdor <15539254+kezmdor@users.noreply.github.com> Date: Fri, 23 Oct 2026 09:13:27 +0200 Subject: [PATCH 09/21] Formula entry: text that would read as a formula is edited with its apostrophe `text_needs_quote_prefix` still used the old rule (a sign followed by a letter or `(`), so text such as `+5+4` (typed as `'+5+4`, or read from a CSV or XLSX) was edited without its apostrophe and became a formula when confirmed unchanged. It now asks what `input_to_cell` asks: the entry starts a formula and parses as one. Text that stays text anyway (`--`) is still edited as it is. Found by @iluebbe in #2023. Co-Authored-By: Claude Opus 5.5 --- crates/engine/src/display.rs | 10 +++++++--- crates/engine/src/tests.rs | 20 ++++++++++++++++++++ 2 files changed, 27 insertions(+), 3 deletions(-) diff --git a/crates/engine/src/display.rs b/crates/engine/src/display.rs index aa8bdb22dd..ad94c808c1 100644 --- a/crates/engine/src/display.rs +++ b/crates/engine/src/display.rs @@ -41,12 +41,16 @@ fn text_needs_quote_prefix(t: &str, sys: gridcraft_core::date::DateSystem) -> bo if t.is_empty() { return false; } - let mut chars = t.chars(); - let (first, second) = (chars.next(), chars.next()); + let first = t.chars().next(); if matches!(first, Some('=' | '\'')) { return true; } - if matches!(first, Some('+' | '-')) && second.is_some_and(|c| c.is_ascii_alphabetic() || c == '(') { + // A `+` or `-` entry that reads as a formula becomes one (`+5+4`, `-abc`); one that doesn't + // stays text (`--`, `+49 170 1234567`), as `input_to_cell` decides it. + if matches!(first, Some('+' | '-')) + && gridcraft_core::parse::starts_formula(t) + && crate::cmd::edit::parse_typed_formula(t).is_ok_and(|e| crate::cmd::edit::check_arg_counts(&e).is_ok()) + { return true; } !matches!(gridcraft_core::parse::parse_input(t, sys).value, Value::Text(ref x) if x.as_ref() == t) diff --git a/crates/engine/src/tests.rs b/crates/engine/src/tests.rs index 285d64ce97..c10a39a9cd 100644 --- a/crates/engine/src/tests.rs +++ b/crates/engine/src/tests.rs @@ -267,6 +267,26 @@ fn a_leading_plus_or_minus_starts_a_formula() { assert_eq!(v(&s, "B1"), value, "{typed}"); assert!(!input(&s, "B1").is_some_and(|t| t.starts_with('=')), "{typed}"); } + // Text that would read as a formula is edited with its apostrophe, so confirming the editor + // unchanged keeps it text; text that wouldn't is edited as it is. + for (typed, shown) in [ + ("'+5+4", "'+5+4"), + ("'-5+4", "'-5+4"), + ("'+1-555-1234", "'+1-555-1234"), + ("'-abc", "'-abc"), + ("--", "--"), + ("+49 170 1234567", "+49 170 1234567"), + ] { + s.execute("cell.set", json!({"cell": "B2", "input": typed})).unwrap(); + let before = v(&s, "B2"); + let edit = { + let d = s.doc().unwrap(); + crate::display::edit_text(&d.wb, d.wb.active().unwrap(), CellRef::parse("B2").unwrap()) + }; + assert_eq!(edit, shown, "{typed}"); + s.execute("cell.set", json!({"cell": "B2", "input": edit})).unwrap(); + assert_eq!(v(&s, "B2"), before, "{typed} stays text after an unchanged edit"); + } // As observed in Excel for the web, an entry that doesn't read as a formula stays text, and // one that does but names nothing known is #NAME?. Only `=` entries are refused. for typed in ["--", "-----", "+5+", "+49 170 1234567"] { From b21dd9151f49a810e364ea1243c27fd928163a86 Mon Sep 17 00:00:00 2001 From: Marco Arnulfo Date: Fri, 23 Oct 2026 10:18:20 +0200 Subject: [PATCH 10/21] Keep the zoom when undoing or redoing a sheet rename keep_zoom matched sheets by name, so undoing a rename found no match and brought back the zoom from before the rename. A sheet missing by name now falls back to the one at the same index, when the sheet count is unchanged and that sheet's name isn't in the restored snapshot. --- crates/engine/src/cmd/view.rs | 28 ++++++++++++++++++++++++++-- 1 file changed, 26 insertions(+), 2 deletions(-) diff --git a/crates/engine/src/cmd/view.rs b/crates/engine/src/cmd/view.rs index 9af8941852..d403e425a8 100644 --- a/crates/engine/src/cmd/view.rs +++ b/crates/engine/src/cmd/view.rs @@ -204,9 +204,15 @@ fn zoom(s: &mut Session, p: &Json) -> Result { /// each sheet's current zoom when they swap in another snapshot of the workbook. Back at the saved /// state, the zoom alone doesn't make the workbook dirty, as with `view.zoom`. pub(crate) fn keep_zoom(d: &mut crate::DocState, now: &Workbook) { - let current = |name: &str| now.sheets.iter().find(|sh| sh.name == name).map(|sh| sh.zoom); + // Sheets have no stable id. A name missing from `now` is a rename being undone or redone, which + // keeps the sheet count and position: the sheet is the one at the same index, under a name the + // restored snapshot doesn't have. + let renamed = |i: usize| { + (now.sheets.len() == d.wb.sheets.len()).then(|| now.sheets.get(i)).flatten().filter(|sh| !d.wb.sheets.iter().any(|s| s.name == sh.name)) + }; + let current = |i: usize, name: &str| now.sheets.iter().find(|sh| sh.name == name).or_else(|| renamed(i)).map(|sh| sh.zoom); let changed: Vec<(usize, u16)> = - d.wb.sheets.iter().enumerate().filter_map(|(i, sh)| current(&sh.name).filter(|z| *z != sh.zoom).map(|z| (i, z))).collect(); + d.wb.sheets.iter().enumerate().filter_map(|(i, sh)| current(i, &sh.name).filter(|z| *z != sh.zoom).map(|z| (i, z))).collect(); if changed.is_empty() { return; } @@ -531,6 +537,24 @@ mod tests { assert_eq!(zoom(&s), 50, "redo keeps the zoom"); } + #[test] + fn undoing_a_rename_keeps_the_current_zoom() { + let mut s = Session::new(); + s.new_workbook(); + let active = |s: &Session| { + let sh = s.doc().unwrap().wb.active().unwrap(); + (sh.name.clone(), sh.zoom) + }; + let before = active(&s).0; + s.execute("sheet.rename", json!({"name": "Data"})).unwrap(); + s.execute("view.zoom", json!({"percent": 150})).unwrap(); + s.execute("edit.undo", json!({})).unwrap(); + assert_eq!(active(&s), (before, 150), "undoing the rename keeps the zoom"); + s.execute("view.zoom", json!({"percent": 75})).unwrap(); + s.execute("edit.redo", json!({})).unwrap(); + assert_eq!(active(&s), ("Data".to_string(), 75), "redoing the rename keeps the zoom"); + } + #[test] fn formula_bar_toggles_without_a_workbook_and_defaults_to_shown() { let mut s = Session::new(); From 42ad67ab13f8ae45da75dfa45b72b3b0ed5390f5 Mon Sep 17 00:00:00 2001 From: Marco Arnulfo Date: Fri, 23 Oct 2026 15:23:03 +0200 Subject: [PATCH 11/21] Keep the zoom per step when undoing or redoing several steps edit.undo and edit.redo with `steps` > 1 ran keep_zoom once, comparing the first and last snapshots. Adding C and deleting B leaves the same sheet count under other names, which keep_zoom took for a rename of B to C, so C's zoom landed on B. keep_zoom now runs after each restored snapshot, against the one it replaces. --- crates/engine/src/cmd/edit.rs | 4 ++-- crates/engine/src/cmd/view.rs | 27 +++++++++++++++++++++++++++ 2 files changed, 29 insertions(+), 2 deletions(-) diff --git a/crates/engine/src/cmd/edit.rs b/crates/engine/src/cmd/edit.rs index 21421902f0..e9c5e1768d 100644 --- a/crates/engine/src/cmd/edit.rs +++ b/crates/engine/src/cmd/edit.rs @@ -657,10 +657,10 @@ fn undo(s: &mut Session, p: &Json) -> Result { label = e.label.clone(); d.wb = e.wb; d.selection = e.selection; + super::view::keep_zoom(d, &cur_wb); crate::push_history(&mut d.redo, label.clone(), cur_wb, &d.wb, cur_selection); } super::extra::keep_watch_list(&now, &mut d.wb); - super::view::keep_zoom(d, &now); d.calc.rebuild(&d.wb); d.revision += 1; Ok(json!({"undone": label})) @@ -678,10 +678,10 @@ fn redo(s: &mut Session, p: &Json) -> Result { label = e.label.clone(); d.wb = e.wb; d.selection = e.selection; + super::view::keep_zoom(d, &cur_wb); crate::push_history(&mut d.undo, label.clone(), cur_wb, &d.wb, cur_selection); } super::extra::keep_watch_list(&now, &mut d.wb); - super::view::keep_zoom(d, &now); d.calc.rebuild(&d.wb); d.revision += 1; Ok(json!({"redone": label})) diff --git a/crates/engine/src/cmd/view.rs b/crates/engine/src/cmd/view.rs index d403e425a8..30a843f911 100644 --- a/crates/engine/src/cmd/view.rs +++ b/crates/engine/src/cmd/view.rs @@ -555,6 +555,33 @@ mod tests { assert_eq!(active(&s), ("Data".to_string(), 75), "redoing the rename keeps the zoom"); } + #[test] + fn undoing_several_steps_keeps_each_sheet_its_own_zoom() { + // Adding C then deleting B leaves as many sheets as before under other names: across both + // steps at once, that looks like B renamed to C, and C's zoom used to land on B. + let mut s = Session::new(); + s.new_workbook(); + let zoom = |s: &Session, name: &str| { + let wb = &s.doc().unwrap().wb; + wb.sheet(wb.sheet_index(name).unwrap()).unwrap().zoom + }; + let names = |s: &Session| s.doc().unwrap().wb.sheets.iter().map(|sh| sh.name.clone()).collect::>(); + let first = names(&s)[0].clone(); + s.execute("home.insertSheet", json!({"name": "B", "before": 1})).unwrap(); + s.execute("home.insertSheet", json!({"name": "C", "before": 2})).unwrap(); + s.execute("home.deleteSheet", json!({"sheet": "B"})).unwrap(); + s.execute("sheet.activate", json!({"sheet": "C"})).unwrap(); + s.execute("view.zoom", json!({"percent": 150})).unwrap(); + s.execute("edit.undo", json!({"steps": 2})).unwrap(); + assert_eq!(names(&s), [first.clone(), "B".to_string()]); + assert_eq!(zoom(&s, "B"), 100, "B never had C's zoom"); + s.execute("sheet.activate", json!({"sheet": "B"})).unwrap(); + s.execute("view.zoom", json!({"percent": 80})).unwrap(); + s.execute("edit.redo", json!({"steps": 2})).unwrap(); + assert_eq!(names(&s), [first, "C".to_string()]); + assert_eq!(zoom(&s, "C"), 150, "C gets its own zoom back, not B's"); + } + #[test] fn formula_bar_toggles_without_a_workbook_and_defaults_to_shown() { let mut s = Session::new(); From dd136062f557a77213147e69e5e911cf326b6037 Mon Sep 17 00:00:00 2001 From: zyzabruh Date: Mon, 26 Oct 2026 01:27:52 +0100 Subject: [PATCH 12/21] Paste Special: a transposed paste turns formula references as Excel does (fixes #2450) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Paste Special > Transpose moved the copied cells but adjusted every formula with `shift_relative`, the adjustment of an ordinary copy, so the formula kept the offset it had in the source: `=A3+1` copied from A3:A4 and pasted at C3 read the cell above instead of the cell to its left and showed 1/1/1900. Excel turns the references instead. Observed against Excel 16 on synthetic workbooks (relative, `$B$1`, `B$1`, `$B1`, ranges, another sheet, whole rows and columns, a reference off the grid, a source block not starting at A1, and a 2x2 block): the row offset of a reference becomes its column offset and the other way round around the pair of positions of the cell carrying the formula, `(r, c)` -> `dest + (c - src.col, r - src.row)`. A reference pinned with `$` is left exactly as written, a whole-row or whole-column reference comes back as a cell range whose open side runs from the transposed far edge of the sheet to its end (`1:2` -> `F$6:G$1048576`), and a result outside the grid is `#REF!`. `adjust::transpose_relative(e, src, dest)` implements that beside `shift_relative`, and `paste_special` uses it when `transpose` is set; the paste-link and cut-paste paths are untouched. Tests: `tests::copy_transpose` in gridcraft-formula covers the observed cases including the two shapes above and `#REF!`; `transposed_paste_turns_the_formula_with_the_cell_that_carries_it` replays the issue's steps and checks the value is the day after the cell to the left, `transposed_paste_turns_every_kind_of_reference_the_way_excel_does` covers a relative, a pinned, a ranged and a whole-column reference end to end. Docs: docs/ui-parity.md (header and revision history), ROADMAP.md (header and progress log). 🤖 Generated with Codebuff Co-Authored-By: Codebuff --- ROADMAP.md | 3 +- crates/engine/src/cmd/edit.rs | 41 +++++++++++++++++++++-- crates/formula/src/adjust.rs | 62 ++++++++++++++++++++++++++++++++++- crates/formula/src/tests.rs | 23 ++++++++++++- docs/ui-parity.md | 3 +- 5 files changed, 126 insertions(+), 6 deletions(-) diff --git a/ROADMAP.md b/ROADMAP.md index c9e746bc5a..62c9e7217c 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-25 · **Change:** minor (AutoSum over a selected row puts its total to the right, and fills a selection's empty last row and column) · **Target:** Microsoft Excel (Microsoft 365) +> **Last reviewed:** 2026-10-11 · **Last updated:** 2026-10-26 · **Change:** minor (Paste Special ▸ Transpose turns a formula's references with the cell that carries it, as Excel does) · **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. @@ -135,6 +135,7 @@ Ranked; estimates in Opus 5.5 agent-hours. Detail and the full beta-gate list in | Date | What landed | |---|---| +| 2026-10-26 | Paste Special ▸ Transpose turns a formula's references with the cell that carries it, as Excel does: the row offset becomes the column offset and the other way round, so `=A3+1` copied from A3:A4 and pasted at C3 reads the cell to its left (`=C3+1`) instead of keeping the offset it had in the column; a reference pinned with `$` is left standing, a whole row or column comes back as a cell range open to the sheet's edge, and one off the grid is `#REF!` (#2450) | | 2026-10-25 | AutoSum over a selection does what Excel does: a selected row gets one total to its right (in its last cell if that is empty), not a one-cell total under each cell; a block whose last column is empty gets each row's total there, one whose last row is empty each column's, and with both the corner gets the total of the block; otherwise totals go under each column as before | | 2026-10-24 | Go To lists the named ranges of every sheet (`Sheet2!Name` for a name scoped to another sheet; hidden names, constants and formulas left out) and the references entered before, a double-click goes to an entry, and the Reference box takes several names or references separated by commas (`Price, Type`, `B14:C22,F19:G30`) | | 2026-10-24 | Status bar: a right-click opens a menu that sets which selection statistics show (Average, Count and Sum by default; Numerical Count, Minimum and Maximum are new), kept with the preferences (`view.statusBar`) | diff --git a/crates/engine/src/cmd/edit.rs b/crates/engine/src/cmd/edit.rs index 102edc2d36..7009b1878d 100644 --- a/crates/engine/src/cmd/edit.rs +++ b/crates/engine/src/cmd/edit.rs @@ -1219,8 +1219,12 @@ fn paste_special(s: &mut Session, p: &Json) -> Result { moved.dynamic = f.dynamic; return Some(std::sync::Arc::new(moved)); } - let moved = - gridcraft_formula::adjust::shift_relative(e, dest.row as i64 - sc.row as i64, dest.col as i64 - sc.col as i64); + let moved = if transpose { + // A transposed paste turns the references instead of shifting them (#2450). + gridcraft_formula::adjust::transpose_relative(e, sc, dest) + } else { + gridcraft_formula::adjust::shift_relative(e, dest.row as i64 - sc.row as i64, dest.col as i64 - sc.col as i64) + }; Some(std::sync::Arc::new(Formula { dynamic: f.dynamic, ..Formula::from_expr(moved) })) }; if link { @@ -2203,6 +2207,39 @@ mod tests { assert_eq!(get(&mut s, "XFD2")["value"], json!(2.0)); } + #[test] + fn transposed_paste_turns_the_formula_with_the_cell_that_carries_it() { + // #2450: the values moved but the formula kept the offset it had in the source column, + // so it read the cell above instead of the cell to its left. + let mut s = Session::new(); + s.new_workbook(); + s.execute("cell.set", json!({"cell": "A3", "input": "2025-10-31"})).unwrap(); + s.execute("cell.set", json!({"cell": "A4", "input": "=A3+1"})).unwrap(); + s.execute("edit.copy", json!({"range": "A3:A4"})).unwrap(); + s.execute("edit.pasteSpecial", json!({"what": "all", "transpose": true, "at": "C3"})).unwrap(); + let get = |s: &mut Session, a: &str| s.execute("cell.get", json!({"cell": a})).unwrap(); + let date = get(&mut s, "C3")["value"].as_f64().expect("the date pastes as its serial"); + assert_eq!(date, get(&mut s, "A3")["value"].as_f64().unwrap()); + assert_eq!(get(&mut s, "D3")["formula"], "=C3+1", "the formula reads the cell to its left, as Excel's does"); + assert_eq!(get(&mut s, "D3")["value"].as_f64().unwrap(), date + 1.0, "and shows the day after it"); + } + + #[test] + fn transposed_paste_turns_every_kind_of_reference_the_way_excel_does() { + // Observed from Excel 16: relative parts turn a quarter turn, a reference pinned with $ + // is left standing, and a whole column comes back as a range open to the sheet's edge. + let mut s = Session::new(); + s.new_workbook(); + s.execute("range.setValues", json!({"range": "A1", "values": [["=B1+1"], ["=$B$1"], ["=SUM(B1:C3)"], ["=SUM(B:D)"]]})).unwrap(); + s.execute("edit.copy", json!({"range": "A1:A4"})).unwrap(); + s.execute("edit.pasteSpecial", json!({"what": "all", "transpose": true, "at": "C10"})).unwrap(); + let formula = |s: &mut Session, a: &str| s.execute("cell.get", json!({"cell": a})).unwrap()["formula"].clone(); + assert_eq!(formula(&mut s, "C10"), "=C11+1"); + assert_eq!(formula(&mut s, "D10"), "=$B$1"); + assert_eq!(formula(&mut s, "E10"), "=SUM(C11:E12)"); + assert_eq!(formula(&mut s, "F10"), "=SUM($C11:$XFD13)"); + } + #[test] fn replace_case_insensitive() { assert_eq!(replace_ci("Apple apple APPLE", "apple", "pear"), "pear pear pear"); diff --git a/crates/formula/src/adjust.rs b/crates/formula/src/adjust.rs index 319474b4ef..04e1fd1cbf 100644 --- a/crates/formula/src/adjust.rs +++ b/crates/formula/src/adjust.rs @@ -1,7 +1,7 @@ //! Reference adjustment: copying formulas, inserting/deleting rows and columns, moving cells, //! renaming and deleting sheets. -use gridcraft_core::{CellError, MAX_COLS, MAX_ROWS, RangeRef}; +use gridcraft_core::{CellError, CellRef, MAX_COLS, MAX_ROWS, RangeRef}; use crate::ast::{Anchor, Expr, RefKind, Reference, SheetSel, clamp_anchor}; @@ -36,6 +36,66 @@ pub fn shift_relative_wrapping(e: Expr, dr: i64, dc: i64) -> Expr { }) } +/// Paste Special ▸ Transpose: the cell holding the formula moves from `src` to `dest`, so every +/// reference turns a quarter turn with it — its row offset becomes its column offset and the other +/// way round, `(r, c)` → `dest + (c − src.col, r − src.row)`. +/// +/// As Excel writes it out: a reference that pins a row or a column with `$` is left exactly as it +/// stands, a whole-row or whole-column reference comes back as a cell range whose open side runs +/// from the transposed far edge of the sheet, and a result that falls off the grid becomes `#REF!`. +pub fn transpose_relative(e: Expr, src: CellRef, dest: CellRef) -> Expr { + e.map(&mut |x| match x { + Expr::Ref(r) if !has_absolute(&r) => match transpose_ref(&r, src, dest) { + Some(r) => Expr::Ref(r), + None => Expr::Error(CellError::Ref), + }, + other => other, + }) +} + +/// Whether any end of the reference pins a row or a column with `$`. +fn has_absolute(r: &Reference) -> bool { + let abs = |a: &Anchor| a.row_abs || a.col_abs; + match &r.kind { + RefKind::Cell(a) => abs(a), + RefKind::Range(a, b) => abs(a) || abs(b), + RefKind::Rows(_, a0, _, a1) | RefKind::Cols(_, a0, _, a1) => *a0 || *a1, + } +} + +/// Where an end lands after the turn: its column drives the new row, its row the new column. +fn transpose_anchor(a: &Anchor, src: CellRef, dest: CellRef) -> Option<(u32, u32)> { + clamp_anchor(dest.row as i64 + a.col as i64 - src.col as i64, dest.col as i64 + a.row as i64 - src.row as i64) +} + +fn transpose_ref(r: &Reference, src: CellRef, dest: CellRef) -> Option { + let kind = match &r.kind { + RefKind::Cell(a) => { + let (row, col) = transpose_anchor(a, src, dest)?; + RefKind::Cell(Anchor { row, col, ..*a }) + } + RefKind::Range(a, b) => { + let (row, col) = transpose_anchor(a, src, dest)?; + let (row2, col2) = transpose_anchor(b, src, dest)?; + RefKind::Range(Anchor { row, col, ..*a }, Anchor { row: row2, col: col2, ..*b }) + } + // A whole row turns into a cell range: its rows become columns, while its open columns + // become rows pinned with `$` — from the transposed first column down to the last row. + RefKind::Rows(r0, _, r1, _) => { + let (row, col) = clamp_anchor(dest.row as i64 - src.col as i64, dest.col as i64 + *r0 as i64 - src.row as i64)?; + let (row2, col2) = clamp_anchor(MAX_ROWS as i64 - 1, dest.col as i64 + *r1 as i64 - src.row as i64)?; + RefKind::Range(Anchor { row, col, row_abs: true, col_abs: false }, Anchor { row: row2, col: col2, row_abs: true, col_abs: false }) + } + // A whole column likewise: its columns become rows, its open rows become columns up to XFD. + RefKind::Cols(c0, _, c1, _) => { + let (row, col) = clamp_anchor(dest.row as i64 + *c0 as i64 - src.col as i64, dest.col as i64 - src.row as i64)?; + let (row2, col2) = clamp_anchor(dest.row as i64 + *c1 as i64 - src.col as i64, MAX_COLS as i64 - 1)?; + RefKind::Range(Anchor { row, col, row_abs: false, col_abs: true }, Anchor { row: row2, col: col2, row_abs: false, col_abs: true }) + } + }; + Some(Reference { sheet: r.sheet.clone(), kind }) +} + /// Whether the formula has a relative (no `$`) row or column anywhere. pub fn has_relative_refs(e: &Expr) -> bool { e.references().iter().any(|r| match r.kind { diff --git a/crates/formula/src/tests.rs b/crates/formula/src/tests.rs index a7506aa4bc..f1fa9d5060 100644 --- a/crates/formula/src/tests.rs +++ b/crates/formula/src/tests.rs @@ -1,5 +1,5 @@ use super::*; -use crate::adjust::{Axis, Edit, adjust, rename_sheet, shift_relative}; +use crate::adjust::{Axis, Edit, adjust, rename_sheet, shift_relative, transpose_relative}; fn rt(src: &str) -> String { print(&parse(src).unwrap_or_else(|e| panic!("{src}: {e}"))) @@ -165,6 +165,27 @@ fn copy_shift() { assert_eq!(print(&shift_relative(e, 5, 1)), "SUM(B:B)"); } +#[test] +fn copy_transpose() { + let at = gridcraft_core::CellRef::new; + // The row of each reference drives its new column and the other way round (Excel, observed: + // A1 → F6 carrying =B1+1 comes out as =F7+1). + let e = parse("B1+SUM(B1:C3)+Sheet2!A1").unwrap(); + assert_eq!(print(&transpose_relative(e, at(0, 0), at(5, 5))), "F7+SUM(F7:H8)+Sheet2!F6"); + // The turn is around the two positions of the formula's cell, not around A1. + let e = parse("G3+SUM(1:2)").unwrap(); + assert_eq!(print(&transpose_relative(e, at(1, 2), at(9, 5))), "G14+SUM(E$8:F$1048576)"); + // A reference pinned with `$` is left exactly as it stands. + let e = parse("$B$1+B$1+$B1+SUM($B$1:$C$3)").unwrap(); + assert_eq!(print(&transpose_relative(e, at(0, 0), at(5, 5))), "$B$1+B$1+$B1+SUM($B$1:$C$3)"); + // Whole rows and columns come back as a cell range open to the sheet's edge. + let e = parse("SUM(1:2)+SUM(B:D)").unwrap(); + assert_eq!(print(&transpose_relative(e, at(0, 0), at(5, 5))), "SUM(F$6:G$1048576)+SUM($F7:$XFD9)"); + // Off the grid is #REF!, like a copy that runs past the edge. + let e = parse("A16384+B1").unwrap(); + assert_eq!(print(&transpose_relative(e, at(0, 0), at(5, 5))), "#REF!+F7"); +} + #[test] fn insert_delete() { let ins = Edit::Insert { axis: Axis::Rows, at: 2, count: 2 }; diff --git a/docs/ui-parity.md b/docs/ui-parity.md index ed875cc8ef..9cd49ba65b 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-25 · **Change:** minor (AutoSum over a selected row puts its total to the right) · **Target:** Microsoft Excel (Microsoft 365), Excel for Mac 16.113.4 +> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-10-26 · **Change:** minor (Paste Special ▸ Transpose turns a formula's references with the cell that carries it, as Excel does) · **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 @@ -186,6 +186,7 @@ scrollbar bugs 2–4 · pixel/feel pass against observed Excel 7–12. | Date | Change | Summary | |---|---|---| +| 2026-10-26 | minor | Paste Special ▸ Transpose turns a formula's references with the cell that carries it, as Excel's does (#2450): the row offset becomes the column offset and the other way round, so `=A3+1` copied from A3:A4 and pasted at C3 lands as `=C3+1` and shows the day after the cell to its left, instead of keeping the offset it had in the column and reading the cell above. A reference pinned with `$` is left exactly as Excel leaves it, a whole row or column comes back as a cell range open to the sheet's edge, and one that lands off the grid is `#REF!` | | 2026-10-25 | minor | AutoSum (Alt+=, Home › AutoSum) over a selected row puts its total to the right of the row, or in its last cell when that is empty, as in Excel; it wrote a one-cell total under each cell. A selection's empty last column takes each row's total and its empty last row each column's, with the block's total in the corner when both are empty | | 2026-10-25 | minor | Paste Name lays out only the names in view, so a workbook with thousands of names opens it at once; the arrow keys still scroll the chosen name into view. Go To matches a `Sheet2!Name` reference and hides a workbook name behind the active sheet's own name in any case and script (`Größe` = `GRÖSSE`), as formulas do. The two Page Layout view rows are one; the 0.7 in side margin used when Align with Page Margins is off is marked unverified | | 2026-10-24 | minor | Go To lists the named ranges on every sheet, as Excel's does ("The Go to popup window shows named ranges on every worksheet in your workbook"): a name scoped to another sheet appears as `Sheet2!Name`, and hidden names, constants and formulas are left out. It keeps the references entered (newest first, ten at most), and a double-click on an entry goes there. The Reference box and `edit.goTo` take several names or references separated by commas (`Price, Type`, `B14:C22,F19:G30,H21:H29`) and select them all; `edit.goTo {list: true}` returns the list | From a53483874e94e62e4272b160909d58fe1dd01759 Mon Sep 17 00:00:00 2001 From: zyzabruh Date: Mon, 26 Oct 2026 01:40:53 +0100 Subject: [PATCH 13/21] Formula: document transpose_ref's turn and its #REF! contract (review #2606) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit CodeRabbit's only finding on the pull request was docstring coverage on the touched functions; this is the one that carried an undocumented contract — `None` means an end left the sheet and the caller turns it into `#REF!`. 🤖 Generated with Codebuff Co-Authored-By: Codebuff --- crates/formula/src/adjust.rs | 2 ++ 1 file changed, 2 insertions(+) diff --git a/crates/formula/src/adjust.rs b/crates/formula/src/adjust.rs index 04e1fd1cbf..2b3739bb2f 100644 --- a/crates/formula/src/adjust.rs +++ b/crates/formula/src/adjust.rs @@ -68,6 +68,8 @@ fn transpose_anchor(a: &Anchor, src: CellRef, dest: CellRef) -> Option<(u32, u32 clamp_anchor(dest.row as i64 + a.col as i64 - src.col as i64, dest.col as i64 + a.row as i64 - src.row as i64) } +/// Turns one reference with `src` → `dest`: `None` when an end falls outside the sheet, which +/// the caller turns into `#REF!`. fn transpose_ref(r: &Reference, src: CellRef, dest: CellRef) -> Option { let kind = match &r.kind { RefKind::Cell(a) => { From 921cdc974f12b22bc5001e4fd2d2f1ee08051e7d Mon Sep 17 00:00:00 2001 From: kezmdor <15539254+kezmdor@users.noreply.github.com> Date: Sat, 31 Oct 2026 11:59:24 +0100 Subject: [PATCH 14/21] AutoSum tests join the `it` test binary, as main's UI tests do The module uses the shared harness (`common::builder`, `common::app`), so it runs with the pinned font set like the other UI tests. Co-Authored-By: Claude Opus 5.5 --- crates/ui-egui/tests/{ => it}/autosum_edit.rs | 14 +++----------- crates/ui-egui/tests/it/main.rs | 1 + 2 files changed, 4 insertions(+), 11 deletions(-) rename crates/ui-egui/tests/{ => it}/autosum_edit.rs (93%) diff --git a/crates/ui-egui/tests/autosum_edit.rs b/crates/ui-egui/tests/it/autosum_edit.rs similarity index 93% rename from crates/ui-egui/tests/autosum_edit.rs rename to crates/ui-egui/tests/it/autosum_edit.rs index 9f76bf8a8d..5440fffe02 100644 --- a/crates/ui-egui/tests/autosum_edit.rs +++ b/crates/ui-egui/tests/it/autosum_edit.rs @@ -4,10 +4,10 @@ use egui::{Event, Key, Modifiers, PointerButton, Pos2}; use gridcraft_engine::core::{CellRef, Value}; use gridcraft_engine::{Mode, Session}; -use gridcraft_ui_egui::{SheetApp, grid::Geo}; +use gridcraft_ui_egui::grid::Geo; use serde_json::json; -type Harness = egui_kittest::Harness<'static, SheetApp>; +use crate::common::Harness; /// 1, 2, 3 in A1:A3 and `selected` selected. fn harness(selected: &str) -> Harness { @@ -20,15 +20,7 @@ fn harness_at(first: &str, selected: &str) -> Harness { session.new_workbook(); session.execute("range.setValues", json!({"range": first, "values": [[1], [2], [3]]})).unwrap(); session.execute("selection.set", json!({"range": selected})).unwrap(); - let mut h = egui_kittest::Harness::builder().with_size(egui::vec2(1200.0, 800.0)).build_ui_state( - |ui, app: &mut SheetApp| { - app.logic(ui.ctx()); - app.ui(ui); - }, - SheetApp::new(session, Default::default()), - ); - h.run_steps(4); - h + crate::common::harness_with(crate::common::builder().with_size(egui::vec2(1200.0, 800.0)), crate::common::app(session), 4) } /// The AutoSum button: a menu-style run. diff --git a/crates/ui-egui/tests/it/main.rs b/crates/ui-egui/tests/it/main.rs index 302bc9c49c..d37c238250 100644 --- a/crates/ui-egui/tests/it/main.rs +++ b/crates/ui-egui/tests/it/main.rs @@ -10,6 +10,7 @@ mod accounting_fill; mod advanced_filter; mod argument_names; mod autosave_persist; +mod autosum_edit; mod borders; mod cell_editor_caret; mod cell_pictures; From af4f17184c0f5e0891d5dd51e1716f3d0447a498 Mon Sep 17 00:00:00 2001 From: kezmdor <15539254+kezmdor@users.noreply.github.com> Date: Sat, 31 Oct 2026 12:20:56 +0100 Subject: [PATCH 15/21] Formula entry: `+` before a time stays text, as in Excel Checked by hand in Excel for the web (English (United States) regional format): `+1:30` stays text, while `-1:30` is the formula `=-1:30` (rows 1 to 30), `+1/30` and `-1/30` are formulas and `1:30` is a time. `starts_formula` now leaves a `+` followed by a time to the usual value parsing, which keeps it as text. Raised by @iluebbe in #2023. Co-Authored-By: Claude Opus 5.5 --- crates/core/src/parse.rs | 15 ++++++++++----- crates/engine/src/tests.rs | 21 ++++++++++++++++----- 2 files changed, 26 insertions(+), 10 deletions(-) diff --git a/crates/core/src/parse.rs b/crates/core/src/parse.rs index 504a92d01f..ffad72c849 100644 --- a/crates/core/src/parse.rs +++ b/crates/core/src/parse.rs @@ -52,9 +52,14 @@ pub fn parse_number_text_in(s: &str, sys: DateSystem) -> Option { /// Whether typed cell input is meant as a formula: it starts with `=`, or, as Lotus 1-2-3 users /// type it, with `+` or `-` and isn't a number on its own (`+5+4` is `=+5+4`, `-5` the number -5, /// a lone `+` or `-` text). A leading space or apostrophe makes the input text. Callers parse -/// the formula; a `+` or `-` entry that doesn't parse (`--`) stays text, as in Excel. +/// the formula; a `+` or `-` entry that doesn't parse (`--`) stays text, as in Excel. So does `+` +/// before a time (`+1:30`), while `-1:30` is a formula (rows 1 to 30), as Excel for the web does. pub fn starts_formula(input: &str) -> bool { - input.starts_with('=') || (input.len() > 1 && input.starts_with(['+', '-']) && parse_number_text(input).is_none()) + input.starts_with('=') + || (input.len() > 1 + && input.starts_with(['+', '-']) + && parse_number_text(input).is_none() + && !input.strip_prefix('+').is_some_and(|time| time.contains(':') && parse_number_text(time).is_some())) } /// Text that Excel's "Number Stored as Text" check flags: it would be a number if typed (signs, @@ -588,12 +593,12 @@ mod tests { #[test] fn a_leading_sign_starts_a_formula_unless_the_entry_is_a_number() { // #2023: Excel reads `+5+4` as `=+5+4`, as Lotus 1-2-3 did. - for s in ["=1", "=", "+5+4", "-5+4", "--5", "+-5", "-.5*2", "-3/4", "+A1", "-SUM(1,2)", "+(5+4)", "-abc", "--"] { + for s in ["=1", "=", "+5+4", "-5+4", "--5", "+-5", "-.5*2", "-3/4", "+A1", "-SUM(1,2)", "+(5+4)", "-abc", "--", "-1:30", "+1/30", "-1/30"] { assert!(starts_formula(s), "{s}"); } // Signed numbers, percentages and currency stay numbers; a lone sign, a leading space or - // apostrophe and other text stay text. - for s in ["+5", "-5", "+5%", "-$5", "-1e3", "+.5", "-1,234.5", "+", "-", " +5+4", "'+5+4", "5+4", "", "a-b"] { + // apostrophe, `+` before a time and other text stay text. + for s in ["+5", "-5", "+5%", "-$5", "-1e3", "+.5", "-1,234.5", "+", "-", " +5+4", "'+5+4", "5+4", "", "a-b", "+1:30", "+0:30:15"] { assert!(!starts_formula(s), "{s}"); } } diff --git a/crates/engine/src/tests.rs b/crates/engine/src/tests.rs index 20c434d920..5239762d88 100644 --- a/crates/engine/src/tests.rs +++ b/crates/engine/src/tests.rs @@ -251,9 +251,16 @@ fn a_leading_plus_or_minus_starts_a_formula() { // #2023: like Excel (and Lotus 1-2-3 before it), typing `+5+4` enters the formula `=+5+4`. let mut s = s(); let input = |s: &Session, a: &str| s.doc().unwrap().wb.active().unwrap().cell(CellRef::parse(a).unwrap()).map(|c| c.input_text()); - for (cell, typed, value) in - [("A1", "+5+4", 9.0), ("A2", "-5+4", -1.0), ("A3", "--5", 5.0), ("A4", "-3/4", -0.75), ("A5", "+A1*2", 18.0), ("A6", "-(A1)", -9.0)] - { + for (cell, typed, value) in [ + ("A1", "+5+4", 9.0), + ("A2", "-5+4", -1.0), + ("A3", "--5", 5.0), + ("A4", "-3/4", -0.75), + ("A5", "+A1*2", 18.0), + ("A6", "-(A1)", -9.0), + ("A7", "+1/30", 1.0 / 30.0), + ("A8", "-1/30", -1.0 / 30.0), + ] { s.execute("cell.set", json!({"cell": cell, "input": typed})).unwrap_or_else(|e| panic!("{typed}: {e}")); assert_eq!(input(&s, cell), Some(format!("={typed}")), "{typed}"); assert_eq!(v(&s, cell), Value::Number(value), "{typed}"); @@ -281,6 +288,7 @@ fn a_leading_plus_or_minus_starts_a_formula() { ("'-abc", "'-abc"), ("--", "--"), ("+49 170 1234567", "+49 170 1234567"), + ("+1:30", "+1:30"), ] { s.execute("cell.set", json!({"cell": "B2", "input": typed})).unwrap(); let before = v(&s, "B2"); @@ -294,16 +302,19 @@ fn a_leading_plus_or_minus_starts_a_formula() { } // As observed in Excel for the web, an entry that doesn't read as a formula stays text, and // one that does but names nothing known is #NAME?. Only `=` entries are refused. - for typed in ["--", "-----", "+5+", "+49 170 1234567"] { + for typed in ["--", "-----", "+5+", "+49 170 1234567", "+1:30"] { s.execute("cell.set", json!({"cell": "C1", "input": typed})).unwrap_or_else(|e| panic!("{typed}: {e}")); assert_eq!(v(&s, "C1"), Value::text(typed), "{typed}"); assert_eq!(input(&s, "C1").as_deref(), Some(typed), "{typed}"); } s.execute("cell.set", json!({"cell": "C2", "input": "- item"})).unwrap(); assert_eq!(v(&s, "C2"), Value::Error(gridcraft_core::CellError::Name)); + // Excel for the web keeps `+1:30` as text (above) but reads `-1:30` as a formula (rows 1 to 30). + s.execute("cell.set", json!({"cell": "C40", "input": "-1:30"})).unwrap(); + assert_eq!(input(&s, "C40").as_deref(), Some("=-1:30")); let e = s.execute("cell.set", json!({"cell": "C1", "input": "=--"})).unwrap_err().to_string(); assert!(e.contains("problem with this formula"), "{e}"); - assert_eq!(v(&s, "C1"), Value::text("+49 170 1234567"), "a refused entry keeps the cell"); + assert_eq!(v(&s, "C1"), Value::text("+1:30"), "a refused entry keeps the cell"); // Pasted or split by Text to Columns, the same rule applies. s.execute("edit.paste", json!({"at": "D1", "text": "--\t-5+4\n"})).unwrap(); assert_eq!(v(&s, "D1"), Value::text("--")); From def4067247e25191363eca7d2c325c8c39c5f9b6 Mon Sep 17 00:00:00 2001 From: kezmdor <15539254+kezmdor@users.noreply.github.com> Date: Sat, 7 Nov 2026 14:22:50 +0100 Subject: [PATCH 16/21] AutoSum: main's Function Library test expects the proposal in the editor MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Formulas › AutoSum and its Count Numbers item on one cell now leave `=SUM(A1:A3)` / `=COUNT(B1:B3)` in the editor until Enter, as in Excel (#1834); the test checks the proposal, presses Enter, then the cell. --- crates/ui-egui/tests/it/function_library.rs | 7 +++++++ 1 file changed, 7 insertions(+) diff --git a/crates/ui-egui/tests/it/function_library.rs b/crates/ui-egui/tests/it/function_library.rs index a1a7a1a37e..3cb132adc3 100644 --- a/crates/ui-egui/tests/it/function_library.rs +++ b/crates/ui-egui/tests/it/function_library.rs @@ -136,6 +136,10 @@ fn autosum_runs_sum_and_its_arrow_opens_the_shared_menu() { } h.run_steps(2); click(&mut h, "AutoSum"); + // One cell: the proposed formula waits in the editor for Enter, as in Excel (#1834). + assert_eq!(editor_text(&h).as_deref(), Some("=SUM(A1:A3)")); + h.key_press(Key::Enter); + h.run_steps(2); assert_eq!(input(&h, "A4"), "=SUM(A1:A3)"); h.state_mut().session.execute("selection.set", json!({"cell": "B4"})).unwrap(); click(&mut h, "AutoSum options"); @@ -143,6 +147,9 @@ fn autosum_runs_sum_and_its_arrow_opens_the_shared_menu() { h.get_by_label(item); } click(&mut h, "Count Numbers"); + assert_eq!(editor_text(&h).as_deref(), Some("=COUNT(B1:B3)")); + h.key_press(Key::Enter); + h.run_steps(2); assert_eq!(input(&h, "B4"), "=COUNT(B1:B3)"); click(&mut h, "AutoSum options"); click(&mut h, "More Functions…"); From 2829120d4dd7ef54db7aa5afa6c44d5e1b464b32 Mon Sep 17 00:00:00 2001 From: kezmdor <15539254+kezmdor@users.noreply.github.com> Date: Sat, 7 Nov 2026 14:24:10 +0100 Subject: [PATCH 17/21] Recently Used: a sign before a space starts a formula too main's `functions_in_formula` test expected `- SUM(1)` not to be a formula. With #2023's rule, which `is_formula_input` now uses, it is one, as Excel for the web enters `- remember this` as `=- remember this`. --- crates/engine/src/recent.rs | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/crates/engine/src/recent.rs b/crates/engine/src/recent.rs index 0a1bba2dc2..2bd8a375cb 100644 --- a/crates/engine/src/recent.rs +++ b/crates/engine/src/recent.rs @@ -154,7 +154,9 @@ mod tests { assert_eq!(functions_in_formula("+SUM(1)"), ["SUM"]); assert_eq!(functions_in_formula("-ABS(A1)"), ["ABS"]); assert!(functions_in_formula("-5").is_empty() && functions_in_formula("+1e3").is_empty(), "numbers"); - assert!(functions_in_formula("+").is_empty() && functions_in_formula("- SUM(1)").is_empty(), "not formulas"); + assert!(functions_in_formula("+").is_empty() && functions_in_formula("--").is_empty(), "not formulas"); + // A sign before a space still starts a formula, as Excel takes `- SUM(1)` (#2023). + assert_eq!(functions_in_formula("- SUM(1)"), ["SUM"]); } #[test] From 8aa01a775060c3a9d8d92d6cb8f6e2be46d99230 Mon Sep 17 00:00:00 2001 From: Gert Pellin Date: Sun, 15 Nov 2026 01:50:53 +0100 Subject: [PATCH 18/21] Selection: a merged active cell is selected whole on open and on a sheet's first visit (#1348) A click goes through selection.set, which takes merged cells whole, but the selection a workbook opens with (built from the sheet's saved active cell) and the default A1 a sheet starts at on its first visit were bare cells. With A1:AG1 merged, opening the file outlined A1 alone. Both now expand merges before the selection is shown. A sheet's remembered selection is left as it was, so only the first visit is expanded. --- crates/engine/src/cmd/edit/selection.rs | 7 ++++ crates/engine/src/lib.rs | 6 +++- crates/engine/src/tests.rs | 43 +++++++++++++++++++++++++ 3 files changed, 55 insertions(+), 1 deletion(-) diff --git a/crates/engine/src/cmd/edit/selection.rs b/crates/engine/src/cmd/edit/selection.rs index e6037c09d3..8c9ed676a0 100644 --- a/crates/engine/src/cmd/edit/selection.rs +++ b/crates/engine/src/cmd/edit/selection.rs @@ -52,6 +52,13 @@ impl crate::DocState { // View state: set in place, so the workbook is neither copied nor made dirty. self.wb.set_active_sheet(i); self.selection = self.sheet_selections.get(i).cloned().unwrap_or_default(); + // A sheet's first visit starts at A1, which may be part of a merged cell: take it whole, + // as a click would (#1348). A selection the sheet remembers comes back as it was. + if self.selection == crate::Selection::default() + && let Some(sh) = self.wb.sheet(i) + { + self.selection.expand_merges(sh); + } } } diff --git a/crates/engine/src/lib.rs b/crates/engine/src/lib.rs index e068f7a1ed..7ecfa702b1 100644 --- a/crates/engine/src/lib.rs +++ b/crates/engine/src/lib.rs @@ -340,7 +340,11 @@ impl DocState { wb.refresh_equations(); let scripts_trusted = !cmd::extra::has_scripts(&wb); let wb = Arc::new(wb); - let sel = Selection::at(wb.active().map(|s| s.view_active).unwrap_or_default()); + let mut sel = Selection::at(wb.active().map(|s| s.view_active).unwrap_or_default()); + // A merged active cell is selected whole, as a click on it selects it (#1348). + if let Some(sh) = wb.active() { + sel.expand_merges(sh); + } DocState { saved: wb.clone(), wb, diff --git a/crates/engine/src/tests.rs b/crates/engine/src/tests.rs index f000eb9fe1..eeb7b63933 100644 --- a/crates/engine/src/tests.rs +++ b/crates/engine/src/tests.rs @@ -6728,3 +6728,46 @@ fn history_charges_the_storage_of_empty_comment_replies() { // 500 replies of no text are still 500 elements. assert!(crate::sheet_text_bytes(&sheet) >= 500 * std::mem::size_of::<(String, String)>()); } + +/// #1348: the selection a workbook opens with, and the one a sheet gets on its first visit, take +/// a merged active cell whole, as a click on it does: a merge at A1 and one elsewhere. A +/// selection the sheet remembers comes back as it was, even inside a merged cell. +#[test] +fn opening_and_switching_sheets_select_a_merged_active_cell_whole() { + let mut wb = gridcraft_model::Workbook::new(); + let sh = wb.sheet_mut(0).unwrap(); + sh.set_value(CellRef::new(0, 0), Value::text("Timesheet")); + sh.merges.push(gridcraft_core::RangeRef::parse("A1:AG1").unwrap()); + sh.merges.push(gridcraft_core::RangeRef::parse("C5:E6").unwrap()); + sh.view_active = CellRef::parse("C5").unwrap(); + let mut second = gridcraft_model::Sheet::new("Sheet2"); + second.merges.push(gridcraft_core::RangeRef::parse("A1:C2").unwrap()); + wb.sheets.push(std::sync::Arc::new(second)); + wb.sheets.push(std::sync::Arc::new(gridcraft_model::Sheet::new("Sheet3"))); + let bytes = gridcraft_xlsx::write_xlsx(&wb).unwrap(); + let sel = |s: &Session| { + let sel = &s.doc().unwrap().selection; + (sel.a1(), sel.active.a1()) + }; + let pair = |a: &str, b: &str| (a.to_string(), b.to_string()); + + let mut s = Session::new(); + s.execute("file.open", json!({"name": "timesheet.xlsx", "base64": crate::io::base64_encode(&bytes)})).unwrap(); + assert_eq!(sel(&s), pair("C5:E6", "C5"), "on open, a merge away from A1"); + + s.execute("sheet.activate", json!({"sheet": "Sheet2"})).unwrap(); + assert_eq!(sel(&s), pair("A1:C2", "A1"), "first visit of a sheet, a merge at A1"); + s.execute("sheet.activate", json!({"sheet": "Sheet3"})).unwrap(); + assert_eq!(sel(&s), pair("A1", "A1"), "an unmerged A1 stays a single cell"); + + // A remembered selection is not expanded again: set one inside Sheet2's merge directly. + s.execute("sheet.activate", json!({"sheet": "Sheet2"})).unwrap(); + s.doc_mut().unwrap().selection = crate::Selection::at(CellRef::parse("B2").unwrap()); + s.execute("sheet.activate", json!({"sheet": "Sheet1"})).unwrap(); + assert_eq!(sel(&s), pair("C5:E6", "C5"), "Sheet1's remembered selection"); + s.execute("selection.set", json!({"cell": "B3"})).unwrap(); + s.execute("sheet.activate", json!({"sheet": "Sheet2"})).unwrap(); + assert_eq!(sel(&s), pair("B2", "B2"), "a remembered selection comes back as it was"); + s.execute("sheet.activate", json!({"sheet": "Sheet1"})).unwrap(); + assert_eq!(sel(&s), pair("B3", "B3"), "a remembered selection comes back as it was"); +} From dec0e1a6c088416742c7592230cf733927a3b847 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Fri, 20 Nov 2026 17:33:46 -0800 Subject: [PATCH 19/21] Deps: update zip past GHSA-m665-v7pm-7grj The workspace required zip 3, which resolved to zip 3.0.0 for gridcraft-xlsx, gridcraft-cli and gridcraft-engine's tests. zip 3.0.0 is affected by GHSA-m665-v7pm-7grj (parser differential through dual local and central headers; affected through 9.0.4, patched in 9.0.5). The requirement is now 9.0.5, which resolves to the zip 9.1.0 that craft-update and craft-zip already use, so one zip remains in the lock file and arbitrary and derive_arbitrary drop out. zip 9 returns entry names as a Result, decoding names not flagged UTF-8 as CP437. The package checker in gridcraft-cli lists an entry whose name does not decode under its raw bytes made lossy, so it is still checked and reported. Tests unwrap the decoded names. --- Cargo.lock | 47 +++---------------- Cargo.toml | 2 +- apps/gridcraft-cli/src/check/package.rs | 8 +++- apps/gridcraft-cli/src/check/tests.rs | 2 +- crates/engine/src/tests/controls.rs | 2 +- crates/engine/src/tests/python_files.rs | 4 +- .../engine/tests/it/chart_workbook_names.rs | 2 +- crates/xlsx/src/tests/equation_tests.rs | 2 +- crates/xlsx/src/tests/fixtures.rs | 2 +- crates/xlsx/src/tests/malformed.rs | 2 +- crates/xlsx/src/tests/note_box.rs | 2 +- crates/xlsx/src/tests/passthrough_tests.rs | 4 +- crates/xlsx/src/tests/pivot_tests.rs | 2 +- crates/xlsx/src/tests/roundtrip.rs | 4 +- crates/xlsx/src/tests/shared_media.rs | 2 +- crates/xlsx/src/tests/trendline_roundtrip.rs | 2 +- crates/xlsx/src/tests/zip_order.rs | 2 +- 17 files changed, 32 insertions(+), 59 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index 2903e7010c..218eba60a7 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -195,15 +195,6 @@ version = "1.0.104" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "330a5ed07fa54e4702c9d6c4174f74427fc0ef6e214bbd677ae50a5099946470" -[[package]] -name = "arbitrary" -version = "1.5.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "3bc62ac97cc33321f50863d514c3bc38a453947a8f9e781137e47c7401020aed" -dependencies = [ - "derive_arbitrary", -] - [[package]] name = "arboard" version = "3.7.0" @@ -1150,7 +1141,7 @@ dependencies = [ "verifysign", "winreg", "winsafe", - "zip 9.1.0", + "zip", ] [[package]] @@ -1253,7 +1244,7 @@ source = "git+https://github.com/storytold/craft-libs?rev=010702ee9b030844c85293 dependencies = [ "flate2", "thiserror 2.0.21", - "zip 9.1.0", + "zip", ] [[package]] @@ -1263,7 +1254,7 @@ source = "git+https://github.com/storytold/craft-libs?rev=a20dfd1623709b0bd98301 dependencies = [ "flate2", "thiserror 2.0.21", - "zip 9.1.0", + "zip", ] [[package]] @@ -1391,17 +1382,6 @@ version = "0.5.9" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "9e9de72ce2ad1f90dc62fa25f0f430ef85eb4b0d8fa0be4f30373bc40a21d28e" -[[package]] -name = "derive_arbitrary" -version = "1.5.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "1b034bd7d5f032402a2479444dcc6f74e36a03f31854d41680fb240ef682a1ac" -dependencies = [ - "proc-macro2", - "quote", - "syn 3.0.6", -] - [[package]] name = "dify" version = "0.8.0" @@ -2326,7 +2306,7 @@ dependencies = [ "log", "quick-xml 0.41.0", "serde_json", - "zip 3.0.0", + "zip", ] [[package]] @@ -2363,7 +2343,7 @@ dependencies = [ "thiserror 2.0.21", "unicode-segmentation", "web-time", - "zip 3.0.0", + "zip", ] [[package]] @@ -2514,7 +2494,7 @@ dependencies = [ "quick-xml 0.41.0", "sha2 0.11.1", "thiserror 2.0.21", - "zip 3.0.0", + "zip", ] [[package]] @@ -7240,20 +7220,6 @@ dependencies = [ "syn 3.0.6", ] -[[package]] -name = "zip" -version = "3.0.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "12598812502ed0105f607f941c386f43d441e00148fce9dec3ca5ffb0bde9308" -dependencies = [ - "arbitrary", - "crc32fast", - "flate2", - "indexmap", - "memchr", - "zopfli", -] - [[package]] name = "zip" version = "9.1.0" @@ -7268,6 +7234,7 @@ dependencies = [ "nix", "typed-path", "windows-sys 0.61.2", + "zopfli", ] [[package]] diff --git a/Cargo.toml b/Cargo.toml index cca4830c6a..901b57c89f 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -65,7 +65,7 @@ web-time = "1.1.0" rayon = "1" regex = { version = "1", default-features = false, features = ["std", "unicode", "perf"] } quick-xml = "0.41" -zip = { version = "3", default-features = false, features = ["deflate"] } +zip = { version = "9.0.5", default-features = false, features = ["deflate"] } sha2 = { version = "0.11", default-features = false } image = { version = "0.25", default-features = false, features = ["png", "jpeg"] } diff --git a/apps/gridcraft-cli/src/check/package.rs b/apps/gridcraft-cli/src/check/package.rs index c0def70374..45c1c7cae5 100644 --- a/apps/gridcraft-cli/src/check/package.rs +++ b/apps/gridcraft-cli/src/check/package.rs @@ -111,7 +111,13 @@ fn resolve_target(source_dir: &str, target: &str) -> String { type Zip<'a> = zip::ZipArchive>; fn zip_names(zip: &mut Zip<'_>) -> Vec { - (0..zip.len().min(MAX_ENTRIES)).filter_map(|i| zip.by_index_raw(i).ok().filter(|f| !f.is_dir()).map(|f| f.name().to_string())).collect() + (0..zip.len().min(MAX_ENTRIES)).filter_map(|i| zip.by_index_raw(i).ok().filter(|f| !f.is_dir()).map(|f| entry_name(&f))).collect() +} + +/// An entry's name: UTF-8, or CP437 when the entry isn't flagged UTF-8. A name that doesn't decode +/// is listed with its raw bytes made lossy, so the entry is still checked and reported. +fn entry_name(f: &zip::read::ZipFile<'_, R>) -> String { + f.name().map(|n| n.into_owned()).unwrap_or_else(|_| String::from_utf8_lossy(f.name_raw()).into_owned()) } fn read_zip_part(zip: &mut Zip<'_>, name: &str) -> Result, String> { diff --git a/apps/gridcraft-cli/src/check/tests.rs b/apps/gridcraft-cli/src/check/tests.rs index d85cb3a3ad..054e158f3d 100644 --- a/apps/gridcraft-cli/src/check/tests.rs +++ b/apps/gridcraft-cli/src/check/tests.rs @@ -344,7 +344,7 @@ fn with_rels(bytes: &[u8], rels: &[(&str, &str)], parts: &[(&str, &str)]) -> Vec let mut pending: Vec<(&str, &str)> = rels.to_vec(); for i in 0..src.len() { let mut f = src.by_index(i).unwrap(); - let name = f.name().to_string(); + let name = f.name().unwrap().to_string(); let mut body = String::new(); f.read_to_string(&mut body).unwrap(); if let Some(at) = pending.iter().position(|(r, _)| *r == name) { diff --git a/crates/engine/src/tests/controls.rs b/crates/engine/src/tests/controls.rs index cb86727fad..ddf9faee44 100644 --- a/crates/engine/src/tests/controls.rs +++ b/crates/engine/src/tests/controls.rs @@ -531,7 +531,7 @@ fn edit_parts(bytes: &[u8], mut edit: impl FnMut(&str, String) -> String) -> Vec let mut out = zip::ZipWriter::new(Cursor::new(Vec::new())); for i in 0..zip.len() { let mut part = zip.by_index(i).unwrap(); - let name = part.name().to_string(); + let name = part.name().unwrap().to_string(); let mut data = Vec::new(); part.read_to_end(&mut data).unwrap(); let data = match String::from_utf8(data) { diff --git a/crates/engine/src/tests/python_files.rs b/crates/engine/src/tests/python_files.rs index cad3f87456..459851be5b 100644 --- a/crates/engine/src/tests/python_files.rs +++ b/crates/engine/src/tests/python_files.rs @@ -56,7 +56,7 @@ fn with_parts(bytes: &[u8], edit: impl Fn(&str, &str) -> String, add: &[(&str, & let mut out = zip::ZipWriter::new(std::io::Cursor::new(Vec::new())); for i in 0..z.len() { let mut f = z.by_index(i).unwrap(); - let name = f.name().to_string(); + let name = f.name().unwrap().to_string(); let mut data = Vec::new(); f.read_to_end(&mut data).unwrap(); if let Ok(text) = std::str::from_utf8(&data) { @@ -250,7 +250,7 @@ fn with_damaged_part(bytes: &[u8], name: &str, marker: &str) -> Vec { let mut out = zip::ZipWriter::new(std::io::Cursor::new(Vec::new())); for i in 0..z.len() { let mut f = z.by_index(i).unwrap(); - let entry = f.name().to_string(); + let entry = f.name().unwrap().to_string(); let mut data = Vec::new(); f.read_to_end(&mut data).unwrap(); let options = zip::write::SimpleFileOptions::default(); diff --git a/crates/engine/tests/it/chart_workbook_names.rs b/crates/engine/tests/it/chart_workbook_names.rs index 0ac156b629..c86883a354 100644 --- a/crates/engine/tests/it/chart_workbook_names.rs +++ b/crates/engine/tests/it/chart_workbook_names.rs @@ -60,7 +60,7 @@ fn edit_chart(bytes: &[u8], edit: impl Fn(String) -> String) -> Vec { let mut out = zip::ZipWriter::new(std::io::Cursor::new(Vec::new())); for i in 0..z.len() { let mut f = z.by_index(i).unwrap(); - let name = f.name().to_string(); + let name = f.name().unwrap().to_string(); let mut data = Vec::new(); f.read_to_end(&mut data).unwrap(); if name == "xl/charts/chart1.xml" { diff --git a/crates/xlsx/src/tests/equation_tests.rs b/crates/xlsx/src/tests/equation_tests.rs index 983f3edfc8..f50ce89564 100644 --- a/crates/xlsx/src/tests/equation_tests.rs +++ b/crates/xlsx/src/tests/equation_tests.rs @@ -42,7 +42,7 @@ fn unzip(bytes: &[u8]) -> BTreeMap> { let mut f = z.by_index(i).unwrap(); let mut b = Vec::new(); f.read_to_end(&mut b).unwrap(); - m.insert(f.name().to_string(), b); + m.insert(f.name().unwrap().to_string(), b); } m } diff --git a/crates/xlsx/src/tests/fixtures.rs b/crates/xlsx/src/tests/fixtures.rs index 46a953bc1d..72b6e68ddb 100644 --- a/crates/xlsx/src/tests/fixtures.rs +++ b/crates/xlsx/src/tests/fixtures.rs @@ -445,7 +445,7 @@ fn drawing_with_picture_and_chart() { let mut f = z.by_index(i).unwrap(); let mut d = vec![]; std::io::Read::read_to_end(&mut f, &mut d).unwrap(); - parts.push((f.name().to_string(), d)); + parts.push((f.name().unwrap().to_string(), d)); } parts.push(("xl/media/image1.png".into(), png.to_vec())); let refs: Vec<(&str, &[u8])> = parts.iter().map(|(n, d)| (n.as_str(), d.as_slice())).collect(); diff --git a/crates/xlsx/src/tests/malformed.rs b/crates/xlsx/src/tests/malformed.rs index eecc5b4901..ae4056fbd0 100644 --- a/crates/xlsx/src/tests/malformed.rs +++ b/crates/xlsx/src/tests/malformed.rs @@ -163,7 +163,7 @@ fn hostile_threaded_comments_persons_and_note_vml() { let mut f = z.by_index(i).unwrap(); let mut d = vec![]; std::io::Read::read_to_end(&mut f, &mut d).unwrap(); - parts.push((f.name().to_string(), d)); + parts.push((f.name().unwrap().to_string(), d)); } let ns = r#"xmlns="http://schemas.microsoft.com/office/spreadsheetml/2018/threadedcomments""#; let deep = "".repeat(300) + &"".repeat(300); diff --git a/crates/xlsx/src/tests/note_box.rs b/crates/xlsx/src/tests/note_box.rs index 09a3d68e6a..289ca64a11 100644 --- a/crates/xlsx/src/tests/note_box.rs +++ b/crates/xlsx/src/tests/note_box.rs @@ -26,7 +26,7 @@ fn package() -> Vec { /// The written VML part (GridCraft writes one per sheet with notes). fn written_vml(bytes: &[u8]) -> String { let mut z = zip::ZipArchive::new(std::io::Cursor::new(bytes)).unwrap(); - let name = (0..z.len()).map(|i| z.by_index(i).unwrap().name().to_string()).find(|n| n.ends_with(".vml")).expect("a VML part"); + let name = (0..z.len()).map(|i| z.by_index(i).unwrap().name().unwrap().to_string()).find(|n| n.ends_with(".vml")).expect("a VML part"); let mut s = String::new(); z.by_name(&name).unwrap().read_to_string(&mut s).unwrap(); s diff --git a/crates/xlsx/src/tests/passthrough_tests.rs b/crates/xlsx/src/tests/passthrough_tests.rs index d014319fb3..534767d757 100644 --- a/crates/xlsx/src/tests/passthrough_tests.rs +++ b/crates/xlsx/src/tests/passthrough_tests.rs @@ -129,7 +129,7 @@ impl Unpacked { let mut f = z.by_index(i).unwrap(); let mut v = vec![]; f.read_to_end(&mut v).unwrap(); - parts.insert(f.name().to_string(), v); + parts.insert(f.name().unwrap().to_string(), v); } Unpacked { parts } } @@ -707,7 +707,7 @@ fn chart_sheet_entries_sharing_a_graph_are_checked_once() { let mut f = z.by_index(i).unwrap(); let mut data = Vec::new(); f.read_to_end(&mut data).unwrap(); - parts.push((f.name().to_string(), data)); + parts.push((f.name().unwrap().to_string(), data)); } let extra: String = (0..3_000).map(|i| format!(r#""#, 100 + i)).collect(); for (name, data) in &mut parts { diff --git a/crates/xlsx/src/tests/pivot_tests.rs b/crates/xlsx/src/tests/pivot_tests.rs index 4489cb441f..d9a9849fd4 100644 --- a/crates/xlsx/src/tests/pivot_tests.rs +++ b/crates/xlsx/src/tests/pivot_tests.rs @@ -210,7 +210,7 @@ fn unzip(bytes: &[u8]) -> HashMap> { let mut f = z.by_index(i).unwrap(); let mut b = Vec::new(); f.read_to_end(&mut b).unwrap(); - m.insert(f.name().to_string(), b); + m.insert(f.name().unwrap().to_string(), b); } m } diff --git a/crates/xlsx/src/tests/roundtrip.rs b/crates/xlsx/src/tests/roundtrip.rs index a497007686..bbe71a87ca 100644 --- a/crates/xlsx/src/tests/roundtrip.rs +++ b/crates/xlsx/src/tests/roundtrip.rs @@ -633,7 +633,7 @@ fn assert_drawing_and_chart_roundtrip(a: &Sheet, b: &Sheet) { fn package_structure() { let bytes = write_xlsx(&sample()).unwrap(); let mut z = zip::ZipArchive::new(std::io::Cursor::new(bytes)).unwrap(); - let names: Vec = (0..z.len()).map(|i| z.name_for_index(i).unwrap().to_string()).collect(); + let names: Vec = (0..z.len()).map(|i| z.name_for_index(i).unwrap().unwrap().to_string()).collect(); assert_eq!(names[0], "[Content_Types].xml"); for n in [ "_rels/.rels", @@ -900,7 +900,7 @@ fn vba_project_roundtrip() { assert_eq!(write_xlsx(&wb).unwrap(), bytes, "output is deterministic"); let mut z = zip::ZipArchive::new(std::io::Cursor::new(bytes.clone())).unwrap(); - let names: Vec = (0..z.len()).map(|i| z.name_for_index(i).unwrap().to_string()).collect(); + let names: Vec = (0..z.len()).map(|i| z.name_for_index(i).unwrap().unwrap().to_string()).collect(); assert!(names.iter().any(|x| x == "xl/vbaProject.bin"), "missing vbaProject.bin"); let mut bin = vec![]; z.by_name("xl/vbaProject.bin").unwrap().read_to_end(&mut bin).unwrap(); diff --git a/crates/xlsx/src/tests/shared_media.rs b/crates/xlsx/src/tests/shared_media.rs index 0c37e584bc..a07dc47d91 100644 --- a/crates/xlsx/src/tests/shared_media.rs +++ b/crates/xlsx/src/tests/shared_media.rs @@ -25,7 +25,7 @@ fn sheet_with(name: &str, pictures: &[(u32, &[u8])]) -> Arc { fn names(bytes: &[u8]) -> Vec { let z = zip::ZipArchive::new(std::io::Cursor::new(bytes.to_vec())).unwrap(); - z.file_names().map(str::to_string).collect() + z.file_names().map(|n| n.unwrap().into_owned()).collect() } fn text(bytes: &[u8], name: &str) -> String { diff --git a/crates/xlsx/src/tests/trendline_roundtrip.rs b/crates/xlsx/src/tests/trendline_roundtrip.rs index 081dceabfc..2beb38d009 100644 --- a/crates/xlsx/src/tests/trendline_roundtrip.rs +++ b/crates/xlsx/src/tests/trendline_roundtrip.rs @@ -108,7 +108,7 @@ fn every_trendline_kind_round_trips_in_every_chart_group() { fn chart_parts(bytes: &[u8]) -> Vec { let mut z = zip::ZipArchive::new(std::io::Cursor::new(bytes.to_vec())).unwrap(); let mut names: Vec = - (0..z.len()).map(|i| z.name_for_index(i).unwrap().to_string()).filter(|n| n.starts_with("xl/charts/chart")).collect(); + (0..z.len()).map(|i| z.name_for_index(i).unwrap().unwrap().to_string()).filter(|n| n.starts_with("xl/charts/chart")).collect(); names.sort(); names .iter() diff --git a/crates/xlsx/src/tests/zip_order.rs b/crates/xlsx/src/tests/zip_order.rs index 939b268d76..97dddd0795 100644 --- a/crates/xlsx/src/tests/zip_order.rs +++ b/crates/xlsx/src/tests/zip_order.rs @@ -17,7 +17,7 @@ fn package_starts_with_content_types_rels_and_workbook_before_any_large_part() { let bytes = write_xlsx(&wb).unwrap(); let mut zip = zip::ZipArchive::new(std::io::Cursor::new(&bytes)).unwrap(); - let names: Vec = (0..zip.len()).filter_map(|i| zip.by_index(i).ok().map(|f| f.name().to_string())).collect(); + let names: Vec = (0..zip.len()).filter_map(|i| zip.by_index(i).ok().map(|f| f.name().unwrap().to_string())).collect(); assert_eq!(names.first().map(String::as_str), Some("[Content_Types].xml"), "{names:?}"); assert_eq!(names.get(1).map(String::as_str), Some("_rels/.rels"), "{names:?}"); assert_eq!(names.get(2).map(String::as_str), Some("xl/_rels/workbook.xml.rels"), "{names:?}"); From 51ab33dbe3bfad909e8051b7c50eab2a9d78b06c Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Fri, 20 Nov 2026 18:56:11 -0800 Subject: [PATCH 20/21] CLI check: read package parts by entry index The package checker listed entry names and then opened each part with by_name. zip 9 decodes names not flagged UTF-8 as CP437, and by_name cannot find such a name in its raw-name index, so every lookup scanned and decoded all entries (up to MAX_ENTRIES). A name that does not decode is listed lossy and by_name did not find it at all, and two entries that decode to the same name were both read from the first. zip_names now returns each entry's index with its name, and the validator, the full-calc-on-load check and the relationship check read parts with by_index. The relationship check caches verdicts per entry index. --- apps/gridcraft-cli/src/check/package.rs | 119 +++++++++++++++++------- 1 file changed, 86 insertions(+), 33 deletions(-) diff --git a/apps/gridcraft-cli/src/check/package.rs b/apps/gridcraft-cli/src/check/package.rs index 45c1c7cae5..5e44d29724 100644 --- a/apps/gridcraft-cli/src/check/package.rs +++ b/apps/gridcraft-cli/src/check/package.rs @@ -110,8 +110,10 @@ fn resolve_target(source_dir: &str, target: &str) -> String { type Zip<'a> = zip::ZipArchive>; -fn zip_names(zip: &mut Zip<'_>) -> Vec { - (0..zip.len().min(MAX_ENTRIES)).filter_map(|i| zip.by_index_raw(i).ok().filter(|f| !f.is_dir()).map(|f| entry_name(&f))).collect() +/// `(index, name)` of every file entry. Parts are read by index: two entries can decode to the +/// same name, and looking up a CP437 name scans the whole archive. +fn zip_names(zip: &mut Zip<'_>) -> Vec<(usize, String)> { + (0..zip.len().min(MAX_ENTRIES)).filter_map(|i| zip.by_index_raw(i).ok().filter(|f| !f.is_dir()).map(|f| (i, entry_name(&f)))).collect() } /// An entry's name: UTF-8, or CP437 when the entry isn't flagged UTF-8. A name that doesn't decode @@ -120,8 +122,8 @@ fn entry_name(f: &zip::read::ZipFile<'_, R>) -> String { f.name().map(|n| n.into_owned()).unwrap_or_else(|_| String::from_utf8_lossy(f.name_raw()).into_owned()) } -fn read_zip_part(zip: &mut Zip<'_>, name: &str) -> Result, String> { - let f = zip.by_name(name).map_err(|e| format!("{name}: {e}"))?; +fn read_zip_part(zip: &mut Zip<'_>, index: usize, name: &str) -> Result, String> { + let f = zip.by_index(index).map_err(|e| format!("{name}: {e}"))?; let mut buf = Vec::new(); f.take(MAX_XML_PART).read_to_end(&mut buf).map_err(|e| format!("{name}: {e}"))?; Ok(buf) @@ -134,8 +136,8 @@ enum PartError { } /// Reads a part like [`read_zip_part`], charging the decompressed bytes to `budget`. -fn read_zip_part_within(zip: &mut Zip<'_>, name: &str, budget: &mut u64) -> Result, PartError> { - let f = zip.by_name(name).map_err(|_| PartError::Unreadable)?; +fn read_zip_part_within(zip: &mut Zip<'_>, index: usize, budget: &mut u64) -> Result, PartError> { + let f = zip.by_index(index).map_err(|_| PartError::Unreadable)?; // One byte past what is left shows that the part doesn't fit. let limit = MAX_XML_PART.min(budget.saturating_add(1)); let mut buf = Vec::new(); @@ -156,10 +158,10 @@ fn read_zip_part_within(zip: &mut Zip<'_>, name: &str, budget: &mut u64) -> Resu pub(super) fn full_calc_on_load(bytes: &[u8]) -> bool { let Ok(mut zip) = zip::ZipArchive::new(Cursor::new(bytes)) else { return false }; let names = zip_names(&mut zip); - let find = |key: &str| names.iter().find(|n| part_key(n) == key).cloned(); + let find = |key: &str| names.iter().find(|(_, n)| part_key(n) == key).cloned(); let mut workbook = "xl/workbook.xml".to_string(); - if let Some(rels) = find("_rels/.rels") - && let Ok(xml) = read_zip_part(&mut zip, &rels) + if let Some((i, rels)) = find("_rels/.rels") + && let Ok(xml) = read_zip_part(&mut zip, i, &rels) && let Ok(els) = xml_elements(&xml) && let Some(target) = els .iter() @@ -168,8 +170,8 @@ pub(super) fn full_calc_on_load(bytes: &[u8]) -> bool { { workbook = resolve_target("", target); } - let Some(name) = find(&part_key(&workbook)) else { return false }; - let Ok(xml) = read_zip_part(&mut zip, &name) else { return false }; + let Some((i, name)) = find(&part_key(&workbook)) else { return false }; + let Ok(xml) = read_zip_part(&mut zip, i, &name) else { return false }; xml_elements(&xml) .ok() .into_iter() @@ -183,15 +185,15 @@ pub(super) fn full_calc_on_load(bytes: &[u8]) -> bool { pub fn validate_package(bytes: &[u8]) -> Result, String> { let mut zip = zip::ZipArchive::new(Cursor::new(bytes)).map_err(|e| format!("not a zip package: {e}"))?; let names = zip_names(&mut zip); - let parts: HashSet = names.iter().map(|n| part_key(n)).collect(); - let mut read_part = |name: &str| read_zip_part(&mut zip, name); + let parts: HashSet = names.iter().map(|(_, n)| part_key(n)).collect(); + let mut read_part = |index: usize, name: &str| read_zip_part(&mut zip, index, name); let mut issues = Vec::new(); - let ct_name = names.iter().find(|n| part_key(n) == "[content_types].xml").cloned(); + let ct_name = names.iter().find(|(_, n)| part_key(n) == "[content_types].xml").cloned(); let (mut defaults, mut overrides) = (HashSet::new(), HashSet::new()); match ct_name { None => issues.push("no [Content_Types].xml".to_string()), - Some(n) => { - for (el, attrs) in xml_elements(&read_part(&n)?).map_err(|e| format!("[Content_Types].xml: {e}"))? { + Some((i, n)) => { + for (el, attrs) in xml_elements(&read_part(i, &n)?).map_err(|e| format!("[Content_Types].xml: {e}"))? { match el.as_str() { "Default" => { if let Some(x) = attr(&attrs, "Extension") { @@ -208,9 +210,9 @@ pub fn validate_package(bytes: &[u8]) -> Result, String> { } } } - let mut sorted: Vec<&String> = names.iter().collect(); - sorted.sort(); - for n in &sorted { + let mut sorted: Vec<&(usize, String)> = names.iter().collect(); + sorted.sort_by(|a, b| a.1.cmp(&b.1).then(a.0.cmp(&b.0))); + for (_, n) in &sorted { let key = part_key(n); if key == "[content_types].xml" { continue; @@ -225,7 +227,7 @@ pub fn validate_package(bytes: &[u8]) -> Result, String> { for p in missing_overrides { issues.push(format!("content type override for missing part /{p}")); } - for n in sorted { + for (i, n) in sorted { let key = part_key(n); let Some(rels_file) = key.strip_suffix(".rels") else { continue }; // `dir/_rels/name.rels` describes `dir/name`; `_rels/.rels` the package itself. @@ -239,7 +241,7 @@ pub fn validate_package(bytes: &[u8]) -> Result, String> { issues.push(format!("{n} describes missing part {source}")); } let mut ids = HashSet::new(); - for (el, attrs) in xml_elements(&read_part(n)?).map_err(|e| format!("{n}: {e}"))? { + for (el, attrs) in xml_elements(&read_part(*i, n)?).map_err(|e| format!("{n}: {e}"))? { if el != "Relationship" { continue; } @@ -274,17 +276,17 @@ pub(super) fn relationship_kinds(bytes: &[u8]) -> Result Result, String> { let mut zip = zip::ZipArchive::new(Cursor::new(bytes)).map_err(|e| format!("not a zip package: {e}"))?; let names = zip_names(&mut zip); - let by_key: HashMap = names.iter().map(|n| (part_key(n), n)).collect(); + let by_key: HashMap = names.iter().map(|e| (part_key(&e.1), e)).collect(); // Several relationships name the same part; each fresh check decompressed it again, so // repeated references to one highly compressible part multiplied the work. The verdict is // remembered per (part, named content) and the decompression the package can cause is // budgeted as a whole, the relationship parts included: many large, unreferenced rels parts // would otherwise each spend a full per-part allowance. - let mut verdicts: HashMap<(String, &'static str), bool> = HashMap::new(); + let mut verdicts: HashMap<(usize, &'static str), bool> = HashMap::new(); let mut kinds = BTreeMap::new(); - for n in names.iter().filter(|n| part_key(n).ends_with(".rels")) { + for (i, n) in names.iter().filter(|(_, n)| part_key(n).ends_with(".rels")) { let Some(src_dir) = rels_source_dir(&part_key(n)) else { continue }; - let xml = match read_zip_part_within(&mut zip, n, &mut budget) { + let xml = match read_zip_part_within(&mut zip, *i, &mut budget) { Ok(xml) => xml, Err(PartError::OverBudget) => return Err(format!("{n}: relationship check stopped at its decompression limit")), Err(PartError::Unreadable) => continue, @@ -298,8 +300,8 @@ fn relationship_kinds_within(bytes: &[u8], mut budget: u64) -> Result Option { /// comes first) a comment, for VML a shape. Read only as far as needed; an unreadable part counts. /// `verdicts` remembers the answer per (part, named content); `budget` is the decompression this /// package's remaining checks may cause, and once it is spent the part counts as having content. -fn holds_something(zip: &mut Zip<'_>, name: &str, kind: &str, verdicts: &mut HashMap<(String, &'static str), bool>, budget: &mut u64) -> bool { +fn holds_something(zip: &mut Zip<'_>, index: usize, kind: &str, verdicts: &mut HashMap<(usize, &'static str), bool>, budget: &mut u64) -> bool { let wanted: Option<&'static [u8]> = match kind.to_ascii_lowercase().as_str() { "comments" => Some(b"comment"), "vmldrawing" => Some(b"shape"), @@ -331,17 +333,17 @@ fn holds_something(zip: &mut Zip<'_>, name: &str, kind: &str, verdicts: &mut Has Some(_) => "shape", None => "any", }; - if let Some(v) = verdicts.get(&(name.to_ascii_lowercase(), marker)) { + if let Some(v) = verdicts.get(&(index, marker)) { return *v; } - let v = holds_something_uncached(zip, name, marker, budget); - verdicts.insert((name.to_ascii_lowercase(), marker), v); + let v = holds_something_uncached(zip, index, marker, budget); + verdicts.insert((index, marker), v); v } -fn holds_something_uncached(zip: &mut Zip<'_>, name: &str, marker: &'static str, budget: &mut u64) -> bool { +fn holds_something_uncached(zip: &mut Zip<'_>, index: usize, marker: &'static str, budget: &mut u64) -> bool { use quick_xml::events::Event; - let Ok(f) = zip.by_name(name) else { return true }; + let Ok(f) = zip.by_index(index) else { return true }; if *budget == 0 { return true; } @@ -398,6 +400,57 @@ mod tests { z.finish().unwrap().into_inner() } + /// A package with two relationship parts whose names both read `xl/_rels/é.xml.rels`: the first + /// stored as UTF-8 holding `first`, the second stored as CP437 (byte 0x82) holding `second`. + fn same_name_rels(first: &str, second: &str) -> Vec { + const PLACEHOLDER: &[u8] = b"xl/_rels/Q.xml.rels"; + let mut z = zip::ZipWriter::new(Cursor::new(Vec::new())); + let opts = zip::write::SimpleFileOptions::default().compression_method(zip::CompressionMethod::Deflated); + z.start_file("xl/_rels/\u{e9}.xml.rels", opts).unwrap(); + z.write_all(first.as_bytes()).unwrap(); + z.start_file(String::from_utf8(PLACEHOLDER.to_vec()).unwrap(), opts).unwrap(); + z.write_all(second.as_bytes()).unwrap(); + let mut bytes = z.finish().unwrap().into_inner(); + // The name sits in the local header and in the central directory; both get the CP437 byte. + let mut at = 0; + let mut patched = 0; + while let Some(i) = bytes.get(at..).and_then(|rest| rest.windows(PLACEHOLDER.len()).position(|w| w == PLACEHOLDER)) { + bytes[at + i + 9] = 0x82; + at += i + PLACEHOLDER.len(); + patched += 1; + } + assert_eq!(patched, 2); + bytes + } + + fn rels_xml(rels: &[(&str, &str)]) -> String { + let body: String = rels + .iter() + .map(|(id, kind)| { + format!( + r#""# + ) + }) + .collect(); + format!(r#"{body}"#) + } + + #[test] + fn parts_with_the_same_decoded_name_are_each_validated() { + let bytes = same_name_rels(&rels_xml(&[("rId1", "custom")]), &rels_xml(&[("rId1", "custom"), ("rId1", "custom")])); + let issues = validate_package(&bytes).unwrap(); + let duplicates = issues.iter().filter(|i| i.ends_with("duplicate relationship id rId1")).count(); + assert_eq!(duplicates, 1, "{issues:?}"); + } + + #[test] + fn relationship_kinds_read_parts_with_the_same_decoded_name() { + let bytes = same_name_rels(&rels_xml(&[("rId1", "custom")]), &rels_xml(&[("rId1", "audio")])); + let kinds = relationship_kinds(&bytes).unwrap(); + assert!(kinds.contains_key("custom"), "{kinds:?}"); + assert!(kinds.contains_key("audio"), "{kinds:?}"); + } + #[test] fn relationship_parts_count_against_the_decompression_budget() { // Each part fits the per-part allowance, but together they need more than the budget. From 5e2bca0ae73a1c0a0357254f0c59dca6c1462c13 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Tue, 24 Nov 2026 05:28:13 -0800 Subject: [PATCH 21/21] Deps: raise the zip minimum to 9.8.2 The workspace requirement was 9.0.5 and the lockfile resolved zip 9.1.0. Both now name 9.8.2, the current 9.x release, which includes the 9.2.3 follow-up fix for GHSA-m665-v7pm-7grj. The lockfile adds constant_time_eq 0.6.1, which zip 9.8.2 depends on. --- Cargo.lock | 16 ++++++++++++++-- Cargo.toml | 2 +- 2 files changed, 15 insertions(+), 3 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index 218eba60a7..c098a9b39f 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -830,6 +830,15 @@ version = "0.10.3" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "be95d4a884358a21a199689323c29e9256b4a1b315e22f183d155422041d3a9a" +[[package]] +name = "constant_time_eq" +version = "0.6.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9eb6feb175df65d0a3ccd3e73484e940d0ac664e8034f0519fd49a93db3071d9" +dependencies = [ + "rustversion", +] + [[package]] name = "core-foundation" version = "0.9.4" @@ -7222,18 +7231,21 @@ dependencies = [ [[package]] name = "zip" -version = "9.1.0" +version = "9.8.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "2886b00003a72c4ccee3f42cfc34908d33b2508a74d827dc2a4244706475c704" +checksum = "2d8dbe089cf6b0448b78f5fc50139ab5aaa40d08ac07cdc1baf2c13add35fcce" dependencies = [ + "constant_time_eq", "crc32fast", "flate2", "getrandom 0.4.3", "indexmap", + "libc", "memchr", "nix", "typed-path", "windows-sys 0.61.2", + "zeroize", "zopfli", ] diff --git a/Cargo.toml b/Cargo.toml index 901b57c89f..4def72259f 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -65,7 +65,7 @@ web-time = "1.1.0" rayon = "1" regex = { version = "1", default-features = false, features = ["std", "unicode", "perf"] } quick-xml = "0.41" -zip = { version = "9.0.5", default-features = false, features = ["deflate"] } +zip = { version = "9.8.2", default-features = false, features = ["deflate"] } sha2 = { version = "0.11", default-features = false } image = { version = "0.25", default-features = false, features = ["png", "jpeg"] }