From 06c2b1440b0134ec184561dcc2275fdb5f18a5af Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sun, 25 Oct 2026 17:46:56 -0700 Subject: [PATCH 01/16] Fill handle: Linear Trend and Growth Trend on the right-drag menu for numbers When every source cell holds a number, the right-drag fill menu now also offers Linear Trend and Growth Trend. edit.autoFill takes them as the modes linearTrend and growthTrend. Linear Trend continues the least-squares line through each row or column of the source, and Growth Trend continues the exponential curve fitted to it, as the TREND and GROWTH functions fit them for positive numbers: 1, 2 continues as 3, 4, 5 or as 4, 8, 16. Dragging up or left continues the trend backward. The source keeps its values, and a lone number repeats. Growth Trend is offered only when each row or column is all above zero or all below zero; numbers below zero grow away from zero. --- ROADMAP.md | 1 + crates/engine/src/cmd/edit.rs | 4 +- crates/engine/src/fill.rs | 157 ++++++++++++++++-- crates/engine/src/tests.rs | 88 ++++++++++ crates/ui-egui/src/grid.rs | 23 +++ .../tests/it/fill_handle_right_drag.rs | 41 ++++- docs/ui-parity.md | 5 +- 7 files changed, 297 insertions(+), 22 deletions(-) diff --git a/ROADMAP.md b/ROADMAP.md index 6b9b0fce7..d94bbb6b0 100644 --- a/ROADMAP.md +++ b/ROADMAP.md @@ -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-25 | Fill handle: from numbers, the right-drag menu offers Linear Trend and Growth Trend, which continue the best-fit line or exponential curve of the source (1, 2 gives 3, 4, 5 or 4, 8, 16) | | 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 28ce338d6..1277e9142 100644 --- a/crates/engine/src/cmd/edit.rs +++ b/crates/engine/src/cmd/edit.rs @@ -79,7 +79,7 @@ pub fn specs() -> Vec { "AutoFill", [], None, - "{source: \"A1:A2\", target: \"A1:A10\", mode?: series|alternate|copy|formats|values|extend|days|weekdays|months|years}: the fill-handle drag (alternate = Ctrl+drag: a lone number counts up, any other series copies; values = Fill Without Formatting: the series, targets keep their formats; extend = Fill Series: the series, and a lone number counts up; days, weekdays, months, years = Fill Days, Fill Weekdays, Fill Months, Fill Years: dates step by one unit, or by the difference between the first two dates in that unit, and weekdays skip Saturday and Sunday)", + "{source: \"A1:A2\", target: \"A1:A10\", mode?: series|alternate|copy|formats|values|extend|days|weekdays|months|years|linearTrend|growthTrend}: the fill-handle drag (alternate = Ctrl+drag: a lone number counts up, any other series copies; values = Fill Without Formatting: the series, targets keep their formats; extend = Fill Series: the series, and a lone number counts up; days, weekdays, months, years = Fill Days, Fill Weekdays, Fill Months, Fill Years: dates step by one unit, or by the difference between the first two dates in that unit, and weekdays skip Saturday and Sunday; linearTrend, growthTrend = Linear Trend, Growth Trend: the targets continue the least-squares line or the exponential curve fitted to each row or column of source numbers, and the source keeps its values; an error when a source cell is not a number or holds a formula, or for growthTrend when a row or column mixes signs or holds zero)", has_doc, auto_fill ), @@ -1589,6 +1589,8 @@ fn auto_fill(s: &mut Session, p: &Json) -> Result { "weekdays" => crate::fill::FillMode::Dates(crate::fill::DateUnit::Weekday), "months" => crate::fill::FillMode::Dates(crate::fill::DateUnit::Month), "years" => crate::fill::FillMode::Dates(crate::fill::DateUnit::Year), + "linearTrend" => crate::fill::FillMode::LinearTrend, + "growthTrend" => crate::fill::FillMode::GrowthTrend, _ => crate::fill::FillMode::Series, }; if target.count() > crate::fill::MAX_FILL_CELLS || src.count() > crate::fill::MAX_FILL_CELLS { diff --git a/crates/engine/src/fill.rs b/crates/engine/src/fill.rs index b12700e4f..1340489c0 100644 --- a/crates/engine/src/fill.rs +++ b/crates/engine/src/fill.rs @@ -28,6 +28,12 @@ pub enum FillMode { /// counted in that unit (one unit when they fall in the same one). A source that isn't dates /// extends like a plain drag. Dates(DateUnit), + /// Linear Trend: the targets continue the least-squares line (y = mx + b) through the source's + /// numbers. The source keeps its values. + LinearTrend, + /// Growth Trend: the targets continue the exponential curve (y = b·m^x) fitted to the source's + /// numbers. The source keeps its values. + GrowthTrend, } /// The step of a [`FillMode::Dates`] fill. @@ -47,6 +53,59 @@ impl FillMode { } } +/// Whether a fill from `src` to `target` runs down or up the sheet rather than across it. +fn fills_vertically(src: RangeRef, target: RangeRef) -> bool { + target.height() != src.height() || target.width() == src.width() +} + +/// The numbers in each lane of `src` that a fill to `target` continues, or `None` when a source +/// cell is empty or holds text, a logical value, an error or a formula. +fn numeric_lanes(wb: &Workbook, sheet: usize, src: RangeRef, target: RangeRef) -> Option>> { + let sh = wb.sheet(sheet)?; + let vertical = fills_vertically(src, target); + let lanes: Vec = if vertical { (src.start.col..=src.end.col).collect() } else { (src.start.row..=src.end.row).collect() }; + let len = if vertical { src.height() } else { src.width() }; + lanes + .into_iter() + .map(|lane| { + (0..len) + .map(|i| { + let c = if vertical { CellRef::new(src.start.row + i, lane) } else { CellRef::new(lane, src.start.col + i) }; + let cell = sh.cell(c)?; + if cell.formula.is_some() || !cell.value.is_number() { + return None; + } + cell.value.as_f64() + }) + .collect() + }) + .collect() +} + +/// Whether the fill menu offers Linear Trend (`growth` false) or Growth Trend (`growth` true) for a +/// fill from `src` to `target`: every source cell holds a number, and for Growth Trend the numbers +/// of each lane are all above zero or all below zero. +pub fn trend_applies(wb: &Workbook, sheet: usize, src: RangeRef, target: RangeRef, growth: bool) -> bool { + let Some(sh) = wb.sheet(sheet) else { return false }; + let vertical = fills_vertically(src, target); + let (lanes, len) = if vertical { (src.start.col..=src.end.col, src.height()) } else { (src.start.row..=src.end.row, src.width()) }; + for lane in lanes { + let (mut above, mut below) = (false, false); + for i in 0..len { + let c = if vertical { CellRef::new(src.start.row + i, lane) } else { CellRef::new(lane, src.start.col + i) }; + let Some(n) = sh.cell(c).filter(|cell| cell.formula.is_none() && cell.value.is_number()).and_then(|cell| cell.value.as_f64()) else { + return false; + }; + above |= n > 0.0; + below |= n < 0.0; + if growth && (n == 0.0 || (above && below)) { + return false; + } + } + } + true +} + /// Whether a number format shows a calendar date (`YYYY-MM-DD` and `m/d/yyyy h:mm` do; `0 "days"` /// and `h:mm` don't). fn is_date_format(fmt: &str) -> bool { @@ -90,7 +149,7 @@ pub fn fill(cx: &mut Ctx, sheet: usize, src: RangeRef, target: RangeRef, mode: F let custom = cx.wb.custom_lists.clone(); let Some(sh) = cx.wb.sheet(sheet) else { return Ok(()) }; // Direction: down/up if target extends rows, else right/left. - let vertical = target.height() != src.height() || target.width() == src.width(); + let vertical = fills_vertically(src, target); let forward = if vertical { target.end.row > src.end.row || target.start.row == src.start.row } else { @@ -108,11 +167,25 @@ pub fn fill(cx: &mut Ctx, sheet: usize, src: RangeRef, target: RangeRef, mode: F if u64::from(lane_count).saturating_mul(u64::from(steps)) > MAX_FILL_CELLS { return Err(crate::EngineError::Other("The fill is too large.".into())); } + // Linear Trend and Growth Trend fit each lane's numbers. + let trends: Vec = match mode { + FillMode::LinearTrend | FillMode::GrowthTrend => { + let Some(lanes) = numeric_lanes(&cx.wb, sheet, src, target) else { + return Err(crate::EngineError::Other("Linear Trend and Growth Trend need a number in every source cell.".into())); + }; + let fit = |nums: &Vec| if mode == FillMode::GrowthTrend { Pattern::growth(nums) } else { Some(Pattern::linear(nums)) }; + let Some(trends) = lanes.iter().map(fit).collect() else { + return Err(crate::EngineError::Other("Growth Trend needs numbers that are all above zero or all below zero.".into())); + }; + trends + } + _ => Vec::new(), + }; let lanes: Vec = if vertical { (src.start.col..=src.end.col).collect() } else { (src.start.row..=src.end.row).collect() }; let src_len = if vertical { src.height() } else { src.width() }; let mut writes: Vec<(CellRef, Option)> = Vec::new(); let mut pictures = Vec::new(); - for lane in lanes { + for (lane_i, lane) in lanes.into_iter().enumerate() { let src_cells: Vec<(CellRef, Option)> = (0..src_len) .map(|i| { let c = if vertical { CellRef::new(src.start.row + i, lane) } else { CellRef::new(lane, src.start.col + i) }; @@ -129,7 +202,9 @@ pub fn fill(cx: &mut Ctx, sheet: usize, src: RangeRef, target: RangeRef, mode: F cols.into_iter().map(|c| CellRef::new(lane, c)).collect() }; let fmt = |c: &(CellRef, Option)| cx.wb.styles.get(c.1.as_ref().map(|c| c.style).unwrap_or_default()).num_fmt.as_str(); - let pattern = if mode.extends_series() || mode == FillMode::Alternate { + let pattern = if let Some(trend) = trends.get(lane_i) { + trend.clone() + } else if mode.extends_series() || mode == FillMode::Alternate { let first_fmt = src_cells.first().map(fmt).unwrap_or_default(); let dates = match mode { FillMode::Dates(unit) => Pattern::dates(&src_cells, unit, cx.wb.date_system, first_fmt), @@ -163,7 +238,14 @@ pub fn fill(cx: &mut Ctx, sheet: usize, src: RangeRef, target: RangeRef, mode: F writes.push((*t, Some(existing))); continue; } - FillMode::ValuesOnly | FillMode::Series | FillMode::Alternate | FillMode::Copy | FillMode::Extend | FillMode::Dates(_) => { + FillMode::ValuesOnly + | FillMode::Series + | FillMode::Alternate + | FillMode::Copy + | FillMode::Extend + | FillMode::Dates(_) + | FillMode::LinearTrend + | FillMode::GrowthTrend => { let style = if mode == FillMode::ValuesOnly { sh.cell(*t).map(|c| c.style).unwrap_or_default() } else { cell.style }; if let Some(f) = &cell.formula { if let Some(e) = f.expr() { @@ -244,9 +326,42 @@ enum Pattern { step: i64, sys: gridcraft_core::DateSystem, }, + /// Growth Trend, kept as logarithms so that a value the curve reaches is not lost to an + /// overflow or underflow on the way: the logarithms of the fitted magnitudes at the source's + /// last and first cells, the logarithm of the factor between neighboring cells, and the sign + /// of every value (1 or -1). + Growth { + last: f64, + first: f64, + step: f64, + sign: f64, + }, } impl Pattern { + /// Linear Trend: the least-squares line through `nums`. A lone number gives a step of zero. + fn linear(nums: &[f64]) -> Pattern { + let (first, last, step) = least_squares(nums); + Pattern::Linear { last, first, step } + } + + /// The exponential curve y = b·m^x fitted to `nums` at positions 0, 1, 2… by least squares on + /// the logarithms, as the GROWTH function fits positive numbers. Numbers below zero are fitted + /// by their magnitudes and keep their sign. `None` when the numbers are not all above zero or + /// all below zero. A lone number gives a factor of one. + fn growth(nums: &[f64]) -> Option { + let sign = if nums.iter().all(|y| *y > 0.0) { + 1.0 + } else if nums.iter().all(|y| *y < 0.0) { + -1.0 + } else { + return None; + }; + let logs: Vec = nums.iter().map(|y| (y * sign).ln()).collect(); + let (first, last, step) = least_squares(&logs); + Some(Pattern::Growth { last, first, step, sign }) + } + /// The pattern of Fill Days, Fill Weekdays, Fill Months or Fill Years, or `None` when the /// source isn't all dates (numbers, not formulas, under a date format in its first cell). fn dates(cells: &[(CellRef, Option)], unit: DateUnit, sys: gridcraft_core::DateSystem, fmt: &str) -> Option { @@ -328,19 +443,7 @@ impl Pattern { } } // Least-squares step for 2+ values (Excel uses a linear trend). - let n = nums.len() as f64; - let mean_x = (n - 1.0) / 2.0; - let mean_y = nums.iter().sum::() / n; - let mut num = 0.0; - let mut den = 0.0; - for (i, y) in nums.iter().enumerate() { - num += (i as f64 - mean_x) * (y - mean_y); - den += (i as f64 - mean_x).powi(2); - } - let step = if den == 0.0 { 0.0 } else { num / den }; - let fitted_last = mean_y + step * (n - 1.0 - mean_x); - let fitted_first = mean_y - step * mean_x; - return Pattern::Linear { last: fitted_last, first: fitted_first, step }; + return Pattern::linear(&nums); } // Text. if !vals.is_empty() && vals.iter().all(|v| v.is_text()) { @@ -434,10 +537,30 @@ impl Pattern { let base = if forward { *last } else { *first }; Some(Value::number(add_weekdays(*sys, base, step.checked_mul(k)?.checked_mul(sign)?)?)) } + Pattern::Growth { last, first, step, sign: growth_sign } => { + let base = if forward { *last } else { *first }; + Some(Value::number(round15(growth_sign * (base + step * (k * sign) as f64).exp()))) + } } } } +/// The least-squares line through `nums` at positions 0, 1, 2…: its values at the first and last +/// positions, and its step. A lone number gives a step of zero. +fn least_squares(nums: &[f64]) -> (f64, f64, f64) { + let n = nums.len() as f64; + let mean_x = (n - 1.0) / 2.0; + let mean_y = nums.iter().sum::() / n; + let mut num = 0.0; + let mut den = 0.0; + for (i, y) in nums.iter().enumerate() { + num += (i as f64 - mean_x) * (y - mean_y); + den += (i as f64 - mean_x).powi(2); + } + let step = if den == 0.0 { 0.0 } else { num / den }; + (mean_y - step * mean_x, mean_y + step * (n - 1.0 - mean_x), step) +} + /// Whether `serial` falls on Monday to Friday; `None` outside the supported date range. fn is_weekday(sys: gridcraft_core::DateSystem, serial: f64) -> Option { datetime_from_serial(sys, serial).map(|d| d.weekday != 0 && d.weekday != 6) diff --git a/crates/engine/src/tests.rs b/crates/engine/src/tests.rs index 13fbb9b3a..3e6c1a350 100644 --- a/crates/engine/src/tests.rs +++ b/crates/engine/src/tests.rs @@ -1003,6 +1003,94 @@ fn fill_days_weekdays_months_and_years_step_a_date_by_that_unit() { assert_eq!(v(&s, "J2"), Value::Number(46081.5)); } +#[test] +fn linear_and_growth_trend_continue_the_fitted_line_or_curve() { + let mut s = s(); + let nums = |s: &Session, cells: &[&str]| cells.iter().map(|c| v(s, c)).collect::>(); + let n = |xs: &[f64]| xs.iter().map(|x| Value::Number(*x)).collect::>(); + let fill = + |s: &mut Session, src: &str, target: &str, mode: &str| s.execute("edit.autoFill", json!({"source": src, "target": target, "mode": mode})); + // The examples on Excel's "Project values in a series" page: 1, 2 and 1, 3 for both trends, 2, 3 + // for Growth Trend and 100, 95 for Linear Trend. 2, 3 gives 4, 5, 6 by Linear Trend. + for (col, start, linear, growth) in [ + ("A", [1.0, 2.0], [3.0, 4.0, 5.0], [4.0, 8.0, 16.0]), + ("B", [1.0, 3.0], [5.0, 7.0, 9.0], [9.0, 27.0, 81.0]), + ("C", [2.0, 3.0], [4.0, 5.0, 6.0], [4.5, 6.75, 10.125]), + ] { + s.execute("range.setValues", json!({"range": format!("{col}1"), "values": [[start[0]], [start[1]]]})).unwrap(); + let (src, target) = (format!("{col}1:{col}2"), format!("{col}1:{col}5")); + let cells: Vec = (3..=5).map(|r| format!("{col}{r}")).collect(); + let cells: Vec<&str> = cells.iter().map(String::as_str).collect(); + fill(&mut s, &src, &target, "linearTrend").unwrap(); + assert_eq!(nums(&s, &cells), n(&linear), "Linear Trend from {start:?}"); + fill(&mut s, &src, &target, "growthTrend").unwrap(); + assert_eq!(nums(&s, &cells), n(&growth), "Growth Trend from {start:?}"); + } + s.execute("range.setValues", json!({"range": "F1", "values": [[100], [95]]})).unwrap(); + fill(&mut s, "F1:F2", "F1:F4", "linearTrend").unwrap(); + assert_eq!(nums(&s, &["F3", "F4"]), n(&[90.0, 85.0])); + // Three numbers: the targets follow the best fit and the source keeps its values. 1, 3, 4 fit + // y = 1.5x + 7/6; 1, 2, 8 fit y = 0.8909·2.8284^x. + s.execute("range.setValues", json!({"range": "D1", "values": [[1, 1], [3, 2], [4, 8]]})).unwrap(); + fill(&mut s, "D1:D3", "D1:D5", "linearTrend").unwrap(); + assert_eq!(nums(&s, &["D1", "D2", "D3", "D4", "D5"]), n(&[1.0, 3.0, 4.0, 5.66666666666667, 7.16666666666667])); + fill(&mut s, "E1:E3", "E1:E4", "growthTrend").unwrap(); + assert_eq!(nums(&s, &["E1", "E2", "E3", "E4"]), n(&[1.0, 2.0, 8.0, 20.158736798318])); + // Upward and leftward the trend continues backward: 1, 2 gives 0 and -1, or 0.5 and 0.25. + s.execute("range.setValues", json!({"range": "G3", "values": [[1], [2]]})).unwrap(); + fill(&mut s, "G3:G4", "G1:G4", "linearTrend").unwrap(); + assert_eq!(nums(&s, &["G2", "G1"]), n(&[0.0, -1.0])); + s.execute("range.setValues", json!({"range": "J1", "values": [[1, 2]]})).unwrap(); + fill(&mut s, "J1:K1", "H1:K1", "growthTrend").unwrap(); + assert_eq!(nums(&s, &["I1", "H1"]), n(&[0.5, 0.25])); + // Negative numbers grow away from zero: -2, -4 gives -8. + s.execute("range.setValues", json!({"range": "L1", "values": [[-2], [-4]]})).unwrap(); + fill(&mut s, "L1:L2", "L1:L3", "growthTrend").unwrap(); + assert_eq!(v(&s, "L3"), Value::Number(-8.0)); + // A tiny start with a huge factor still reaches 1e300 without overflowing on the way. + s.execute("range.setValues", json!({"range": "S1", "values": [[1e-200], [1e-100]]})).unwrap(); + fill(&mut s, "S1:S2", "S1:S6", "growthTrend").unwrap(); + let Value::Number(s6) = v(&s, "S6") else { panic!("S6 is {:?}", v(&s, "S6")) }; + assert!((s6 / 1e300 - 1.0).abs() < 1e-9, "S6 = {s6}"); + // A lone number repeats, and dates a month apart step by their days, not by months. + s.execute("cell.set", json!({"cell": "M1", "input": "7"})).unwrap(); + fill(&mut s, "M1", "M1:M2", "linearTrend").unwrap(); + assert_eq!(v(&s, "M2"), Value::Number(7.0)); + s.execute("cell.set", json!({"cell": "N1", "input": "1/15/2026"})).unwrap(); + s.execute("cell.set", json!({"cell": "N2", "input": "2/15/2026"})).unwrap(); + fill(&mut s, "N1:N2", "N1:N3", "linearTrend").unwrap(); + assert_eq!(v(&s, "N3"), Value::Number(46099.0), "2/15/2026 plus 31 days"); + // Text or an empty cell in the source, and zero or mixed signs for Growth Trend, are refused + // and fill nothing. + s.execute("range.setValues", json!({"range": "O1", "values": [[1, 1, 0], ["x", -2, 2]]})).unwrap(); + assert!(fill(&mut s, "O1:O2", "O1:O3", "linearTrend").is_err()); + assert!(fill(&mut s, "P1:P2", "P1:P3", "growthTrend").is_err()); + assert!(fill(&mut s, "Q1:Q2", "Q1:Q3", "growthTrend").is_err()); + assert!(fill(&mut s, "R1:R2", "R1:R3", "linearTrend").is_err()); + assert_eq!(nums(&s, &["O3", "P3", "Q3", "R3"]), [Value::Empty, Value::Empty, Value::Empty, Value::Empty]); + fill(&mut s, "P1:P2", "P1:P3", "linearTrend").unwrap(); + assert_eq!(v(&s, "P3"), Value::Number(-5.0)); +} + +#[test] +fn trend_fills_are_offered_for_numbers_only() { + let mut s = s(); + let offered = |s: &Session, src: &str, target: &str, growth: bool| { + let r = |a: &str| gridcraft_core::RangeRef::parse(a).unwrap(); + crate::fill::trend_applies(&s.doc().unwrap().wb, 0, r(src), r(target), growth) + }; + s.execute("range.setValues", json!({"range": "A1", "values": [[1, -1, 1], [2, -3, "x"]]})).unwrap(); + s.execute("cell.set", json!({"cell": "D1", "input": "=A1"})).unwrap(); + s.execute("cell.set", json!({"cell": "D2", "input": "5"})).unwrap(); + assert!(offered(&s, "A1:A2", "A1:A5", false) && offered(&s, "A1:A2", "A1:A5", true)); + // Down A1:B2, each column keeps one sign; across it, row 1 holds 1 and -1. + assert!(offered(&s, "A1:B2", "A1:B5", true)); + assert!(offered(&s, "A1:B2", "A1:E2", false) && !offered(&s, "A1:B2", "A1:E2", true)); + assert!(!offered(&s, "C1:C2", "C1:C4", false), "text"); + assert!(!offered(&s, "D1:D2", "D1:D4", false), "a formula"); + assert!(!offered(&s, "E1:E2", "E1:E4", false), "empty cells"); +} + #[test] fn only_a_number_in_a_date_format_offers_the_date_fills() { let mut s = s(); diff --git a/crates/ui-egui/src/grid.rs b/crates/ui-egui/src/grid.rs index 2f9a1ba6e..581dda80b 100644 --- a/crates/ui-egui/src/grid.rs +++ b/crates/ui-egui/src/grid.rs @@ -157,6 +157,9 @@ pub struct GridState { pub context_menu_frame: u64, /// After a right-drag of the fill handle: the source, the dragged range and where to open the menu. pub fill_menu: Option<(RangeRef, RangeRef, Pos2)>, + /// The trends the fill menu lists, cached per (doc uid, revision, sheet, source, dragged range): + /// finding them reads every source cell. + pub fill_menu_trends: Option<((u64, u64, usize, RangeRef, RangeRef), Vec<(&'static str, &'static str)>)>, /// After a left-drag of the fill handle: the Auto Fill Options button beside the filled cells. pub fill_tag: Option, /// The right-clicked chart, picture, shape or slicer: where to open its menu, its kind and id. @@ -3553,6 +3556,25 @@ fn fill_modes(app: &SheetApp, src: RangeRef) -> Vec<(&'static str, &'static str) FILL_MODES.into_iter().chain(DATE_FILL_MODES.into_iter().filter(|_| dates)).collect() } +/// Linear Trend and Growth Trend, which the right-drag fill menu adds after the other fill modes +/// when they apply to a fill from `src` to `target` on the active sheet. +fn trend_fill_modes(app: &mut SheetApp, src: RangeRef, target: RangeRef) -> Vec<(&'static str, &'static str)> { + let Some(d) = app.session.active() else { return Vec::new() }; + let key = (d.uid, d.revision, d.wb.active_sheet(), src, target); + if let Some((k, modes)) = &app.grid.fill_menu_trends + && *k == key + { + return modes.clone(); + } + let modes: Vec<(&'static str, &'static str)> = [("Linear Trend", "linearTrend", false), ("Growth Trend", "growthTrend", true)] + .into_iter() + .filter(|(_, _, growth)| gridcraft_engine::fill::trend_applies(&d.wb, d.wb.active_sheet(), src, target, *growth)) + .map(|(label, mode, _)| (label, mode)) + .collect(); + app.grid.fill_menu_trends = Some((key, modes.clone())); + modes +} + /// Remembers the fill just made so the Auto Fill Options button can offer the other ways. fn set_fill_tag(app: &mut SheetApp, src: RangeRef, target: RangeRef) { app.grid.fill_tag = @@ -3636,6 +3658,7 @@ fn fill_menu(app: &mut SheetApp, ui: &mut egui::Ui, was_open: bool) { let Some((src, target, at)) = app.grid.fill_menu else { return }; let mut close = false; let mut items = fill_modes(app, src); + items.extend(trend_fill_modes(app, src, target)); items.extend([("-", ""), ("Series…", "ui:series")]); let response = egui::Area::new(egui::Id::unique("fill_menu")).fixed_pos(at).order(egui::Order::Foreground).show(ui.ctx(), |ui| { egui::Frame::popup(ui.style()).show(ui, |ui| { diff --git a/crates/ui-egui/tests/it/fill_handle_right_drag.rs b/crates/ui-egui/tests/it/fill_handle_right_drag.rs index d8ffbff9a..54d45bf7a 100644 --- a/crates/ui-egui/tests/it/fill_handle_right_drag.rs +++ b/crates/ui-egui/tests/it/fill_handle_right_drag.rs @@ -1,6 +1,7 @@ //! Dragging the fill handle with the right button fills nothing on release: it opens Excel's fill -//! menu (Copy Cells, Fill Series, Fill Formatting Only, Fill Without Formatting, Series…, and from -//! a date Fill Days, Fill Weekdays, Fill Months and Fill Years). +//! menu (Copy Cells, Fill Series, Fill Formatting Only, Fill Without Formatting, Series…, from a +//! date Fill Days, Fill Weekdays, Fill Months and Fill Years, and from numbers Linear Trend and +//! Growth Trend). use egui::{Event, Key, Modifiers, PointerButton, Pos2, vec2}; use egui_kittest::kittest::Queryable; @@ -224,6 +225,42 @@ fn a_number_gets_no_date_fills() { } } +#[test] +fn growth_trend_multiplies_and_linear_trend_adds() { + let mut h = harness(one_two); + drag_handle(&mut h, "B2", "B5", PointerButton::Secondary); + h.get_by_label("Growth Trend").click(); + h.run_steps(3); + assert_eq!(values(&h, &["B1", "B2", "B3", "B4", "B5"]), [n(1.0), n(2.0), n(4.0), n(8.0), n(16.0)]); + assert!(h.state().grid.fill_menu.is_none()); + assert_eq!(selection(&h), "B1:B5"); + + let mut h = harness(one_two); + drag_handle(&mut h, "B2", "B5", PointerButton::Secondary); + h.get_by_label("Linear Trend").click(); + h.run_steps(3); + assert_eq!(values(&h, &["B3", "B4", "B5"]), [n(3.0), n(4.0), n(5.0)]); +} + +#[test] +fn text_and_mixed_signs_leave_out_the_trends() { + let mut h = harness(|s| { + s.execute("range.setValues", json!({"range": "B1", "values": [["Item 1"], ["Item 2"]]})).unwrap(); + s.execute("selection.set", json!({"range": "B1:B2"})).unwrap(); + }); + drag_handle(&mut h, "B2", "B4", PointerButton::Secondary); + assert!(h.query_by_label("Fill Series").is_some()); + assert!(h.query_by_label("Linear Trend").is_none() && h.query_by_label("Growth Trend").is_none()); + + let mut h = harness(|s| { + s.execute("range.setValues", json!({"range": "B1", "values": [[-1], [2]]})).unwrap(); + s.execute("selection.set", json!({"range": "B1:B2"})).unwrap(); + }); + drag_handle(&mut h, "B2", "B4", PointerButton::Secondary); + assert!(h.query_by_label("Linear Trend").is_some()); + assert!(h.query_by_label("Growth Trend").is_none()); +} + #[test] fn escape_mid_right_drag_cancels_it() { let mut h = harness(|s| { diff --git a/docs/ui-parity.md b/docs/ui-parity.md index f35899236..481e71bb9 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-25 · **Change:** minor (Linear Trend and Growth Trend in the right-drag fill menu; AutoSum over a selected row puts its total to the right) · **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 @@ -52,7 +52,7 @@ this logic, with one undo step. | Click/drag/Shift/Ctrl selection, multi-area selection | rectangular drag works in one direction only in some cases (#28) | | Cursor while dragging cells, headers, freeze handles and objects | stable for the active drag (#936); Draw tools keep their crosshair; header arrows and a custom cell cursor remain unimplemented | | 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; month patterns use the workbook's 1900 or 1904 date system); right-drag menu partial: Copy Cells, Fill Series, Fill Formatting Only, Fill Without Formatting, and from a date Fill Days, Fill Weekdays, Fill Months and Fill Years, then Series…; a left-drag leaves an Auto Fill Options button with the same fill choices (gone once the workbook changes or the selection moves); Linear/Growth Trend and Flash Fill missing | +| Fill handle: drag to fill series, double-click to fill down, right-drag menu | fill done (Ctrl+drag swaps copy and series; month patterns use the workbook's 1900 or 1904 date system); right-drag menu partial: Copy Cells, Fill Series, Fill Formatting Only, Fill Without Formatting, from a date Fill Days, Fill Weekdays, Fill Months and Fill Years, and from numbers Linear Trend and Growth Trend, then Series…; a left-drag leaves an Auto Fill Options button with the same fill choices except the trends (gone once the workbook changes or the selection moves); Flash Fill 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; Command/Ctrl-click adds separate arguments with the edit's locale separator, and Shift-click extends the current reference from a fixed anchor on the same sheet. Pointer-event regressions cover repeated/reversed selections, manual separators, sheet switches and keyboard continuation. | @@ -187,6 +187,7 @@ scrollbar bugs 2–4 · pixel/feel pass against observed Excel 7–12. | Date | Change | Summary | |---|---|---| +| 2026-10-25 | minor | The right-drag fill menu offers Linear Trend and Growth Trend when every source cell holds a number (`edit.autoFill` modes `linearTrend` and `growthTrend`). The targets continue the least-squares line (y = mx + b) or the exponential curve (y = b·m^x) fitted to each row or column of the source, so 1, 2 continues 3, 4, 5 or 4, 8, 16, and dragging up or left continues the trend backward. The source keeps its values, and a lone number repeats. Growth Trend is offered only when each row or column is all above zero or all below zero; numbers below zero grow away from zero | | 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 2a8cc47a3f5e01c3379f2ed46ea2a6b586b881b2 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Wed, 28 Oct 2026 01:30:43 -0700 Subject: [PATCH 02/16] Fill: the trend menu check reuses numeric_lanes and Pattern::growth trend_applies now calls the same lane reader and growth fit as the fill, so the menu offers Linear Trend and Growth Trend exactly when the fill accepts them. --- crates/engine/src/fill.rs | 19 +------------------ 1 file changed, 1 insertion(+), 18 deletions(-) diff --git a/crates/engine/src/fill.rs b/crates/engine/src/fill.rs index 1340489c0..3bf3991d4 100644 --- a/crates/engine/src/fill.rs +++ b/crates/engine/src/fill.rs @@ -86,24 +86,7 @@ fn numeric_lanes(wb: &Workbook, sheet: usize, src: RangeRef, target: RangeRef) - /// fill from `src` to `target`: every source cell holds a number, and for Growth Trend the numbers /// of each lane are all above zero or all below zero. pub fn trend_applies(wb: &Workbook, sheet: usize, src: RangeRef, target: RangeRef, growth: bool) -> bool { - let Some(sh) = wb.sheet(sheet) else { return false }; - let vertical = fills_vertically(src, target); - let (lanes, len) = if vertical { (src.start.col..=src.end.col, src.height()) } else { (src.start.row..=src.end.row, src.width()) }; - for lane in lanes { - let (mut above, mut below) = (false, false); - for i in 0..len { - let c = if vertical { CellRef::new(src.start.row + i, lane) } else { CellRef::new(lane, src.start.col + i) }; - let Some(n) = sh.cell(c).filter(|cell| cell.formula.is_none() && cell.value.is_number()).and_then(|cell| cell.value.as_f64()) else { - return false; - }; - above |= n > 0.0; - below |= n < 0.0; - if growth && (n == 0.0 || (above && below)) { - return false; - } - } - } - true + numeric_lanes(wb, sheet, src, target).is_some_and(|lanes| !growth || lanes.iter().all(|nums| Pattern::growth(nums).is_some())) } /// Whether a number format shows a calendar date (`YYYY-MM-DD` and `m/d/yyyy h:mm` do; `0 "days"` From 5846f5908144a2bdb1a8b590bb2f303aa4c11b7a Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Wed, 28 Oct 2026 03:17:15 -0700 Subject: [PATCH 03/16] Fill: the least-squares mean does not overflow for numbers near the largest double --- crates/engine/src/fill.rs | 2 +- crates/engine/src/tests.rs | 4 ++++ 2 files changed, 5 insertions(+), 1 deletion(-) diff --git a/crates/engine/src/fill.rs b/crates/engine/src/fill.rs index 3bf3991d4..6040ed89a 100644 --- a/crates/engine/src/fill.rs +++ b/crates/engine/src/fill.rs @@ -533,7 +533,7 @@ impl Pattern { fn least_squares(nums: &[f64]) -> (f64, f64, f64) { let n = nums.len() as f64; let mean_x = (n - 1.0) / 2.0; - let mean_y = nums.iter().sum::() / n; + let mean_y = nums.iter().map(|y| y / n).sum::(); let mut num = 0.0; let mut den = 0.0; for (i, y) in nums.iter().enumerate() { diff --git a/crates/engine/src/tests.rs b/crates/engine/src/tests.rs index 3e6c1a350..ba3db4103 100644 --- a/crates/engine/src/tests.rs +++ b/crates/engine/src/tests.rs @@ -1052,6 +1052,10 @@ fn linear_and_growth_trend_continue_the_fitted_line_or_curve() { fill(&mut s, "S1:S2", "S1:S6", "growthTrend").unwrap(); let Value::Number(s6) = v(&s, "S6") else { panic!("S6 is {:?}", v(&s, "S6")) }; assert!((s6 / 1e300 - 1.0).abs() < 1e-9, "S6 = {s6}"); + // Two numbers near the largest double repeat without their sum overflowing. + s.execute("range.setValues", json!({"range": "T1", "values": [[1e308], [1e308]]})).unwrap(); + fill(&mut s, "T1:T2", "T1:T3", "linearTrend").unwrap(); + assert_eq!(v(&s, "T3"), Value::Number(1e308)); // A lone number repeats, and dates a month apart step by their days, not by months. s.execute("cell.set", json!({"cell": "M1", "input": "7"})).unwrap(); fill(&mut s, "M1", "M1:M2", "linearTrend").unwrap(); From 364e48dcabdaeda2ebad949b78e1fa3be47f8e13 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Thu, 29 Oct 2026 03:22:11 -0700 Subject: [PATCH 04/16] Fill: the trend menu cache has a type alias, as main's clippy settings now require --- crates/ui-egui/src/grid.rs | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/crates/ui-egui/src/grid.rs b/crates/ui-egui/src/grid.rs index e9a633c70..eda0f16db 100644 --- a/crates/ui-egui/src/grid.rs +++ b/crates/ui-egui/src/grid.rs @@ -21,6 +21,8 @@ pub(crate) type PaneQuad = ((u32, u32), (u32, u32), Rect); type PagesCache = ((u64, u64, usize), Vec<(RangeRef, u32)>); /// Cached Show Details cells, keyed by (doc uid, revision, sheet, pivot). type DetailsCache = ((u64, u64, usize, usize), Option>); +/// Cached fill-menu trend entries (label, mode), keyed by (doc uid, revision, sheet, source, dragged range). +pub type FillTrendsCache = ((u64, u64, usize, RangeRef, RangeRef), Vec<(&'static str, &'static str)>); mod cell_paint; mod cursor; @@ -197,7 +199,7 @@ pub struct GridState { pub fill_menu: Option<(RangeRef, RangeRef, Pos2)>, /// The trends the fill menu lists, cached per (doc uid, revision, sheet, source, dragged range): /// finding them reads every source cell. - pub fill_menu_trends: Option<((u64, u64, usize, RangeRef, RangeRef), Vec<(&'static str, &'static str)>)>, + pub fill_menu_trends: Option, /// After a left-drag of the fill handle: the Auto Fill Options button beside the filled cells. pub fill_tag: Option, /// The right-clicked chart, picture, shape or slicer: where to open its menu, its kind and id. From 53228adb7d56da0f95a95a5cb3d33d75191df80c Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Thu, 29 Oct 2026 04:43:54 -0700 Subject: [PATCH 05/16] Fill: Linear Trend fits numbers near the largest double without overflowing When a source number is larger than 2^600, least_squares multiplies the numbers by 2^-600 before the fit and multiplies the fitted values and the step by 2^600 afterward. A source of 1e308 four times and then 0 now continues at 2e307; before, the covariance sum overflowed and the target cell showed #NUM!. The test for numbers near the largest double compares to within 1e-9 instead of exactly, since the rounding to 15 digits of 1e308 gives 1.0000000000000004e308 on Linux. --- crates/engine/src/fill.rs | 15 +++++++++++---- crates/engine/src/tests.rs | 11 ++++++++--- 2 files changed, 19 insertions(+), 7 deletions(-) diff --git a/crates/engine/src/fill.rs b/crates/engine/src/fill.rs index 4fdd5b9b9..2f1a98a37 100644 --- a/crates/engine/src/fill.rs +++ b/crates/engine/src/fill.rs @@ -528,20 +528,27 @@ impl Pattern { } } +/// 2^600 and 2^-600, both exact. +const TWO_POW_600: f64 = f64::from_bits((1023 + 600) << 52); +const TWO_POW_MINUS_600: f64 = f64::from_bits((1023 - 600) << 52); + /// The least-squares line through `nums` at positions 0, 1, 2…: its values at the first and last -/// positions, and its step. A lone number gives a step of zero. +/// positions, and its step. A lone number gives a step of zero. When a number is larger than 2^600, +/// the fit runs on the numbers multiplied by 2^-600 and its results are multiplied by 2^600, so the +/// sums stay finite for numbers up to the largest double. fn least_squares(nums: &[f64]) -> (f64, f64, f64) { + let (down, up) = if nums.iter().any(|y| y.abs() > TWO_POW_600) { (TWO_POW_MINUS_600, TWO_POW_600) } else { (1.0, 1.0) }; let n = nums.len() as f64; let mean_x = (n - 1.0) / 2.0; - let mean_y = nums.iter().map(|y| y / n).sum::(); + let mean_y = nums.iter().map(|y| y * down / n).sum::(); let mut num = 0.0; let mut den = 0.0; for (i, y) in nums.iter().enumerate() { - num += (i as f64 - mean_x) * (y - mean_y); + num += (i as f64 - mean_x) * (y * down - mean_y); den += (i as f64 - mean_x).powi(2); } let step = if den == 0.0 { 0.0 } else { num / den }; - (mean_y - step * mean_x, mean_y + step * (n - 1.0 - mean_x), step) + ((mean_y - step * mean_x) * up, (mean_y + step * (n - 1.0 - mean_x)) * up, step * up) } /// Whether `serial` falls on Monday to Friday; `None` outside the supported date range. diff --git a/crates/engine/src/tests.rs b/crates/engine/src/tests.rs index 3bcf559e4..7e99df964 100644 --- a/crates/engine/src/tests.rs +++ b/crates/engine/src/tests.rs @@ -1052,10 +1052,15 @@ fn linear_and_growth_trend_continue_the_fitted_line_or_curve() { fill(&mut s, "S1:S2", "S1:S6", "growthTrend").unwrap(); let Value::Number(s6) = v(&s, "S6") else { panic!("S6 is {:?}", v(&s, "S6")) }; assert!((s6 / 1e300 - 1.0).abs() < 1e-9, "S6 = {s6}"); - // Two numbers near the largest double repeat without their sum overflowing. - s.execute("range.setValues", json!({"range": "T1", "values": [[1e308], [1e308]]})).unwrap(); + // Numbers near the largest double continue their line without a sum overflowing: two equal + // numbers repeat, and 1e308 four times then 0 fit a step of -2e307 and continue at 2e307. + s.execute("range.setValues", json!({"range": "T1", "values": [[1e308, 1e308], [1e308, 1e308], [0, 1e308], [0, 1e308], [0, 0]]})).unwrap(); fill(&mut s, "T1:T2", "T1:T3", "linearTrend").unwrap(); - assert_eq!(v(&s, "T3"), Value::Number(1e308)); + fill(&mut s, "U1:U5", "U1:U6", "linearTrend").unwrap(); + for (cell, want) in [("T3", 1e308), ("U6", 2e307)] { + let Value::Number(got) = v(&s, cell) else { panic!("{cell} is {:?}", v(&s, cell)) }; + assert!((got / want - 1.0).abs() < 1e-9, "{cell} = {got}"); + } // A lone number repeats, and dates a month apart step by their days, not by months. s.execute("cell.set", json!({"cell": "M1", "input": "7"})).unwrap(); fill(&mut s, "M1", "M1:M2", "linearTrend").unwrap(); From 1668d576a8d41c90dfb3d46a32058759528a0027 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Fri, 30 Oct 2026 21:08:10 -0700 Subject: [PATCH 06/16] Fill handle: a trend from a lone number copies it unchanged Linear Trend and Growth Trend from a single number now copy the cell as it is. They used to pass it through the fitted line or the logarithm, which rounded it to 15 digits and moved a value near the largest double (1e308 became 1.00000000000001e308). --- crates/engine/src/fill.rs | 10 ++++++++-- crates/engine/src/tests.rs | 5 +++++ 2 files changed, 13 insertions(+), 2 deletions(-) diff --git a/crates/engine/src/fill.rs b/crates/engine/src/fill.rs index a03dbfe3b..ab2d901bb 100644 --- a/crates/engine/src/fill.rs +++ b/crates/engine/src/fill.rs @@ -322,8 +322,11 @@ enum Pattern { } impl Pattern { - /// Linear Trend: the least-squares line through `nums`. A lone number gives a step of zero. + /// Linear Trend: the least-squares line through `nums`. A lone number is copied unchanged. fn linear(nums: &[f64]) -> Pattern { + if nums.len() == 1 { + return Pattern::Copy; + } let (first, last, step) = least_squares(nums); Pattern::Linear { last, first, step } } @@ -331,7 +334,7 @@ impl Pattern { /// The exponential curve y = b·m^x fitted to `nums` at positions 0, 1, 2… by least squares on /// the logarithms, as the GROWTH function fits positive numbers. Numbers below zero are fitted /// by their magnitudes and keep their sign. `None` when the numbers are not all above zero or - /// all below zero. A lone number gives a factor of one. + /// all below zero. A lone number is copied unchanged. fn growth(nums: &[f64]) -> Option { let sign = if nums.iter().all(|y| *y > 0.0) { 1.0 @@ -340,6 +343,9 @@ impl Pattern { } else { return None; }; + if nums.len() == 1 { + return Some(Pattern::Copy); + } let logs: Vec = nums.iter().map(|y| (y * sign).ln()).collect(); let (first, last, step) = least_squares(&logs); Some(Pattern::Growth { last, first, step, sign }) diff --git a/crates/engine/src/tests.rs b/crates/engine/src/tests.rs index acbb9fbb7..160f48693 100644 --- a/crates/engine/src/tests.rs +++ b/crates/engine/src/tests.rs @@ -1065,6 +1065,11 @@ fn linear_and_growth_trend_continue_the_fitted_line_or_curve() { s.execute("cell.set", json!({"cell": "M1", "input": "7"})).unwrap(); fill(&mut s, "M1", "M1:M2", "linearTrend").unwrap(); assert_eq!(v(&s, "M2"), Value::Number(7.0)); + // It repeats unchanged, with every digit and at any size, by either trend. + s.execute("range.setValues", json!({"range": "V1", "values": [[1e308, 0.12345678901234567]]})).unwrap(); + fill(&mut s, "V1", "V1:V3", "growthTrend").unwrap(); + fill(&mut s, "W1", "W1:W3", "linearTrend").unwrap(); + assert_eq!(nums(&s, &["V2", "V3", "W2", "W3"]), n(&[1e308, 1e308, 0.12345678901234567, 0.12345678901234567])); s.execute("cell.set", json!({"cell": "N1", "input": "1/15/2026"})).unwrap(); s.execute("cell.set", json!({"cell": "N2", "input": "2/15/2026"})).unwrap(); fill(&mut s, "N1:N2", "N1:N3", "linearTrend").unwrap(); From 210b8c9cd68973bdfaa8f3423ef577da5ee684d9 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Fri, 30 Oct 2026 21:12:21 -0700 Subject: [PATCH 07/16] Fill handle: a linear fit of very small numbers keeps them The fitted line sums the numbers before dividing by their count, so the smallest doubles no longer round to zero one by one; three cells of 5e-324 continue at 5e-324 instead of 0. --- crates/engine/src/fill.rs | 2 +- crates/engine/src/tests.rs | 5 +++++ 2 files changed, 6 insertions(+), 1 deletion(-) diff --git a/crates/engine/src/fill.rs b/crates/engine/src/fill.rs index ab2d901bb..2b967a3b6 100644 --- a/crates/engine/src/fill.rs +++ b/crates/engine/src/fill.rs @@ -546,7 +546,7 @@ fn least_squares(nums: &[f64]) -> (f64, f64, f64) { let (down, up) = if nums.iter().any(|y| y.abs() > TWO_POW_600) { (TWO_POW_MINUS_600, TWO_POW_600) } else { (1.0, 1.0) }; let n = nums.len() as f64; let mean_x = (n - 1.0) / 2.0; - let mean_y = nums.iter().map(|y| y * down / n).sum::(); + let mean_y = nums.iter().map(|y| y * down).sum::() / n; let mut num = 0.0; let mut den = 0.0; for (i, y) in nums.iter().enumerate() { diff --git a/crates/engine/src/tests.rs b/crates/engine/src/tests.rs index 160f48693..e6514ac7a 100644 --- a/crates/engine/src/tests.rs +++ b/crates/engine/src/tests.rs @@ -1070,6 +1070,11 @@ fn linear_and_growth_trend_continue_the_fitted_line_or_curve() { fill(&mut s, "V1", "V1:V3", "growthTrend").unwrap(); fill(&mut s, "W1", "W1:W3", "linearTrend").unwrap(); assert_eq!(nums(&s, &["V2", "V3", "W2", "W3"]), n(&[1e308, 1e308, 0.12345678901234567, 0.12345678901234567])); + // The smallest double three times repeats rather than averaging to zero. + let tiny = f64::from_bits(1); + s.execute("range.setValues", json!({"range": "X1", "values": [[tiny], [tiny], [tiny]]})).unwrap(); + fill(&mut s, "X1:X3", "X1:X4", "linearTrend").unwrap(); + assert_eq!(v(&s, "X4"), Value::Number(tiny)); s.execute("cell.set", json!({"cell": "N1", "input": "1/15/2026"})).unwrap(); s.execute("cell.set", json!({"cell": "N2", "input": "2/15/2026"})).unwrap(); fill(&mut s, "N1:N2", "N1:N3", "linearTrend").unwrap(); From b4beded7390bdd631c64b80141b48bf334b7a13f Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Mon, 2 Nov 2026 14:27:54 -0800 Subject: [PATCH 08/16] Fill handle: a Python cell is not a Linear Trend or Growth Trend source --- crates/engine/src/fill.rs | 4 ++-- crates/engine/src/tests/python_cells.rs | 12 ++++++++++++ 2 files changed, 14 insertions(+), 2 deletions(-) diff --git a/crates/engine/src/fill.rs b/crates/engine/src/fill.rs index 70f7f0887..7936d689e 100644 --- a/crates/engine/src/fill.rs +++ b/crates/engine/src/fill.rs @@ -59,7 +59,7 @@ fn fills_vertically(src: RangeRef, target: RangeRef) -> bool { } /// The numbers in each lane of `src` that a fill to `target` continues, or `None` when a source -/// cell is empty or holds text, a logical value, an error or a formula. +/// cell is empty or holds text, a logical value, an error, a formula or Python code. fn numeric_lanes(wb: &Workbook, sheet: usize, src: RangeRef, target: RangeRef) -> Option>> { let sh = wb.sheet(sheet)?; let vertical = fills_vertically(src, target); @@ -72,7 +72,7 @@ fn numeric_lanes(wb: &Workbook, sheet: usize, src: RangeRef, target: RangeRef) - .map(|i| { let c = if vertical { CellRef::new(src.start.row + i, lane) } else { CellRef::new(lane, src.start.col + i) }; let cell = sh.cell(c)?; - if cell.formula.is_some() || !cell.value.is_number() { + if cell.formula.is_some() || cell.py.is_some() || !cell.value.is_number() { return None; } cell.value.as_f64() diff --git a/crates/engine/src/tests/python_cells.rs b/crates/engine/src/tests/python_cells.rs index 63cf1d92b..172440d08 100644 --- a/crates/engine/src/tests/python_cells.rs +++ b/crates/engine/src/tests/python_cells.rs @@ -530,3 +530,15 @@ fn python_code_with_an_empty_value_counts_as_content() { s.execute("edit.copy", json!({"range": "T1"})).unwrap(); assert!(s.execute("edit.paste", json!({"at": "R2"})).is_err_and(|e| e.to_string().contains("part of an array"))); } + +#[test] +fn a_python_cell_is_not_a_trend_source() { + let mut s = s(); + s.execute("cell.set", json!({"cell": "A2", "input": "2"})).unwrap(); + plant(&mut s, 0, "A1", "1"); + let offered = |s: &Session, growth: bool| { + let r = |a: &str| gridcraft_core::RangeRef::parse(a).unwrap(); + crate::fill::trend_applies(&s.doc().unwrap().wb, 0, r("A1:A2"), r("A1:A5"), growth) + }; + assert!(!offered(&s, false) && !offered(&s, true)); +} From 5b6c4a0739899a71102acae9223f7ad4872c7abd Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Tue, 3 Nov 2026 16:28:08 -0800 Subject: [PATCH 09/16] Docs: the fill-handle row lists Linear Trend and Growth Trend --- docs/ui-parity.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/docs/ui-parity.md b/docs/ui-parity.md index 10b6d152d..3132ae0a9 100644 --- a/docs/ui-parity.md +++ b/docs/ui-parity.md @@ -57,7 +57,7 @@ this logic, with one undo step. | Cursor while dragging cells, headers, freeze handles and objects | stable for the active drag (#936); Draw tools keep their crosshair; header arrows and a custom cell cursor remain unimplemented | | 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 | | Highlight the active cell's row (no Excel equivalent; Focus Cell tints the row and the column) | done (11-03): File › Options › General, off by default; a preference for every sheet and workbook, nothing saved in the file. Tints over the fills and under the text, in Normal and Page Layout views (`options.highlightActiveRow`) | -| Fill handle: drag to fill series, double-click to fill down, right-drag menu | fill done (Ctrl+drag swaps copy and series; month patterns use the workbook's 1900 or 1904 date system); right-drag menu partial: Copy Cells, Fill Series, Fill Formatting Only, Fill Without Formatting, and from a date Fill Days, Fill Weekdays, Fill Months and Fill Years, then Series…; a left-drag leaves an Auto Fill Options button with the same fill choices (gone once the workbook changes or the selection moves); Linear/Growth Trend and Flash Fill missing | +| Fill handle: drag to fill series, double-click to fill down, right-drag menu | fill done (Ctrl+drag swaps copy and series; month patterns use the workbook's 1900 or 1904 date system); right-drag menu partial: Copy Cells, Fill Series, Fill Formatting Only, Fill Without Formatting, and from a date Fill Days, Fill Weekdays, Fill Months and Fill Years, and from numbers Linear Trend and Growth Trend, then Series…; a left-drag leaves an Auto Fill Options button with the same fill choices except Linear Trend and Growth Trend (gone once the workbook changes or the selection moves); Flash Fill missing | | Drag-move and drag-copy cells (border drag, Ctrl/Option, Shift to insert) | border drag moves (M3) and asks "There's already data here. Do you want to replace it?" before replacing cells that hold data (`range.move`, #3136); Ctrl/Option to copy and Shift to insert are not wired to the border drag yet (reorder whole columns by their headers instead) | | In-cell editing, Enter/Tab movement, Alt/Option+Enter line breaks | done | | Point mode (click/drag/arrow references), reference colouring, F4 | done; dragging over row or column headers points at whole rows or columns (`A:C`, `2:5`); Command/Ctrl-click adds separate arguments with the edit's locale separator, and Shift-click extends the current reference from a fixed anchor on the same sheet. Pointer-event regressions cover repeated/reversed selections, manual separators, sheet switches and keyboard continuation. | From 6d02203e8fc493531e1ad72befcd5d1c2f50becc Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Thu, 12 Nov 2026 14:22:34 -0800 Subject: [PATCH 10/16] Fill handle: the menu leaves out trends for fills AutoFill refuses fill::trends_that_apply answers for Linear Trend and Growth Trend from one read of the source, checking each cell's number and sign without fitting a line or curve, and the right-drag menu calls it once instead of calling trend_applies for each trend. Both return false, without reading any source cell, when the source or target holds more than MAX_FILL_CELLS cells or the target does not hold the source in a corner, the same checks edit.autoFill applies. New engine tests fill a two-column source down and a two-row source across with each trend and check every value, and check that undo after a Linear Trend fill restores the targets and leaves the source as it was. --- crates/engine/src/fill.rs | 47 ++++++++++++++++++++++++----- crates/engine/src/tests.rs | 51 ++++++++++++++++++++++++++++++++ crates/ui-egui/src/grid/menus.rs | 5 ++-- 3 files changed, 94 insertions(+), 9 deletions(-) diff --git a/crates/engine/src/fill.rs b/crates/engine/src/fill.rs index 4bed7a95e..6f0c7a11b 100644 --- a/crates/engine/src/fill.rs +++ b/crates/engine/src/fill.rs @@ -71,22 +71,55 @@ fn numeric_lanes(wb: &Workbook, sheet: usize, src: RangeRef, target: RangeRef) - (0..len) .map(|i| { let c = if vertical { CellRef::new(src.start.row + i, lane) } else { CellRef::new(lane, src.start.col + i) }; - let cell = sh.cell(c)?; - if cell.formula.is_some() || cell.py.is_some() || !cell.value.is_number() { - return None; - } - cell.value.as_f64() + trend_number(sh, c) }) .collect() }) .collect() } +/// The number a trend fill reads from source cell `c`, or `None` when it is empty or holds text, a +/// logical value, an error, a formula or Python code. +fn trend_number(sh: &gridcraft_model::Sheet, c: CellRef) -> Option { + let cell = sh.cell(c)?; + if cell.formula.is_some() || cell.py.is_some() || !cell.value.is_number() { + return None; + } + cell.value.as_f64() +} + /// Whether the fill menu offers Linear Trend (`growth` false) or Growth Trend (`growth` true) for a /// fill from `src` to `target`: every source cell holds a number, and for Growth Trend the numbers -/// of each lane are all above zero or all below zero. +/// of each lane are all above zero or all below zero. A source or target larger than +/// [`MAX_FILL_CELLS`], or a target that doesn't hold the source in a corner, is refused by +/// `edit.autoFill`, so neither trend applies to it and no source cell is read. pub fn trend_applies(wb: &Workbook, sheet: usize, src: RangeRef, target: RangeRef, growth: bool) -> bool { - numeric_lanes(wb, sheet, src, target).is_some_and(|lanes| !growth || lanes.iter().all(|nums| Pattern::growth(nums).is_some())) + let (linear, growth_fits) = trends_that_apply(wb, sheet, src, target); + if growth { growth_fits } else { linear } +} + +/// [`trend_applies`] for both trends from one read of the source: (Linear Trend, Growth Trend). It +/// checks each cell's number and sign and fits nothing, so the menu does not wait on a fit. +pub fn trends_that_apply(wb: &Workbook, sheet: usize, src: RangeRef, target: RangeRef) -> (bool, bool) { + if src.count() > MAX_FILL_CELLS || target.count() > MAX_FILL_CELLS || !holds_source_in_corner(src, target) { + return (false, false); + } + let Some(sh) = wb.sheet(sheet) else { return (false, false) }; + let vertical = fills_vertically(src, target); + let (lanes, len) = if vertical { (src.start.col..=src.end.col, src.height()) } else { (src.start.row..=src.end.row, src.width()) }; + let mut growth = true; + for lane in lanes { + // Growth Trend needs the lane all above zero or all below zero, as `Pattern::growth` does. + let (mut above, mut below) = (true, true); + for i in 0..len { + let c = if vertical { CellRef::new(src.start.row + i, lane) } else { CellRef::new(lane, src.start.col + i) }; + let Some(y) = trend_number(sh, c) else { return (false, false) }; + above &= y > 0.0; + below &= y < 0.0; + } + growth &= above || below; + } + (true, growth) } /// Whether a number format shows a calendar date (`YYYY-MM-DD` and `m/d/yyyy h:mm` do; `0 "days"` diff --git a/crates/engine/src/tests.rs b/crates/engine/src/tests.rs index 51b590d6a..5a7a6ec83 100644 --- a/crates/engine/src/tests.rs +++ b/crates/engine/src/tests.rs @@ -1143,9 +1143,60 @@ fn trend_fills_are_offered_for_numbers_only() { // Down A1:B2, each column keeps one sign; across it, row 1 holds 1 and -1. assert!(offered(&s, "A1:B2", "A1:B5", true)); assert!(offered(&s, "A1:B2", "A1:E2", false) && !offered(&s, "A1:B2", "A1:E2", true)); + let r = |a: &str| gridcraft_core::RangeRef::parse(a).unwrap(); + assert_eq!(crate::fill::trends_that_apply(&s.doc().unwrap().wb, 0, r("A1:B2"), r("A1:E2")), (true, false)); + assert_eq!(crate::fill::trends_that_apply(&s.doc().unwrap().wb, 0, r("A1:B2"), r("A1:B5")), (true, true)); assert!(!offered(&s, "C1:C2", "C1:C4", false), "text"); assert!(!offered(&s, "D1:D2", "D1:D4", false), "a formula"); assert!(!offered(&s, "E1:E2", "E1:E4", false), "empty cells"); + // A fill `edit.autoFill` refuses is not offered: five columns down to the last row is more than + // MAX_FILL_CELLS cells, and a target that doesn't hold the source in a corner. + s.execute("range.setValues", json!({"range": "F1", "values": [[1, 2, 3, 4, 5], [2, 4, 6, 8, 10]]})).unwrap(); + assert!(offered(&s, "F1:J2", "F1:J1000", false) && offered(&s, "F1:J2", "F1:J1000", true)); + assert!(!offered(&s, "F1:J2", "F1:J1048576", false) && !offered(&s, "F1:J2", "F1:J1048576", true), "too large"); + assert!(!offered(&s, "F1:J2", "F2:J5", false), "source outside the target"); +} + +#[test] +fn trend_fills_fit_each_lane_of_a_two_dimensional_source() { + let mut s = s(); + let nums = |s: &Session, cells: &[&str]| cells.iter().map(|c| v(s, c)).collect::>(); + let n = |xs: &[f64]| xs.iter().map(|x| Value::Number(*x)).collect::>(); + let fill = + |s: &mut Session, src: &str, target: &str, mode: &str| s.execute("edit.autoFill", json!({"source": src, "target": target, "mode": mode})); + // Down: column A holds 1, 2 and column B 10, 20, and one command fits each column on its own. + s.execute("range.setValues", json!({"range": "A1", "values": [[1, 10], [2, 20]]})).unwrap(); + let down = ["A3", "A4", "A5", "B3", "B4", "B5"]; + fill(&mut s, "A1:B2", "A1:B5", "linearTrend").unwrap(); + assert_eq!(nums(&s, &down), n(&[3.0, 4.0, 5.0, 30.0, 40.0, 50.0])); + fill(&mut s, "A1:B2", "A1:B5", "growthTrend").unwrap(); + assert_eq!(nums(&s, &down), n(&[4.0, 8.0, 16.0, 40.0, 80.0, 160.0])); + // Across: row 1 holds 1, 10 and row 2 holds 2, 20, and each row is fitted on its own. + s.execute("range.setValues", json!({"range": "H1", "values": [[1, 10], [2, 20]]})).unwrap(); + let across = ["J1", "K1", "L1", "J2", "K2", "L2"]; + fill(&mut s, "H1:I2", "H1:L2", "linearTrend").unwrap(); + assert_eq!(nums(&s, &across), n(&[19.0, 28.0, 37.0, 38.0, 56.0, 74.0])); + fill(&mut s, "H1:I2", "H1:L2", "growthTrend").unwrap(); + assert_eq!(nums(&s, &across), n(&[100.0, 1000.0, 10000.0, 200.0, 2000.0, 20000.0])); + // The sources keep their values. + assert_eq!(nums(&s, &["A1", "A2", "B1", "B2", "H1", "I1", "H2", "I2"]), n(&[1.0, 2.0, 10.0, 20.0, 1.0, 10.0, 2.0, 20.0])); +} + +#[test] +fn a_trend_fill_undoes_as_one_step() { + let mut s = s(); + let nums = |s: &Session, cells: &[&str]| cells.iter().map(|c| v(s, c)).collect::>(); + s.execute("range.setValues", json!({"range": "A1", "values": [[1, 10], [2, 20]]})).unwrap(); + s.execute("cell.set", json!({"cell": "A4", "input": "99"})).unwrap(); + s.execute("edit.autoFill", json!({"source": "A1:B2", "target": "A1:B5", "mode": "linearTrend"})).unwrap(); + assert_eq!(v(&s, "A4"), Value::Number(4.0)); + s.execute("edit.undo", json!({})).unwrap(); + // The targets are back as they were (empty, and 99 in A4), and the source is unchanged. + assert_eq!( + nums(&s, &["A3", "A4", "A5", "B3", "B4", "B5"]), + [Value::Empty, Value::Number(99.0), Value::Empty, Value::Empty, Value::Empty, Value::Empty] + ); + assert_eq!(nums(&s, &["A1", "A2", "B1", "B2"]), [Value::Number(1.0), Value::Number(2.0), Value::Number(10.0), Value::Number(20.0)]); } #[test] diff --git a/crates/ui-egui/src/grid/menus.rs b/crates/ui-egui/src/grid/menus.rs index c9b2bee1c..4d8e2a9ed 100644 --- a/crates/ui-egui/src/grid/menus.rs +++ b/crates/ui-egui/src/grid/menus.rs @@ -284,9 +284,10 @@ fn trend_fill_modes(app: &mut SheetApp, src: RangeRef, target: RangeRef) -> Vec< { return modes.clone(); } - let modes: Vec<(&'static str, &'static str)> = [("Linear Trend", "linearTrend", false), ("Growth Trend", "growthTrend", true)] + let (linear, growth) = gridcraft_engine::fill::trends_that_apply(&d.wb, d.wb.active_sheet(), src, target); + let modes: Vec<(&'static str, &'static str)> = [("Linear Trend", "linearTrend", linear), ("Growth Trend", "growthTrend", growth)] .into_iter() - .filter(|(_, _, growth)| gridcraft_engine::fill::trend_applies(&d.wb, d.wb.active_sheet(), src, target, *growth)) + .filter(|(_, _, applies)| *applies) .map(|(label, mode, _)| (label, mode)) .collect(); app.grid.fill_menu_trends = Some((key, modes.clone())); From 322cc7e93ae9a93bd0a9de2215958ffc965d8034 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sat, 14 Nov 2026 12:57:38 -0800 Subject: [PATCH 11/16] Fill handle: huge numbers keep every digit in Linear Trend and Fill Series Rounding to 15 significant digits divided by an inexact power of ten, so a number near the largest double came back with a changed 16th digit: three copies of the largest double filled 1.797693134862311e308. The rounding now goes through the number's exact decimal expansion, and a number whose rounding would pass the largest double keeps its value. --- crates/engine/src/fill.rs | 10 +++++++--- crates/engine/src/tests.rs | 5 +++++ 2 files changed, 12 insertions(+), 3 deletions(-) diff --git a/crates/engine/src/fill.rs b/crates/engine/src/fill.rs index 6f0c7a11b..63f45431c 100644 --- a/crates/engine/src/fill.rs +++ b/crates/engine/src/fill.rs @@ -666,13 +666,17 @@ fn add_months_clamped(sys: gridcraft_core::DateSystem, serial: f64, months: i64) serial_from_ymd(sys, year, month, (d.day as i64).min(last as i64)).map(|day| day + serial - serial.floor()) } +/// `x` rounded to 15 significant digits through its exact decimal expansion, so a number that +/// already has 15 or fewer digits comes back unchanged at any size. A number near the largest +/// double whose rounding would pass it keeps its value. fn round15(x: f64) -> f64 { if x == 0.0 || !x.is_finite() { return x; } - let mag = x.abs().log10().floor() as i32; - let p = 10f64.powi(14 - mag); - if !p.is_finite() || p == 0.0 { x } else { (x * p).round() / p } + match format!("{x:.14e}").parse::() { + Ok(r) if r.is_finite() => r, + _ => x, + } } /// `1st Period` → `2nd Period`: an English ordinal ending is rewritten to suit the new number. diff --git a/crates/engine/src/tests.rs b/crates/engine/src/tests.rs index 5a7a6ec83..cc98de3ef 100644 --- a/crates/engine/src/tests.rs +++ b/crates/engine/src/tests.rs @@ -1113,6 +1113,11 @@ fn linear_and_growth_trend_continue_the_fitted_line_or_curve() { s.execute("range.setValues", json!({"range": "X1", "values": [[tiny], [tiny], [tiny]]})).unwrap(); fill(&mut s, "X1:X3", "X1:X4", "linearTrend").unwrap(); assert_eq!(v(&s, "X4"), Value::Number(tiny)); + // Huge numbers three times repeat exactly: the largest double, and one with 14 digits. + let (big, big14) = (f64::MAX, 1.7976931348623e308); + s.execute("range.setValues", json!({"range": "Y1", "values": [[big, big14], [big, big14], [big, big14]]})).unwrap(); + fill(&mut s, "Y1:Z3", "Y1:Z4", "linearTrend").unwrap(); + assert_eq!(nums(&s, &["Y4", "Z4"]), n(&[big, big14])); s.execute("cell.set", json!({"cell": "N1", "input": "1/15/2026"})).unwrap(); s.execute("cell.set", json!({"cell": "N2", "input": "2/15/2026"})).unwrap(); fill(&mut s, "N1:N2", "N1:N3", "linearTrend").unwrap(); From 512bf992f515a26db5a849930f5775ccbd1d5eb7 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sat, 14 Nov 2026 13:03:18 -0800 Subject: [PATCH 12/16] Fill handle: Growth Trend repeats the same number exactly A lane that holds one number repeated went through the logarithm and back, so two cells of 1e300 filled 9.99999999999976e299. Such a lane is now copied unchanged, as a lone number already was. --- crates/engine/src/fill.rs | 4 ++-- crates/engine/src/tests.rs | 4 ++++ 2 files changed, 6 insertions(+), 2 deletions(-) diff --git a/crates/engine/src/fill.rs b/crates/engine/src/fill.rs index 63f45431c..b8b71d11f 100644 --- a/crates/engine/src/fill.rs +++ b/crates/engine/src/fill.rs @@ -382,7 +382,7 @@ impl Pattern { /// The exponential curve y = b·m^x fitted to `nums` at positions 0, 1, 2… by least squares on /// the logarithms, as the GROWTH function fits positive numbers. Numbers below zero are fitted /// by their magnitudes and keep their sign. `None` when the numbers are not all above zero or - /// all below zero. A lone number is copied unchanged. + /// all below zero. A lone number, or the same number repeated, is copied unchanged. fn growth(nums: &[f64]) -> Option { let sign = if nums.iter().all(|y| *y > 0.0) { 1.0 @@ -391,7 +391,7 @@ impl Pattern { } else { return None; }; - if nums.len() == 1 { + if nums.windows(2).all(|w| w.first() == w.last()) { return Some(Pattern::Copy); } let logs: Vec = nums.iter().map(|y| (y * sign).ln()).collect(); diff --git a/crates/engine/src/tests.rs b/crates/engine/src/tests.rs index cc98de3ef..e5c236baf 100644 --- a/crates/engine/src/tests.rs +++ b/crates/engine/src/tests.rs @@ -1118,6 +1118,10 @@ fn linear_and_growth_trend_continue_the_fitted_line_or_curve() { s.execute("range.setValues", json!({"range": "Y1", "values": [[big, big14], [big, big14], [big, big14]]})).unwrap(); fill(&mut s, "Y1:Z3", "Y1:Z4", "linearTrend").unwrap(); assert_eq!(nums(&s, &["Y4", "Z4"]), n(&[big, big14])); + // Growth Trend repeats the same number exactly too, huge, tiny or below zero. + s.execute("range.setValues", json!({"range": "AA1", "values": [[1e300, 1e-300, -0.3], [1e300, 1e-300, -0.3]]})).unwrap(); + fill(&mut s, "AA1:AC2", "AA1:AC4", "growthTrend").unwrap(); + assert_eq!(nums(&s, &["AA4", "AB4", "AC4"]), n(&[1e300, 1e-300, -0.3])); s.execute("cell.set", json!({"cell": "N1", "input": "1/15/2026"})).unwrap(); s.execute("cell.set", json!({"cell": "N2", "input": "2/15/2026"})).unwrap(); fill(&mut s, "N1:N2", "N1:N3", "linearTrend").unwrap(); From 6429399f208845f05f859dfd0b111f0c2ce972d7 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Tue, 17 Nov 2026 18:07:14 -0800 Subject: [PATCH 13/16] Fill: the trend menu walks lanes and checks signs with the fill's helpers trends_that_apply, numeric_lanes and Pattern::growth now share lane_cells and growth_sign, so the right-drag menu and edit.autoFill use one lane walk and one Growth Trend sign rule. --- crates/engine/src/fill.rs | 68 +++++++++++++++++++++------------------ 1 file changed, 37 insertions(+), 31 deletions(-) diff --git a/crates/engine/src/fill.rs b/crates/engine/src/fill.rs index b8b71d11f..f4e365a84 100644 --- a/crates/engine/src/fill.rs +++ b/crates/engine/src/fill.rs @@ -62,20 +62,32 @@ fn fills_vertically(src: RangeRef, target: RangeRef) -> bool { /// cell is empty or holds text, a logical value, an error, a formula or Python code. fn numeric_lanes(wb: &Workbook, sheet: usize, src: RangeRef, target: RangeRef) -> Option>> { let sh = wb.sheet(sheet)?; + lane_cells(src, target).map(|lane| lane.map(|c| trend_number(sh, c)).collect()).collect() +} + +/// The cells of each lane of `src` that a fill to `target` continues: each column when the fill +/// runs down or up the sheet, each row when it runs across. +fn lane_cells(src: RangeRef, target: RangeRef) -> impl Iterator> { let vertical = fills_vertically(src, target); - let lanes: Vec = if vertical { (src.start.col..=src.end.col).collect() } else { (src.start.row..=src.end.row).collect() }; - let len = if vertical { src.height() } else { src.width() }; - lanes - .into_iter() - .map(|lane| { - (0..len) - .map(|i| { - let c = if vertical { CellRef::new(src.start.row + i, lane) } else { CellRef::new(lane, src.start.col + i) }; - trend_number(sh, c) - }) - .collect() - }) - .collect() + let (lanes, len) = if vertical { (src.start.col..=src.end.col, src.height()) } else { (src.start.row..=src.end.row, src.width()) }; + lanes.map(move |lane| (0..len).map(move |i| if vertical { CellRef::new(src.start.row + i, lane) } else { CellRef::new(lane, src.start.col + i) })) +} + +/// The sign Growth Trend fits a lane's numbers by: 1 when they are all above zero, -1 when they +/// are all below zero, and `None` otherwise. +fn growth_sign(nums: impl IntoIterator) -> Option { + let (mut above, mut below) = (true, true); + for y in nums { + above &= y > 0.0; + below &= y < 0.0; + } + if above { + Some(1.0) + } else if below { + Some(-1.0) + } else { + None + } } /// The number a trend fill reads from source cell `c`, or `None` when it is empty or holds text, a @@ -105,19 +117,19 @@ pub fn trends_that_apply(wb: &Workbook, sheet: usize, src: RangeRef, target: Ran return (false, false); } let Some(sh) = wb.sheet(sheet) else { return (false, false) }; - let vertical = fills_vertically(src, target); - let (lanes, len) = if vertical { (src.start.col..=src.end.col, src.height()) } else { (src.start.row..=src.end.row, src.width()) }; let mut growth = true; - for lane in lanes { - // Growth Trend needs the lane all above zero or all below zero, as `Pattern::growth` does. - let (mut above, mut below) = (true, true); - for i in 0..len { - let c = if vertical { CellRef::new(src.start.row + i, lane) } else { CellRef::new(lane, src.start.col + i) }; - let Some(y) = trend_number(sh, c) else { return (false, false) }; - above &= y > 0.0; - below &= y < 0.0; + // The lanes and the sign rule are the ones the fill uses (`numeric_lanes`, `Pattern::growth`). + for lane in lane_cells(src, target) { + let mut missing = false; + let sign = growth_sign(lane.map_while(|c| { + let y = trend_number(sh, c); + missing |= y.is_none(); + y + })); + if missing { + return (false, false); } - growth &= above || below; + growth &= sign.is_some(); } (true, growth) } @@ -384,13 +396,7 @@ impl Pattern { /// by their magnitudes and keep their sign. `None` when the numbers are not all above zero or /// all below zero. A lone number, or the same number repeated, is copied unchanged. fn growth(nums: &[f64]) -> Option { - let sign = if nums.iter().all(|y| *y > 0.0) { - 1.0 - } else if nums.iter().all(|y| *y < 0.0) { - -1.0 - } else { - return None; - }; + let sign = growth_sign(nums.iter().copied())?; if nums.windows(2).all(|w| w.first() == w.last()) { return Some(Pattern::Copy); } From 80897d8bd4a8ea20bbc5988dd56c57de31a99112 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Tue, 17 Nov 2026 20:25:52 -0800 Subject: [PATCH 14/16] i18n: Linear Trend and Growth Trend have a row in every catalog The right-drag fill menu shows both labels through lang.tr, and no catalog had a row for them, so every interface language showed them in English. Each of the 18 catalogs now translates them, and a test checks that none falls back to English. --- crates/ui-egui/src/i18n.rs | 15 +++++++++++++++ crates/ui-egui/src/i18n/cs.rs | 2 ++ crates/ui-egui/src/i18n/de.rs | 2 ++ crates/ui-egui/src/i18n/el.rs | 2 ++ crates/ui-egui/src/i18n/es.rs | 2 ++ crates/ui-egui/src/i18n/fr.rs | 2 ++ crates/ui-egui/src/i18n/it.rs | 2 ++ crates/ui-egui/src/i18n/ja.rs | 2 ++ crates/ui-egui/src/i18n/ko.rs | 2 ++ crates/ui-egui/src/i18n/nl.rs | 2 ++ crates/ui-egui/src/i18n/pl.rs | 2 ++ crates/ui-egui/src/i18n/pt.rs | 2 ++ crates/ui-egui/src/i18n/ro.rs | 2 ++ crates/ui-egui/src/i18n/ru.rs | 2 ++ crates/ui-egui/src/i18n/sr.rs | 2 ++ crates/ui-egui/src/i18n/tr.rs | 2 ++ crates/ui-egui/src/i18n/uk.rs | 2 ++ crates/ui-egui/src/i18n/vi.rs | 2 ++ crates/ui-egui/src/i18n/zh.rs | 2 ++ 19 files changed, 51 insertions(+) diff --git a/crates/ui-egui/src/i18n.rs b/crates/ui-egui/src/i18n.rs index 0ffd0ad09..619b2830c 100644 --- a/crates/ui-egui/src/i18n.rs +++ b/crates/ui-egui/src/i18n.rs @@ -418,6 +418,21 @@ mod tests { } } + /// The right-drag fill menu's Linear Trend and Growth Trend have a row in every catalog, with + /// no English fallback. + #[test] + fn trend_fill_labels_are_translated_in_every_catalog() { + for key in ["Linear Trend", "Growth Trend"] { + assert_eq!(Language::En.tr(key), key); + for language in Language::ALL.into_iter().filter(|l| *l != Language::En) { + let code = language.code(); + let shown = language.translated(key).unwrap_or_else(|| panic!("{code}: no row for {key:?}")); + assert!(!shown.trim().is_empty() && !shown.contains('\n'), "{code}: bad translation of {key:?}: {shown:?}"); + assert_ne!(shown, key, "{code}: the row for {key:?} is still English"); + } + } + } + #[test] fn translations_never_show_the_context_prefix() { // `tr` returns a found translation as it is, so a catalog that keeps `context|` in its diff --git a/crates/ui-egui/src/i18n/cs.rs b/crates/ui-egui/src/i18n/cs.rs index a2d1312be..ee77b01d6 100644 --- a/crates/ui-egui/src/i18n/cs.rs +++ b/crates/ui-egui/src/i18n/cs.rs @@ -3,6 +3,8 @@ /// Returns the Czech translation for `text`, or `None` so callers fall back to English. pub(super) fn translate(text: &str) -> Option<&'static str> { Some(match text { + "Linear Trend" => "Lineární trend", + "Growth Trend" => "Exponenciální trend", "Diagram" => "Diagram", "Decorative Text" => "Ozdobný text", "Paste" => "Vložit", diff --git a/crates/ui-egui/src/i18n/de.rs b/crates/ui-egui/src/i18n/de.rs index fa4303851..9a4f14b5c 100644 --- a/crates/ui-egui/src/i18n/de.rs +++ b/crates/ui-egui/src/i18n/de.rs @@ -4,6 +4,8 @@ /// Returns the German translation for `text`, or `None` so callers fall back to English. pub(super) fn translate(text: &str) -> Option<&'static str> { Some(match text { + "Linear Trend" => "Linearer Trend", + "Growth Trend" => "Exponentieller Trend", "Diagram" => "Schema", "Decorative Text" => "Dekorativer Text", "Paste" => "Einfügen", diff --git a/crates/ui-egui/src/i18n/el.rs b/crates/ui-egui/src/i18n/el.rs index 2a7449fd6..3d97667be 100644 --- a/crates/ui-egui/src/i18n/el.rs +++ b/crates/ui-egui/src/i18n/el.rs @@ -5,6 +5,8 @@ /// Returns the Greek translation for `text`, or `None` so callers fall back to English. pub(super) fn translate(text: &str) -> Option<&'static str> { Some(match text { + "Linear Trend" => "Γραμμική τάση", + "Growth Trend" => "Εκθετική τάση", "Diagram" => "Διάγραμμα", "Decorative Text" => "Διακοσμητικό κείμενο", "Paste" => "Επικόλληση", diff --git a/crates/ui-egui/src/i18n/es.rs b/crates/ui-egui/src/i18n/es.rs index df0fb4384..93375a398 100644 --- a/crates/ui-egui/src/i18n/es.rs +++ b/crates/ui-egui/src/i18n/es.rs @@ -5,6 +5,8 @@ /// Returns the Spanish translation for `text`, or `None` so callers fall back to English. pub(super) fn translate(text: &str) -> Option<&'static str> { Some(match text { + "Linear Trend" => "Tendencia lineal", + "Growth Trend" => "Tendencia geométrica", "Diagram" => "Diagrama", "Decorative Text" => "Texto decorativo", "Paste" => "Pegar", diff --git a/crates/ui-egui/src/i18n/fr.rs b/crates/ui-egui/src/i18n/fr.rs index 31e42afe5..7608927fd 100644 --- a/crates/ui-egui/src/i18n/fr.rs +++ b/crates/ui-egui/src/i18n/fr.rs @@ -3,6 +3,8 @@ /// Returns the French translation for `text`, or `None` so callers fall back to English. pub(super) fn translate(text: &str) -> Option<&'static str> { Some(match text { + "Linear Trend" => "Tendance linéaire", + "Growth Trend" => "Tendance géométrique", "Diagram" => "Diagramme", "Decorative Text" => "Texte décoratif", "Different First Page" => "Première page différente", diff --git a/crates/ui-egui/src/i18n/it.rs b/crates/ui-egui/src/i18n/it.rs index 24fa45c95..f430c8c76 100644 --- a/crates/ui-egui/src/i18n/it.rs +++ b/crates/ui-egui/src/i18n/it.rs @@ -5,6 +5,8 @@ /// Returns the Italian translation for `text`, or `None` so callers fall back to English. pub(super) fn translate(text: &str) -> Option<&'static str> { Some(match text { + "Linear Trend" => "Tendenza lineare", + "Growth Trend" => "Tendenza esponenziale", "Diagram" => "Diagramma", "Decorative Text" => "Testo decorativo", "Paste" => "Incolla", diff --git a/crates/ui-egui/src/i18n/ja.rs b/crates/ui-egui/src/i18n/ja.rs index a659da744..9c85de1ba 100644 --- a/crates/ui-egui/src/i18n/ja.rs +++ b/crates/ui-egui/src/i18n/ja.rs @@ -1027,6 +1027,8 @@ pub(super) const DIALOGS: &[(&str, &str)] = &[ /// Portuguese catalog has no entry for them either). Kept apart so the two catalogs above keep the /// same key set; it never overlaps them. pub(super) const EXTRA: &[(&str, &str)] = &[ + ("Linear Trend", "線形近似"), + ("Growth Trend", "乗算近似"), ("Cut (⌘X)", "切り取り (⌘X)"), ("Copy (⌘C)", "コピー (⌘C)"), ("Bold (⌘B)", "太字 (⌘B)"), diff --git a/crates/ui-egui/src/i18n/ko.rs b/crates/ui-egui/src/i18n/ko.rs index 9d6d3644a..09483b2a3 100644 --- a/crates/ui-egui/src/i18n/ko.rs +++ b/crates/ui-egui/src/i18n/ko.rs @@ -3,6 +3,8 @@ /// Returns the Korean translation for `text`, or `None` so callers fall back to English. pub(super) fn translate(text: &str) -> Option<&'static str> { Some(match text { + "Linear Trend" => "선형 추세", + "Growth Trend" => "지수 추세", "Diagram" => "다이어그램", "Decorative Text" => "장식 텍스트", "Paste" => "붙여넣기", diff --git a/crates/ui-egui/src/i18n/nl.rs b/crates/ui-egui/src/i18n/nl.rs index 44a1b3815..0dd33644d 100644 --- a/crates/ui-egui/src/i18n/nl.rs +++ b/crates/ui-egui/src/i18n/nl.rs @@ -3,6 +3,8 @@ /// Returns the Dutch translation for `text`, or `None` so callers fall back to English. pub(super) fn translate(text: &str) -> Option<&'static str> { Some(match text { + "Linear Trend" => "Lineaire trend", + "Growth Trend" => "Groeitrend", "Diagram" => "Diagram", "Decorative Text" => "Decoratieve tekst", "Paste" => "Plakken", diff --git a/crates/ui-egui/src/i18n/pl.rs b/crates/ui-egui/src/i18n/pl.rs index d232a6e0d..9fcff2467 100644 --- a/crates/ui-egui/src/i18n/pl.rs +++ b/crates/ui-egui/src/i18n/pl.rs @@ -1,6 +1,8 @@ /// Returns the Polish translation for `text`, or `None` so callers fall back to English. pub(super) fn translate(text: &str) -> Option<&'static str> { Some(match text { + "Linear Trend" => "Trend liniowy", + "Growth Trend" => "Trend wykładniczy", "Diagram" => "Diagram", "Decorative Text" => "Tekst ozdobny", "Paste" => "Wklej", diff --git a/crates/ui-egui/src/i18n/pt.rs b/crates/ui-egui/src/i18n/pt.rs index d93054309..f52cf570a 100644 --- a/crates/ui-egui/src/i18n/pt.rs +++ b/crates/ui-egui/src/i18n/pt.rs @@ -4,6 +4,8 @@ /// Returns the Portuguese translation for `text`, or `None` so callers fall back to English. pub(super) fn translate(text: &str) -> Option<&'static str> { Some(match text { + "Linear Trend" => "Tendência Linear", + "Growth Trend" => "Tendência de Crescimento", "Diagram" => "Diagrama", "Decorative Text" => "Texto decorativo", "Paste" => "Colar", diff --git a/crates/ui-egui/src/i18n/ro.rs b/crates/ui-egui/src/i18n/ro.rs index 0876ac50f..b04facf93 100644 --- a/crates/ui-egui/src/i18n/ro.rs +++ b/crates/ui-egui/src/i18n/ro.rs @@ -8,6 +8,8 @@ /// Returns the Romanian translation for `text`, or `None` so callers fall back to English. pub(super) fn translate(text: &str) -> Option<&'static str> { Some(match text { + "Linear Trend" => "Tendință liniară", + "Growth Trend" => "Tendință de creștere", "Diagram" => "Schemă", "Decorative Text" => "Text decorativ", "Paste" => "Lipire", diff --git a/crates/ui-egui/src/i18n/ru.rs b/crates/ui-egui/src/i18n/ru.rs index f422bcb93..48a7f10b4 100644 --- a/crates/ui-egui/src/i18n/ru.rs +++ b/crates/ui-egui/src/i18n/ru.rs @@ -3,6 +3,8 @@ /// Returns the Russian translation for `text`, or `None` so callers fall back to English. pub(super) fn translate(text: &str) -> Option<&'static str> { Some(match text { + "Linear Trend" => "Линейное приближение", + "Growth Trend" => "Экспоненциальное приближение", "Diagram" => "Схема", "Decorative Text" => "Декоративный текст", "Paste" => "Вставить", diff --git a/crates/ui-egui/src/i18n/sr.rs b/crates/ui-egui/src/i18n/sr.rs index fa9d1285a..4212dcef5 100644 --- a/crates/ui-egui/src/i18n/sr.rs +++ b/crates/ui-egui/src/i18n/sr.rs @@ -3,6 +3,8 @@ /// Returns the Serbian translation for `text`, or `None` so callers fall back to English. pub(super) fn translate(text: &str) -> Option<&'static str> { Some(match text { + "Linear Trend" => "Linearni trend", + "Growth Trend" => "Eksponencijalni trend", "Diagram" => "Dijagram", "Decorative Text" => "Ukrasni tekst", "Paste" => "Nalepi", diff --git a/crates/ui-egui/src/i18n/tr.rs b/crates/ui-egui/src/i18n/tr.rs index 35143bf9a..91f5cb85b 100644 --- a/crates/ui-egui/src/i18n/tr.rs +++ b/crates/ui-egui/src/i18n/tr.rs @@ -4,6 +4,8 @@ /// Returns the Turkish translation for `text`, or `None` so callers fall back to English. pub(super) fn translate(text: &str) -> Option<&'static str> { Some(match text { + "Linear Trend" => "Doğrusal Eğilim", + "Growth Trend" => "Büyüme Eğilimi", "Diagram" => "Diyagram", "Decorative Text" => "Dekoratif Metin", "Paste" => "Yapıştır", diff --git a/crates/ui-egui/src/i18n/uk.rs b/crates/ui-egui/src/i18n/uk.rs index 4374cc135..6d3e5e88b 100644 --- a/crates/ui-egui/src/i18n/uk.rs +++ b/crates/ui-egui/src/i18n/uk.rs @@ -3,6 +3,8 @@ /// Returns the Ukrainian translation for `text`, or `None` so callers fall back to English. pub(super) fn translate(text: &str) -> Option<&'static str> { Some(match text { + "Linear Trend" => "Лінійне наближення", + "Growth Trend" => "Експоненційне наближення", "Diagram" => "Схема", "Decorative Text" => "Декоративний текст", "Paste" => "Вставити", diff --git a/crates/ui-egui/src/i18n/vi.rs b/crates/ui-egui/src/i18n/vi.rs index 62462cc4b..ab2b2ff50 100644 --- a/crates/ui-egui/src/i18n/vi.rs +++ b/crates/ui-egui/src/i18n/vi.rs @@ -4,6 +4,8 @@ /// Returns the Vietnamese translation for `text`, or `None` so callers fall back to English. pub(super) fn translate(text: &str) -> Option<&'static str> { Some(match text { + "Linear Trend" => "Xu hướng tuyến tính", + "Growth Trend" => "Xu hướng tăng trưởng", "Diagram" => "Sơ đồ", "Decorative Text" => "Chữ trang trí", "Paste" => "Dán", diff --git a/crates/ui-egui/src/i18n/zh.rs b/crates/ui-egui/src/i18n/zh.rs index e7ff3fc75..1ac64a75d 100644 --- a/crates/ui-egui/src/i18n/zh.rs +++ b/crates/ui-egui/src/i18n/zh.rs @@ -3,6 +3,8 @@ /// Returns the Chinese translation for `text`, or `None` so callers fall back to English. pub(super) fn translate(text: &str) -> Option<&'static str> { Some(match text { + "Linear Trend" => "线性趋势", + "Growth Trend" => "等比趋势", "Diagram" => "图示", "Decorative Text" => "装饰文字", "Paste" => "粘贴", From 1175b54e6593188f74d65400680b3e001e03fb02 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Tue, 24 Nov 2026 23:22:43 -0800 Subject: [PATCH 15/16] Fill: Linear Trend keeps the step of subnormal numbers When every source number is smaller than 2^-600, the least-squares fit runs on the numbers multiplied by 2^600 and scales its results back, so the smallest doubles 1 and 2 times the minimum continue at 3 and 4 times it instead of repeating. --- crates/engine/src/fill.rs | 12 ++++++++++-- crates/engine/src/tests.rs | 4 ++++ 2 files changed, 14 insertions(+), 2 deletions(-) diff --git a/crates/engine/src/fill.rs b/crates/engine/src/fill.rs index f4e365a84..41f94d466 100644 --- a/crates/engine/src/fill.rs +++ b/crates/engine/src/fill.rs @@ -596,9 +596,17 @@ const TWO_POW_MINUS_600: f64 = f64::from_bits((1023 - 600) << 52); /// The least-squares line through `nums` at positions 0, 1, 2…: its values at the first and last /// positions, and its step. A lone number gives a step of zero. When a number is larger than 2^600, /// the fit runs on the numbers multiplied by 2^-600 and its results are multiplied by 2^600, so the -/// sums stay finite for numbers up to the largest double. +/// sums stay finite for numbers up to the largest double. When every number is smaller than 2^-600, +/// the fit runs on the numbers multiplied by 2^600 and its results are multiplied by 2^-600, so +/// subnormal numbers keep their step instead of rounding it to zero. fn least_squares(nums: &[f64]) -> (f64, f64, f64) { - let (down, up) = if nums.iter().any(|y| y.abs() > TWO_POW_600) { (TWO_POW_MINUS_600, TWO_POW_600) } else { (1.0, 1.0) }; + let (down, up) = if nums.iter().any(|y| y.abs() > TWO_POW_600) { + (TWO_POW_MINUS_600, TWO_POW_600) + } else if nums.iter().all(|y| y.abs() < TWO_POW_MINUS_600) { + (TWO_POW_600, TWO_POW_MINUS_600) + } else { + (1.0, 1.0) + }; let n = nums.len() as f64; let mean_x = (n - 1.0) / 2.0; let mean_y = nums.iter().map(|y| y * down).sum::() / n; diff --git a/crates/engine/src/tests.rs b/crates/engine/src/tests.rs index 949568a64..676339ddc 100644 --- a/crates/engine/src/tests.rs +++ b/crates/engine/src/tests.rs @@ -1343,6 +1343,10 @@ fn linear_and_growth_trend_continue_the_fitted_line_or_curve() { s.execute("range.setValues", json!({"range": "X1", "values": [[tiny], [tiny], [tiny]]})).unwrap(); fill(&mut s, "X1:X3", "X1:X4", "linearTrend").unwrap(); assert_eq!(v(&s, "X4"), Value::Number(tiny)); + // The two smallest doubles continue their step: 1 and 2 times the smallest give 3 and 4 times it. + s.execute("range.setValues", json!({"range": "AD1", "values": [[tiny], [f64::from_bits(2)]]})).unwrap(); + fill(&mut s, "AD1:AD2", "AD1:AD4", "linearTrend").unwrap(); + assert_eq!(nums(&s, &["AD3", "AD4"]), n(&[f64::from_bits(3), f64::from_bits(4)])); // Huge numbers three times repeat exactly: the largest double, and one with 14 digits. let (big, big14) = (f64::MAX, 1.7976931348623e308); s.execute("range.setValues", json!({"range": "Y1", "values": [[big, big14], [big, big14], [big, big14]]})).unwrap(); From c41535a75c35ad57e51f610db59d26e804736b31 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Tue, 24 Nov 2026 23:29:26 -0800 Subject: [PATCH 16/16] Fill: rounding a filled number to 15 digits no longer allocates round15 returns a whole number below 10^15 as it is and writes other numbers to a stack buffer instead of a String, so a large fill does not allocate for each cell. The results are the same bit for bit. --- crates/engine/src/fill.rs | 33 +++++++++++++++++++++++++++++---- 1 file changed, 29 insertions(+), 4 deletions(-) diff --git a/crates/engine/src/fill.rs b/crates/engine/src/fill.rs index 41f94d466..a43fa6e81 100644 --- a/crates/engine/src/fill.rs +++ b/crates/engine/src/fill.rs @@ -682,13 +682,23 @@ fn add_months_clamped(sys: gridcraft_core::DateSystem, serial: f64, months: i64) /// `x` rounded to 15 significant digits through its exact decimal expansion, so a number that /// already has 15 or fewer digits comes back unchanged at any size. A number near the largest -/// double whose rounding would pass it keeps its value. +/// double whose rounding would pass it keeps its value. A whole number below 10^15 is returned +/// as it is, and other numbers are written to a buffer on the stack, so a fill does not allocate +/// for each cell. fn round15(x: f64) -> f64 { - if x == 0.0 || !x.is_finite() { + use std::io::Write; + if x == 0.0 || !x.is_finite() || (x.fract() == 0.0 && x.abs() < 1e15) { return x; } - match format!("{x:.14e}").parse::() { - Ok(r) if r.is_finite() => r, + // "-1.23456789012345e-308" is the longest expansion: 22 bytes. + let mut buf = [0u8; 32]; + let mut out = &mut buf[..]; + if write!(out, "{x:.14e}").is_err() { + return x; + } + let len = 32 - out.len(); + match buf.get(..len).and_then(|b| std::str::from_utf8(b).ok()).and_then(|s| s.parse::().ok()) { + Some(r) if r.is_finite() => r, _ => x, } } @@ -981,6 +991,21 @@ mod tests { assert_eq!(sh.value(CellRef::new(1, 1)), Value::from("03/12/2023")); } + #[test] + fn round15_matches_the_decimal_expansion_without_allocating() { + let by_string = |x: f64| match format!("{x:.14e}").parse::() { + Ok(r) if r.is_finite() => r, + _ => x, + }; + let tiny = f64::from_bits(1); + let whole = [1.0, -7.0, 999_999_999_999_999.0, 1e15, 1e15 + 1.0, 123_456_789_012_345_680.0]; + let other = [0.1 + 0.2, -1.0 / 3.0, tiny, -tiny, 1e-308, f64::MAX, -f64::MAX, 1.7976931348623e308]; + for x in whole.into_iter().chain(other) { + assert_eq!(round15(x).to_bits(), by_string(x).to_bits(), "{x:e}"); + } + assert_eq!(round15(-0.0).to_bits(), (-0.0f64).to_bits()); + } + #[test] fn series_keeps_value_equal_to_stop_after_float_drift() { let mut s = crate::Session::new();