diff --git a/crates/engine/src/cmd/data.rs b/crates/engine/src/cmd/data.rs index 0906f4893..489ca15fb 100644 --- a/crates/engine/src/cmd/data.rs +++ b/crates/engine/src/cmd/data.rs @@ -31,9 +31,9 @@ use sort::{quick_sort, sort}; #[cfg(test)] use tools::split_delimited; use tools::{remove_duplicates, text_to_columns}; +pub(super) use validation::{Rule, move_rule_formula, moved_rule_parts, remove_rule_cells, remove_validation_cells}; pub use validation::{check_validation, list_items}; use validation::{circle_invalid, validate_cmd, validation}; -pub(super) use validation::{move_rule_formula, remove_validation_cells}; pub fn specs() -> Vec { vec![ diff --git a/crates/engine/src/cmd/data/validation.rs b/crates/engine/src/cmd/data/validation.rs index 2217a372a..cadf986d8 100644 --- a/crates/engine/src/cmd/data/validation.rs +++ b/crates/engine/src/cmd/data/validation.rs @@ -37,21 +37,69 @@ fn subtract_range(r: RangeRef, cut: &RangeRef) -> Vec { out } +/// A conditional format or validation: ranges, and formulas written for their top-left cell. +pub(in super::super) trait Rule: Clone { + fn parts(&mut self) -> (&mut Vec, Vec<&mut String>); +} + +impl Rule for Validation { + fn parts(&mut self) -> (&mut Vec, Vec<&mut String>) { + let Validation { ranges, f1, f2, .. } = self; + (ranges, std::iter::once(f1).chain(f2.as_mut()).collect()) + } +} + +impl Rule for gridcraft_model::CondFormat { + fn parts(&mut self) -> (&mut Vec, Vec<&mut String>) { + (&mut self.ranges, self.rule.relative_formulas_mut()) + } +} + /// Removes the cells of `cuts` from every validation, keeping the rest of each rule's ranges. /// When the rule's top-left cell goes, its relative formulas are rewritten for the new top-left /// cell, so the cells left keep checking the same cells. pub(in super::super) fn remove_validation_cells(validations: &mut Vec, cuts: &[RangeRef]) { - for dv in validations.iter_mut() { - let before = RangeRef::top_left(&dv.ranges); + remove_rule_cells(validations, cuts); +} + +/// [`remove_validation_cells`] for any kind of rule. +pub(in super::super) fn remove_rule_cells(rules: &mut Vec, cuts: &[RangeRef]) { + for rule in rules.iter_mut() { + let (ranges, formulas) = rule.parts(); + let before = RangeRef::top_left(ranges); for cut in cuts { - dv.ranges = dv.ranges.iter().flat_map(|r| subtract_range(*r, cut)).collect(); + *ranges = ranges.iter().flat_map(|r| subtract_range(*r, cut)).collect(); } - if let (Some(from), Some(to)) = (before, RangeRef::top_left(&dv.ranges)) { - dv.f1 = move_rule_formula(&dv.f1, from, to); - dv.f2 = dv.f2.take().map(|f| move_rule_formula(&f, from, to)); + if let (Some(from), Some(to)) = (before, RangeRef::top_left(ranges)) { + for f in formulas { + *f = move_rule_formula(f, from, to); + } } } - validations.retain(|d| !d.ranges.is_empty()); + rules.retain_mut(|r| !r.parts().0.is_empty()); +} + +/// The parts of `rules` inside `block`, moved to the block at `to`, as a cut takes them with +/// its cells. Each part's formulas stay written for where its top-left cell was, as a cut +/// cell's formula is copied: the reference rewrite for the move then shifts them. +pub(in super::super) fn moved_rule_parts(rules: &[T], block: RangeRef, to: CellRef) -> Vec { + let dr = i64::from(to.row) - i64::from(block.start.row); + let dc = i64::from(to.col) - i64::from(block.start.col); + let mut out = Vec::new(); + for rule in rules { + let mut part = rule.clone(); + let (ranges, formulas) = part.parts(); + let Some(first) = RangeRef::top_left(ranges) else { continue }; + let inside: Vec = ranges.iter().filter_map(|r| r.intersection(&block)).collect(); + let Some(from) = RangeRef::top_left(&inside) else { continue }; + let moved: Vec = inside.iter().filter_map(|r| Some(RangeRef::new(r.start.offset(dr, dc)?, r.end.offset(dr, dc)?))).collect(); + for f in formulas { + *f = move_rule_formula(f, first, from); + } + *ranges = moved; + out.push(part); + } + out } pub(super) fn validation(s: &mut Session, p: &Json) -> Result { diff --git a/crates/engine/src/cmd/edit.rs b/crates/engine/src/cmd/edit.rs index 83133c01c..e6af5557d 100644 --- a/crates/engine/src/cmd/edit.rs +++ b/crates/engine/src/cmd/edit.rs @@ -35,7 +35,7 @@ use go_to::go_to_special; #[cfg(test)] use go_to::{GO_TO_MAX_AREAS, GO_TO_RECENT, reference_parts}; use paste_special::paste_special; -pub(crate) use paste_special::{rewrite_all_formulas, rewrite_cell_links, rewrite_python_refs}; +pub(crate) use paste_special::{rewrite_all_formulas, rewrite_python_refs}; use selection::{select_all, select_col, select_region, select_row, selection_move, selection_next, selection_next_corner, selection_set}; pub fn specs() -> Vec { diff --git a/crates/engine/src/cmd/edit/paste_special.rs b/crates/engine/src/cmd/edit/paste_special.rs index a19bceb67..350557400 100644 --- a/crates/engine/src/cmd/edit/paste_special.rs +++ b/crates/engine/src/cmd/edit/paste_special.rs @@ -278,7 +278,7 @@ pub(super) fn paste_special(s: &mut Session, p: &Json) -> Result { } } // The copied cell's validation rule replaces whatever rule the destination had. - if !link && matches!(what, What::All | What::AllExceptBorders | What::Validation) { + if !link && !cut_move && matches!(what, What::All | What::AllExceptBorders | What::Validation) { let rule = src_sheet.validations.iter().find(|dv| dv.ranges.iter().any(|r| r.contains(sc))).cloned(); let sh = cx.sheet_mut(dest_sheet)?; crate::cmd::data::remove_validation_cells(&mut sh.validations, &[RangeRef::new(dest, dest)]); @@ -321,6 +321,7 @@ pub(super) fn paste_special(s: &mut Session, p: &Json) -> Result { // Merged areas inside the copied block travel with it. copy_merges(cx, dest_sheet, src_sheet, src, at, what, transpose)?; if cut_move { + move_cut_rules(cx, src_sheet, (clip.sheet, dest_sheet), src, at)?; // References elsewhere to the moved block now point to its new place. let dest_name = cx.wb.sheet(dest_sheet).map(|s| s.name.clone()).unwrap_or_default(); let e = if dest_sheet == clip.sheet { @@ -351,76 +352,70 @@ pub(super) fn paste_special(s: &mut Session, p: &Json) -> Result { Ok(json!({"pasted": s.doc()?.selection.a1()})) } -/// Applies a reference adjustment to every cell formula and defined name in the workbook. -pub(crate) fn rewrite_all_formulas(wb: &mut gridcraft_model::Workbook, target: &str, e: &gridcraft_formula::adjust::Edit) -> Result<()> { - use gridcraft_formula::adjust::Edit; - // Rows and columns inserted or deleted on the target sheet move its legacy array ranges too - // (a cut moves its arrays itself). - let moves_arrays = matches!(e, Edit::Insert { .. } | Edit::Delete { .. } | Edit::InsertCells { .. } | Edit::DeleteCells { .. }); - for si in 0..wb.sheets.len() { - let host = wb.sheets.get(si).map(|s| s.name.clone()).unwrap_or_default(); - let keys: Vec<(CellRef, std::sync::Arc)> = - wb.sheets.get(si).map(|s| s.cells.iter().filter_map(|(c, cell)| cell.formula.clone().map(|f| (c, f))).collect()).unwrap_or_default(); - if keys.is_empty() { - continue; - } - let on_target = moves_arrays && host.eq_ignore_ascii_case(target); - let Some(sheet) = wb.sheet_mut(si) else { continue }; - for (c, f) in keys { - let Some(expr) = f.expr() else { continue }; - let new = gridcraft_formula::adjust::adjust(expr, &host, target, e); - let text = gridcraft_formula::print(&new); - let array = match f.array { - Some(a) if on_target => crate::cmd::sheet::map_range(a, e), - a => a, - }; - if (text != f.text || array != f.array) - && let Some(cell) = sheet.cells.get_mut(c) - { - let mut nf = Formula::from_expr(new); - nf.array = array; - nf.dynamic = f.dynamic; - cell.formula = Some(std::sync::Arc::new(nf)); - } - } - } - for n in wb.names.iter_mut() { - if let Ok(expr) = gridcraft_formula::parse_name(&n.formula) { - // Names are workbook-level: unqualified refs don't occur; qualified ones adjust. - let new = gridcraft_formula::adjust::adjust(expr, "\u{0}", target, e); - n.formula = gridcraft_formula::print(&new); - } - } - rewrite_cell_links(wb, |host, expr| gridcraft_formula::adjust::adjust(expr, host, target, e)); - rewrite_python_refs(wb, &|host, expr| gridcraft_formula::adjust::adjust(expr, host, target, e)) -} - -/// Runs `f` over every reference a floating object holds (a chart's series values, categories, -/// name and bubble sizes, and the source block it was made from). Every edit that moves -/// references calls it: inserting and deleting lines and cells and cut-moves (through -/// [`rewrite_all_formulas`]), and renaming and deleting sheets. `f` maps a reference held by an -/// object on the sheet named `host` to its new form; text that does not parse is kept. A source -/// block that no longer exists is dropped. -pub(crate) fn rewrite_cell_links(wb: &mut gridcraft_model::Workbook, f: impl Fn(&str, gridcraft_formula::Expr) -> gridcraft_formula::Expr) { - for si in 0..wb.sheets.len() { - let Some(host) = wb.sheets.get(si).filter(|s| !s.charts.is_empty()).map(|s| s.name.clone()) else { continue }; - let Some(sh) = wb.sheet_mut(si) else { continue }; - let fix = |text: &str| -> String { - match gridcraft_formula::parse(text) { - Ok(expr) => gridcraft_formula::print(&f(&host, expr)), - Err(_) => text.to_string(), +/// A cut takes its cells' conditional formats and validation with it, from sheet `from` to the +/// block at `at` on sheet `to`, replacing the rules there. The moved parts' formulas are handled +/// as the cut cells' are: kept written for where their cells were (on another sheet, with +/// their references to it named), so the reference rewrite for the move shifts those into the +/// block once. `snapshot` is the source sheet as it was cut. +fn move_cut_rules(cx: &mut crate::cmd::Ctx, snapshot: &gridcraft_model::Sheet, (from, to): (usize, usize), src: RangeRef, at: CellRef) -> Result<()> { + use crate::cmd::data::Rule; + let mut cfs = crate::cmd::data::moved_rule_parts(&snapshot.cond_formats, src, at); + let mut dvs = crate::cmd::data::moved_rule_parts(&snapshot.validations, src, at); + if from != to { + let name = |t: &mut String| { + if let Ok(e) = gridcraft_formula::parse(t.trim_start_matches('=')) { + let e = e.map(&mut |x| match x { + gridcraft_formula::Expr::Ref(mut r) if r.sheet == gridcraft_formula::SheetSel::Current => { + r.sheet = gridcraft_formula::SheetSel::Named(snapshot.name.clone()); + gridcraft_formula::Expr::Ref(r) + } + other => other, + }); + *t = format!("{}{}", if t.starts_with('=') { "=" } else { "" }, gridcraft_formula::print(&e)); } }; - for ch in sh.charts.iter_mut() { - ch.source = ch.source.as_deref().map(fix).filter(|s| !s.contains("#REF!")); - for se in ch.series.iter_mut() { - se.values = fix(&se.values); - se.categories = se.categories.as_deref().map(fix); - se.name = se.name.as_deref().map(fix); - se.bubble_sizes = se.bubble_sizes.as_deref().map(fix); + cfs.iter_mut().flat_map(|r| r.parts().1).for_each(name); + dvs.iter_mut().flat_map(|r| r.parts().1).for_each(name); + } + let source = cx.sheet_mut(from)?; + crate::cmd::data::remove_rule_cells(&mut source.cond_formats, &[src]); + crate::cmd::data::remove_rule_cells(&mut source.validations, &[src]); + let block = RangeRef::new(at, at.offset_clamped(i64::from(src.height()) - 1, i64::from(src.width()) - 1)); + let dest = cx.sheet_mut(to)?; + crate::cmd::data::remove_rule_cells(&mut dest.cond_formats, &[block]); + crate::cmd::data::remove_rule_cells(&mut dest.validations, &[block]); + dest.cond_formats.extend(cfs); + dest.validations.extend(dvs); + Ok(()) +} + +/// Applies a reference adjustment to every reference the workbook holds +/// ([`Workbook::rewrite_references`]: formulas, names, conditional formats, validation, links, +/// charts, sparklines, PivotTable sources) and its Python cells, and moves the legacy array +/// ranges on `target`. +/// +/// [`Workbook::rewrite_references`]: gridcraft_model::Workbook::rewrite_references +pub(crate) fn rewrite_all_formulas(wb: &mut gridcraft_model::Workbook, target: &str, e: &gridcraft_formula::adjust::Edit) -> Result<()> { + use gridcraft_formula::adjust::Edit; + wb.rewrite_references(&|host, expr| gridcraft_formula::adjust::adjust(expr, host.name, target, e)); + // Rows and columns inserted or deleted on the target sheet move its legacy array ranges too + // (a cut moves its arrays itself). + if matches!(e, Edit::Insert { .. } | Edit::Delete { .. } | Edit::InsertCells { .. } | Edit::DeleteCells { .. }) + && let Some(si) = wb.sheet_index(target) + && let Some(sheet) = wb.sheet_mut(si) + { + let arrays: Vec<(CellRef, std::sync::Arc)> = + sheet.cells.iter().filter_map(|(c, cell)| cell.formula.clone().filter(|f| f.array.is_some()).map(|f| (c, f))).collect(); + for (c, f) in arrays { + let array = f.array.and_then(|a| crate::cmd::sheet::map_range(a, e)); + if array != f.array + && let Some(cell) = sheet.cells.get_mut(c) + { + cell.formula = Some(std::sync::Arc::new(Formula { array, ..(*f).clone() })); } } } + rewrite_python_refs(wb, &|host, expr| gridcraft_formula::adjust::adjust(expr, host, target, e)) } /// Rewrites the `xl("…")` literals in every Python cell with `f`, which maps a reference held on diff --git a/crates/engine/src/cmd/formulas.rs b/crates/engine/src/cmd/formulas.rs index d72f814a1..457821264 100644 --- a/crates/engine/src/cmd/formulas.rs +++ b/crates/engine/src/cmd/formulas.rs @@ -1,7 +1,7 @@ //! Formulas tab: AutoSum, Insert Function, names, auditing, calculation. use gridcraft_core::{CellError, CellRef, RangeRef, Value}; -use gridcraft_model::{CalcMode, Cell, DefinedName, Formula, Workbook}; +use gridcraft_model::{CalcMode, Cell, DefinedName, Workbook}; use serde_json::{Value as Json, json}; use super::{ @@ -407,7 +407,7 @@ fn define_name(s: &mut Session, p: &Json) -> Result { if let Some((old_name, old_scope)) = &old { cx.wb.names.retain(|n| !(n.name.eq_ignore_ascii_case(old_name) && n.scope == *old_scope)); if !old_name.eq_ignore_ascii_case(&name) { - rename_name_in_formulas(&mut cx.wb, old_name, *old_scope, &name); + rename_name_in_formulas(&mut cx.wb, old_name, *old_scope, &name)?; } } cx.wb.names.retain(|n| !(n.name.eq_ignore_ascii_case(&name) && n.scope == scope)); @@ -420,7 +420,7 @@ fn define_name(s: &mut Session, p: &Json) -> Result { /// Formulas that use a renamed name follow it: cell formulas and other names' definitions, on /// the sheets where `old` resolves to the renamed name (its own sheet for a sheet-scoped name; /// every sheet without a same-named sheet-level name for a workbook-level one). -fn rename_name_in_formulas(wb: &mut gridcraft_model::Workbook, old: &str, old_scope: Option, new: &str) { +fn rename_name_in_formulas(wb: &mut gridcraft_model::Workbook, old: &str, old_scope: Option, new: &str) -> Result<()> { let shadowed: Vec = wb.names.iter().filter(|n| n.name.eq_ignore_ascii_case(old)).filter_map(|n| n.scope).collect(); let applies = |sheet: usize| match old_scope { Some(s) => s == sheet, @@ -438,29 +438,14 @@ fn rename_name_in_formulas(wb: &mut gridcraft_model::Workbook, old: &str, old_sc }); hit.then_some(out) }; - for i in 0..wb.sheets.len() { - if !applies(i) { - continue; - } - let Some(sh) = wb.sheet_mut(i) else { continue }; - let formulas: Vec<(CellRef, std::sync::Arc)> = sh.cells.iter().filter_map(|(c, x)| x.formula.clone().map(|f| (c, f))).collect(); - for (c, f) in formulas { - let Some(e) = f.expr().and_then(rename) else { continue }; - let mut nf = Formula::from_expr(e); - nf.array = f.array; - nf.dynamic = f.dynamic; - if let Some(cell) = sh.cells.get_mut(c) { - cell.formula = Some(std::sync::Arc::new(nf)); - } - } - } - for n in wb.names.iter_mut() { - if n.scope.is_none_or(applies) - && let Some(e) = gridcraft_formula::parse_name(&n.formula).ok().and_then(rename) - { - n.formula = gridcraft_formula::print(&e); - } - } + // Every reference held where the renamed name is the one meant: on its sheet (or, for a + // workbook name, every sheet without one of its own), and in workbook names. + wb.rewrite_references(&|host, e| if host.sheet.is_none_or(applies) { rename(e.clone()).unwrap_or(e) } else { e }); + // Python cells' `xl("…")` references too. + let sheet_of: std::collections::HashMap = wb.sheets.iter().enumerate().map(|(i, s)| (s.name.to_ascii_lowercase(), i)).collect(); + crate::cmd::edit::rewrite_python_refs(wb, &|host, e| { + if sheet_of.get(&host.to_ascii_lowercase()).copied().is_none_or(applies) { rename(e.clone()).unwrap_or(e) } else { e } + }) } /// Refuses a name of the shape GridCraft keeps its own workbook data in ([`super::stash`]): diff --git a/crates/engine/src/cmd/insert.rs b/crates/engine/src/cmd/insert.rs index 56e066383..38e8c64f7 100644 --- a/crates/engine/src/cmd/insert.rs +++ b/crates/engine/src/cmd/insert.rs @@ -553,28 +553,24 @@ fn table_rename(s: &mut Session, p: &Json) -> Result { if let Some(t) = cx.sheet_mut(si)?.tables.get_mut(ti) { t.name = name.clone(); } - // Structured references follow the rename. - for i in 0..cx.wb.sheets.len() { - let keys: Vec<(CellRef, std::sync::Arc)> = - cx.wb.sheets.get(i).map(|s| s.cells.iter().filter_map(|(c, x)| x.formula.clone().map(|f| (c, f))).collect()).unwrap_or_default(); - // A bare name that is also a defined name resolves to the defined name, so it is not the table. - let shadowed = cx.wb.name(&old, i).is_some(); - let Some(sh) = cx.wb.sheet_mut(i) else { continue }; - for (c, f) in keys { - let Some(e) = f.expr() else { continue }; - let ne = e.map(&mut |x| match x { - gridcraft_formula::Expr::Struct(mut st) if st.table.eq_ignore_ascii_case(&old) => { - st.table = name.clone(); - gridcraft_formula::Expr::Struct(st) - } - gridcraft_formula::Expr::Name(n) if !shadowed && n.eq_ignore_ascii_case(&old) => gridcraft_formula::Expr::Name(name.clone()), - o => o, - }); - if let Some(cell) = sh.cells.get_mut(c) { - cell.formula = Some(std::sync::Arc::new(Formula::from_expr(ne))); + // Every reference to the table follows the rename. A bare name that is also a defined + // name where it is held resolves to the defined name, so it is not the table. + let shadowed: Vec = (0..cx.wb.sheets.len()).map(|i| cx.wb.name(&old, i).is_some()).collect(); + let sheet_of: std::collections::HashMap = + cx.wb.sheets.iter().enumerate().map(|(i, s)| (s.name.to_ascii_lowercase(), i)).collect(); + let rename = |sheet: Option, e: gridcraft_formula::Expr| { + let shadow = sheet.is_some_and(|i| shadowed.get(i).copied().unwrap_or(false)); + e.map(&mut |x| match x { + gridcraft_formula::Expr::Struct(mut st) if st.table.eq_ignore_ascii_case(&old) => { + st.table = name.clone(); + gridcraft_formula::Expr::Struct(st) } - } - } + gridcraft_formula::Expr::Name(n) if !shadow && n.eq_ignore_ascii_case(&old) => gridcraft_formula::Expr::Name(name.clone()), + o => o, + }) + }; + cx.wb.rewrite_references(&|host, e| rename(host.sheet, e)); + crate::cmd::edit::rewrite_python_refs(&mut cx.wb, &|host, e| rename(sheet_of.get(&host.to_ascii_lowercase()).copied(), e))?; cx.structural = true; Ok(Json::Null) }) @@ -1742,7 +1738,9 @@ fn clear_cf(s: &mut Session, p: &Json) -> Result { // The relative formulas are written for the top-left cell: when it goes, they're // rewritten for the new one, so the areas left keep reading the same cells. if let (Some(from), Some(to)) = (before, RangeRef::top_left(&cf.ranges)) { - rebase_cf_formulas(&mut cf.rule, from, to); + for f in cf.rule.relative_formulas_mut() { + *f = crate::cmd::data::move_rule_formula(f, from, to); + } } } sh.cond_formats.retain(|c| !c.ranges.is_empty()); @@ -1751,19 +1749,6 @@ fn clear_cf(s: &mut Session, p: &Json) -> Result { }) } -/// Moves the relative references of a rule's per-cell formulas written for `from` to `to`. -fn rebase_cf_formulas(rule: &mut CfRule, from: CellRef, to: CellRef) { - let mv = |f: &str| crate::cmd::data::move_rule_formula(f, from, to); - match rule { - CfRule::CellIs { a, b, .. } => { - *a = mv(a); - *b = b.as_deref().map(mv); - } - CfRule::Expression { formula, .. } => *formula = mv(formula), - _ => {} - } -} - fn manage_cf(s: &mut Session, p: &Json) -> Result { let sheet = target_sheet(s, p)?; if p.get("delete").is_none() && p.get("moveUp").is_none() && p.get("moveDown").is_none() { diff --git a/crates/engine/src/cmd/sheet.rs b/crates/engine/src/cmd/sheet.rs index 95a0c93f5..f37bcb788 100644 --- a/crates/engine/src/cmd/sheet.rs +++ b/crates/engine/src/cmd/sheet.rs @@ -154,7 +154,9 @@ fn shift_sheet_features(sh: &mut Sheet, axis: Axis, at: u32, count: u32, insert: } sh.merges = sh.merges.iter().filter_map(|m| map_range(*m)).filter(|m| !m.is_single()).collect(); for cf in sh.cond_formats.iter_mut() { - cf.ranges = cf.ranges.iter().filter_map(|r| map_range(*r)).collect(); + let moves: Vec<(RangeRef, RangeRef)> = cf.ranges.iter().filter_map(|r| map_range(*r).map(|m| (*r, m))).collect(); + cf.ranges = moves.iter().map(|(_, m)| *m).collect(); + rehost_rule(cf.rule.relative_formulas_mut(), &moves, &e); } for er in sh.edit_ranges.iter_mut() { er.ranges = er.ranges.iter().filter_map(|r| map_range(*r)).collect(); @@ -162,7 +164,9 @@ fn shift_sheet_features(sh: &mut Sheet, axis: Axis, at: u32, count: u32, insert: sh.edit_ranges.retain(|er| !er.ranges.is_empty()); sh.cond_formats.retain(|cf| !cf.ranges.is_empty()); for dv in sh.validations.iter_mut() { - dv.ranges = dv.ranges.iter().filter_map(|r| map_range(*r)).collect(); + let moves: Vec<(RangeRef, RangeRef)> = dv.ranges.iter().filter_map(|r| map_range(*r).map(|m| (*r, m))).collect(); + dv.ranges = moves.iter().map(|(_, m)| *m).collect(); + rehost_rule(dv.formulas_mut(), &moves, &e); } sh.validations.retain(|dv| !dv.ranges.is_empty()); for t in sh.tables.iter_mut() { @@ -215,38 +219,10 @@ fn shift_sheet_features(sh: &mut Sheet, axis: Axis, at: u32, count: u32, insert: } } -/// Rewrites every formula reference (chart series included), sparkline source and PivotTable -/// source for a structural edit on `target`. +/// Rewrites every reference the workbook holds for a structural edit on `target`. pub(super) fn rewrite(cx: &mut Ctx, target: &str, e: &Edit) -> Result<()> { cx.edits.push((target.to_string(), e.clone())); - let wb = &mut cx.wb; - super::edit::rewrite_all_formulas(wb, target, e)?; - for si in 0..wb.sheets.len() { - let host = wb.sheets.get(si).map(|s| s.name.clone()).unwrap_or_default(); - let Some(sh) = wb.sheet_mut(si) else { continue }; - let fix = |text: &str| -> String { - match gridcraft_formula::parse(text) { - Ok(expr) => gridcraft_formula::print(&gridcraft_formula::adjust::adjust(expr, &host, target, e)), - Err(_) => text.to_string(), - } - }; - for sp in sh.sparklines.iter_mut() { - sp.source = fix(&sp.source); - } - // PivotTable sources (a range, table or defined name) are only rewritten when the edit - // moves them, so table and name sources keep their text. - for pt in sh.pivots.iter_mut() { - let body = pt.source.trim().trim_start_matches('='); - if let Ok(expr) = gridcraft_formula::parse(body) { - let before = gridcraft_formula::print(&expr); - let after = gridcraft_formula::print(&gridcraft_formula::adjust::adjust(expr, &host, target, e)); - if after != before { - pt.source = after; - } - } - } - } - Ok(()) + super::edit::rewrite_all_formulas(&mut cx.wb, target, e) } /// Inserting or deleting cells moves the copied block away from the stored source range, so, like @@ -725,13 +701,75 @@ pub(crate) fn map_range(r: RangeRef, e: &Edit) -> Option { } } +/// A conditional format's or validation's formulas are written for its ranges' top-left cell. +/// When an edit moves its ranges (`moves`: each range before and after) so the top-left is +/// another cell, they are re-hosted at that cell where it stood before the edit; rewriting the +/// workbook's references for the edit then moves them as it moves a formula there. A range +/// moved whole keeps its cells in step, so its top-left stood where the range's offset says; +/// only one cut short (its first cells deleted) takes the cell that moved into its place. +fn rehost_rule(formulas: Vec<&mut String>, moves: &[(RangeRef, RangeRef)], e: &Edit) { + let (Some(from), Some(to)) = ( + RangeRef::top_left(&moves.iter().map(|(r, _)| *r).collect::>()), + RangeRef::top_left(&moves.iter().map(|(_, m)| *m).collect::>()), + ) else { + return; + }; + let whole = |(r, m): &(RangeRef, RangeRef)| r.width() == m.width() && r.height() == m.height(); + let back = |c: CellRef, (r, m): &(RangeRef, RangeRef)| { + CellRef::new( + (i64::from(c.row) - i64::from(m.start.row) + i64::from(r.start.row)).max(0) as u32, + (i64::from(c.col) - i64::from(m.start.col) + i64::from(r.start.col)).max(0) as u32, + ) + }; + let holder = moves.iter().find(|(_, m)| m.contains(to)); + let same_shift = moves.iter().all(whole) + && moves.windows(2).all(|w| match w { + [a, b] => back(to, a) == back(to, b), + _ => true, + }); + let at = match holder { + Some(p) if whole(p) => back(to, p), + Some(_) => pre_image(e, to), + None if same_shift => moves.first().map_or(to, |p| back(to, p)), + None => pre_image(e, to), + }; + if at != from { + for f in formulas { + *f = crate::cmd::data::move_rule_formula(f, from, at); + } + } +} + +/// Where the cell that `e` puts at `c` stood before it (`c` itself when nothing moved it). +fn pre_image(e: &Edit, c: CellRef) -> CellRef { + let (axis, count) = match *e { + Edit::Insert { axis, count, .. } | Edit::Delete { axis, count, .. } => (axis, count), + Edit::InsertCells { axis, range } | Edit::DeleteCells { axis, range } => { + (axis, if axis == Axis::Rows { range.height() } else { range.width() }) + } + // A move takes ranges whole, which `rehost_rule` handles by their offset. + Edit::Move { .. } | Edit::MoveToSheet { .. } => return c, + }; + let along = |d: i64| match axis { + Axis::Rows => c.offset(d, 0), + Axis::Cols => c.offset(0, d), + }; + [Some(c), along(i64::from(count)), along(-i64::from(count))] + .into_iter() + .flatten() + .find(|p| map_range(RangeRef::cell(*p), e).map(|r| r.start) == Some(c)) + .unwrap_or(c) +} + /// Shifts what Insert/Delete Cells moves along with the cells: merged areas, conditional /// format, validation, table, filter and print-area ranges, notes, links and sparklines. pub(super) fn shift_cell_features(sh: &mut Sheet, e: &Edit) { let map_cell = |c: CellRef| map_range(RangeRef::cell(c), e).map(|r| r.start); sh.merges = sh.merges.iter().filter_map(|m| map_range(*m, e)).filter(|m| !m.is_single()).collect(); for cf in sh.cond_formats.iter_mut() { - cf.ranges = cf.ranges.iter().filter_map(|r| map_range(*r, e)).collect(); + let moves: Vec<(RangeRef, RangeRef)> = cf.ranges.iter().filter_map(|r| map_range(*r, e).map(|m| (*r, m))).collect(); + cf.ranges = moves.iter().map(|(_, m)| *m).collect(); + rehost_rule(cf.rule.relative_formulas_mut(), &moves, e); } for er in sh.edit_ranges.iter_mut() { er.ranges = er.ranges.iter().filter_map(|r| map_range(*r, e)).collect(); @@ -739,7 +777,9 @@ pub(super) fn shift_cell_features(sh: &mut Sheet, e: &Edit) { sh.edit_ranges.retain(|er| !er.ranges.is_empty()); sh.cond_formats.retain(|cf| !cf.ranges.is_empty()); for dv in sh.validations.iter_mut() { - dv.ranges = dv.ranges.iter().filter_map(|r| map_range(*r, e)).collect(); + let moves: Vec<(RangeRef, RangeRef)> = dv.ranges.iter().filter_map(|r| map_range(*r, e).map(|m| (*r, m))).collect(); + dv.ranges = moves.iter().map(|(_, m)| *m).collect(); + rehost_rule(dv.formulas_mut(), &moves, e); } sh.validations.retain(|dv| !dv.ranges.is_empty()); for t in sh.tables.iter_mut() { diff --git a/crates/engine/src/cmd/sheet/tabs.rs b/crates/engine/src/cmd/sheet/tabs.rs index 0c3925d22..c6586133f 100644 --- a/crates/engine/src/cmd/sheet/tabs.rs +++ b/crates/engine/src/cmd/sheet/tabs.rs @@ -1,4 +1,4 @@ -use super::{Arc, CellRef, Ctx, EngineError, Json, Result, Session, Sheet, Visibility, bad, bool_param, edit, json, ok, str_param, target_sheet}; +use super::{Arc, Ctx, EngineError, Json, Result, Session, Sheet, Visibility, bad, bool_param, edit, json, ok, str_param, target_sheet}; pub(super) fn insert_sheet(s: &mut Session, p: &Json) -> Result { if s.doc()?.wb.protected_structure { @@ -50,36 +50,16 @@ pub(super) fn delete_sheet(s: &mut Session, p: &Json) -> Result { let d = s.doc_mut()?; edit_doc(d, |cx| { cx.wb.sheets.remove(i); - for si in 0..cx.wb.sheets.len() { - let keys: Vec<(CellRef, Arc)> = - cx.wb.sheets.get(si).map(|s| s.cells.iter().filter_map(|(c, x)| x.formula.clone().map(|f| (c, f))).collect()).unwrap_or_default(); - let Some(sh) = cx.wb.sheet_mut(si) else { continue }; - for (c, f) in keys { - if let Some(e) = f.expr() { - let ne = gridcraft_formula::adjust::delete_sheet(e, &name, &order); - if let Some(cell) = sh.cells.get_mut(c) { - cell.formula = Some(Arc::new(gridcraft_model::Formula::from_expr(ne))); - } - } - } - } - crate::cmd::edit::rewrite_python_refs(&mut cx.wb, &|_, e| gridcraft_formula::adjust::delete_sheet(e, &name, &order))?; - // Chart series into the deleted sheet become #REF!, like formulas. - crate::cmd::edit::rewrite_cell_links(&mut cx.wb, |_, e| gridcraft_formula::adjust::delete_sheet(e, &name, &order)); cx.wb.names.retain(|n| n.scope != Some(i)); + // Every reference into the deleted sheet becomes #REF!. + cx.wb.rewrite_references(&|_, e| gridcraft_formula::adjust::delete_sheet(e, &name, &order)); + crate::cmd::edit::rewrite_python_refs(&mut cx.wb, &|_, e| gridcraft_formula::adjust::delete_sheet(e, &name, &order))?; for n in cx.wb.names.iter_mut() { if let Some(sc) = n.scope.as_mut() && *sc > i { *sc -= 1; } - // Names referring to the sheet become #REF!. - if let Ok(e) = gridcraft_formula::parse_name(&n.formula) { - let ne = gridcraft_formula::adjust::delete_sheet(e.clone(), &name, &order); - if ne != e { - n.formula = gridcraft_formula::print(&ne); - } - } } if cx.wb.active_sheet() >= cx.wb.sheets.len() || cx.wb.active_sheet() > i { cx.wb.set_active_sheet(cx.wb.active_sheet().saturating_sub(1).min(cx.wb.sheets.len().saturating_sub(1))); @@ -104,21 +84,10 @@ pub(super) fn rename_sheet(s: &mut Session, p: &Json) -> Result { edit(s, |cx| { let old = cx.wb.sheet(i).map(|s| s.name.clone()).unwrap_or_default(); cx.sheet_mut(i)?.name = name.clone(); + // Every reference the workbook holds follows the sheet. + cx.wb.rewrite_references(&|_, e| gridcraft_formula::adjust::rename_sheet(e, &old, &name)); for si in 0..cx.wb.sheets.len() { - let keys: Vec<(CellRef, Arc)> = - cx.wb.sheets.get(si).map(|s| s.cells.iter().filter_map(|(c, x)| x.formula.clone().map(|f| (c, f))).collect()).unwrap_or_default(); let Some(sh) = cx.wb.sheet_mut(si) else { continue }; - for (c, f) in keys { - if let Some(e) = f.expr() { - let ne = gridcraft_formula::adjust::rename_sheet(e, &old, &name); - let text = gridcraft_formula::print(&ne); - if text != f.text - && let Some(cell) = sh.cells.get_mut(c) - { - cell.formula = Some(Arc::new(gridcraft_model::Formula::from_expr(ne))); - } - } - } for ch in sh.charts.iter_mut() { // A PivotChart follows its PivotTable's sheet. if let Some((sheet, pivot)) = ch.pivot.as_deref().and_then(crate::pivot::parse_chart_link) @@ -128,12 +97,6 @@ pub(super) fn rename_sheet(s: &mut Session, p: &Json) -> Result { } } } - crate::cmd::edit::rewrite_cell_links(&mut cx.wb, |_, e| gridcraft_formula::adjust::rename_sheet(e, &old, &name)); - for n in cx.wb.names.iter_mut() { - if let Ok(e) = gridcraft_formula::parse_name(&n.formula) { - n.formula = gridcraft_formula::print(&gridcraft_formula::adjust::rename_sheet(e, &old, &name)); - } - } crate::cmd::edit::rewrite_python_refs(&mut cx.wb, &|_, e| gridcraft_formula::adjust::rename_sheet(e, &old, &name))?; cx.structural = true; Ok(Json::Null) @@ -165,6 +128,21 @@ pub(super) fn move_sheet(s: &mut Session, p: &Json) -> Result { .find(|nm| cx.wb.sheet_index(nm).is_none()) .unwrap_or(base.clone()); sh.name = name; + // A copied sheet's charts plot the copy's own data, as Excel's do (its formulas keep + // what they name). + let fix = |t: &str| match gridcraft_formula::parse(t.trim_start_matches('=')) { + Ok(e) => gridcraft_formula::print(&gridcraft_formula::adjust::rename_sheet(e, &base, &sh.name)), + Err(_) => t.to_string(), + }; + for ch in &mut sh.charts { + for se in &mut ch.series { + se.values = fix(&se.values); + for t in [&mut se.categories, &mut se.name, &mut se.bubble_sizes].into_iter().flatten() { + *t = fix(t); + } + } + ch.source = ch.source.as_deref().map(fix); + } sh.tables.clear(); // table names must be unique sh.preserved = None; // kept file content (form controls, OLE objects…) stays with the original // Object ids are unique across the workbook (selection and the `{kind, id}` commands diff --git a/crates/engine/src/tests.rs b/crates/engine/src/tests.rs index 75e5eac96..52e5815fc 100644 --- a/crates/engine/src/tests.rs +++ b/crates/engine/src/tests.rs @@ -5649,3 +5649,190 @@ fn pivot_new_sheet_destination_respects_workbook_structure_protection() { } assert!(s.execute("insert.pivotTable", json!({"source": "A1:B3", "location": "New"})).is_err()); } + +/// Renaming a sheet renames every reference to it: a PivotTable's source, a conditional +/// format's formula and a validation's list follow it. +#[test] +fn sheet_rename_renames_every_reference() { + let mut s = s(); + s.execute("range.setValues", json!({"range": "A1:B3", "values": [["Region", "Sales"], ["East", 1], ["West", 2]]})).unwrap(); + s.execute("insert.pivotTable", json!({"source": "Sheet1!$A$1:$B$3", "destination": "Sheet1!E3", "rows": ["Region"], "values": ["Sales"]})) + .unwrap(); + s.execute("sheet.rename", json!({"name": "Data"})).unwrap(); + let wb = &s.doc().unwrap().wb; + assert_eq!(wb.sheets[0].pivots[0].source, "Data!$A$1:$B$3"); + s.execute("pivot.refresh", json!({})).unwrap(); +} + +/// Every edit that moves references moves those in conditional formats and validation too: +/// inserting rows, renaming a name, deleting a sheet; and deleting a sheet leaves arrays be. +#[test] +fn reference_edits_reach_conditional_formats_and_validation() { + let mut s = s(); + s.execute("home.insertSheet", json!({"name": "Lists"})).unwrap(); + s.execute("range.setValues", json!({"range": "Lists!A1:A3", "values": [["a"], ["b"], ["c"]]})).unwrap(); + s.execute("sheet.activate", json!({"sheet": 1})).ok(); + let sheet1 = s.doc().unwrap().wb.sheet_index("Sheet1").unwrap(); + s.execute("sheet.activate", json!({"sheet": sheet1})).ok(); + s.execute("formulas.defineName", json!({"name": "Opts", "refersTo": "=Lists!$A$1:$A$3"})).unwrap(); + s.execute("data.validation", json!({"range": "Sheet1!B1:B5", "type": "list", "formula1": "=Opts"})).unwrap(); + s.execute("data.validation", json!({"range": "Sheet1!E1:E5", "type": "list", "formula1": "=Lists!$A$1:$A$3"})).unwrap(); + s.execute( + "home.conditionalFormat", + json!({"range": "Sheet1!C1:C5", "rule": {"type": "expression", "formula": "=C1>$D$3"}, "style": {"fill": "#FFC7CE"}}), + ) + .unwrap(); + s.execute("cell.set", json!({"cell": "Sheet1!G2", "input": "=B2:B3*2", "array": true})).unwrap(); + let sh = |s: &Session| s.doc().unwrap().wb.sheet(s.doc().unwrap().wb.sheet_index("Sheet1").unwrap()).cloned().unwrap(); + // Inserting a row above moves the rule's references with its range. + s.execute("home.insertRows", json!({"rows": "1:1", "sheet": "Sheet1"})).unwrap(); + let rule = match &sh(&s).cond_formats[0].rule { + gridcraft_model::CfRule::Expression { formula, .. } => formula.clone(), + _ => String::new(), + }; + assert_eq!(rule.trim_start_matches('='), "C2>$D$4"); + // Renaming a name renames it in validation lists. + s.execute("formulas.defineName", json!({"name": "Choices", "oldName": "Opts", "refersTo": "=Lists!$A$1:$A$3"})).unwrap(); + assert!(sh(&s).validations.iter().any(|v| v.f1.trim_start_matches('=') == "Choices")); + // Deleting the sheet a list comes from makes it #REF!, and keeps the array formula. + let array_before = sh(&s).cells.iter().find_map(|(_, c)| c.formula.as_ref().and_then(|f| f.array)); + assert!(array_before.is_some()); + let lists = s.doc().unwrap().wb.sheet_index("Lists").unwrap(); + s.execute("home.deleteSheet", json!({"sheet": lists})).unwrap(); + assert!(sh(&s).validations.iter().any(|v| v.f1.contains("#REF!")), "{:?}", sh(&s).validations.iter().map(|v| v.f1.clone()).collect::>()); + assert_eq!(sh(&s).cells.iter().find_map(|(_, c)| c.formula.as_ref().and_then(|f| f.array)), array_before); +} + +/// A copied sheet's chart plots the copy's data. +#[test] +fn a_copied_sheets_chart_plots_the_copy() { + let mut s = s(); + s.execute("range.setValues", json!({"range": "A1:B3", "values": [["x", "y"], ["a", 1], ["b", 2]]})).unwrap(); + s.execute("insert.chart", json!({"range": "A1:B3", "type": "column"})).unwrap(); + s.execute("sheet.move", json!({"sheet": 0, "to": 1, "copy": true})).unwrap(); + let wb = &s.doc().unwrap().wb; + let copy = wb.sheets.iter().find(|sh| sh.name != "Sheet1").unwrap(); + assert!(copy.charts[0].series[0].values.contains(©.name), "{}", copy.charts[0].series[0].values); +} + +/// A rule's formulas follow its ranges: deleting its top-left row re-hosts them at the cell +/// that takes its place, and a cut takes rules with their cells, moving their references once. +#[test] +fn rule_formulas_follow_their_ranges() { + let rule_text = |s: &Session| -> (Vec, Vec) { + let sh = s.doc().unwrap().wb.sheets[0].clone(); + let cf = sh.cond_formats.iter().map(|c| match &c.rule { + gridcraft_model::CfRule::Expression { formula, .. } => { + format!("{}@{}", formula.trim_start_matches('='), c.ranges.iter().map(|r| r.a1()).collect::>().join(",")) + } + _ => String::new(), + }); + let dv = sh + .validations + .iter() + .map(|v| format!("{}@{}", v.f1.trim_start_matches('='), v.ranges.iter().map(|r| r.a1()).collect::>().join(","))); + (cf.collect(), dv.collect()) + }; + let mut s = s(); + s.execute("home.conditionalFormat", json!({"range": "A2:A5", "rule": {"type": "expression", "formula": "=B2>0"}, "style": {"fill": "#FFC7CE"}})) + .unwrap(); + s.execute("data.validation", json!({"range": "C2:C5", "type": "custom", "formula1": "=D2>0"})).unwrap(); + s.execute("home.deleteRows", json!({"rows": "2:2"})).unwrap(); + assert_eq!(rule_text(&s), (vec!["B2>0@A2:A4".to_string()], vec!["D2>0@C2:C4".to_string()])); + // Cut A2:A4 to F2: the rule goes with the cells, still testing the cells beside them. + s.execute("edit.cut", json!({"range": "A2:A4"})).unwrap(); + s.execute("edit.paste", json!({"at": "F2"})).unwrap(); + assert_eq!(rule_text(&s).0, vec!["B2>0@F2:F4".to_string()]); + // An overlapping cut moves a self-referring rule's reference once. + let mut s = super::tests::s(); + s.execute("data.validation", json!({"range": "A1:A2", "type": "custom", "formula1": "=A1>0"})).unwrap(); + s.execute("edit.cut", json!({"range": "A1:A2"})).unwrap(); + s.execute("edit.paste", json!({"at": "A2"})).unwrap(); + assert_eq!(rule_text(&s).1, vec!["A2>0@A2:A3".to_string()]); +} + +/// Renaming a table renames every reference to it (a PivotTable's source, a name, a rule) and +/// leaves formulas that don't name it, legacy arrays included, as they are. +#[test] +fn table_rename_renames_every_reference() { + let mut s = s(); + s.execute("range.setValues", json!({"range": "A1:B3", "values": [["k", "v"], ["a", 1], ["b", 2]]})).unwrap(); + s.execute("insert.table", json!({"range": "A1:B3"})).unwrap(); + let table = s.doc().unwrap().wb.sheets[0].tables[0].name.clone(); + s.execute("cell.set", json!({"cell": "D1", "input": "=A2:A3", "array": true})).unwrap(); + s.execute("formulas.defineName", json!({"name": "Tot", "refersTo": format!("=SUM({table}[v])")})).unwrap(); + s.execute( + "home.conditionalFormat", + json!({"range": "F1:F3", "rule": {"type": "expression", "formula": format!("=COUNT({table}[v])>0")}, "style": {"fill": "#FFC7CE"}}), + ) + .unwrap(); + s.execute("insert.pivotTable", json!({"source": table, "destination": "Sheet1!H3", "rows": ["k"], "values": ["v"]})).unwrap(); + let array = s.doc().unwrap().wb.sheets[0].cell(CellRef::new(0, 3)).and_then(|c| c.formula.clone()).unwrap(); + s.execute("table.rename", json!({"table": table, "name": "Data"})).unwrap(); + let wb = &s.doc().unwrap().wb; + let sh = &wb.sheets[0]; + assert_eq!( + sh.cell(CellRef::new(0, 3)).and_then(|c| c.formula.clone()).map(|f| (f.text.clone(), f.array, f.dynamic)), + Some((array.text.clone(), array.array, array.dynamic)) + ); + assert_eq!(wb.names.iter().find(|n| n.name == "Tot").map(|n| n.formula.clone()).as_deref(), Some("SUM(Data[v])")); + assert!(matches!(&sh.cond_formats[0].rule, gridcraft_model::CfRule::Expression { formula, .. } if formula.contains("Data[v]"))); + assert_eq!(sh.pivots[0].source, "Data"); + s.execute("data.refreshAll", json!({})).unwrap(); +} + +/// Rules moved whole keep their formulas; a range an edit leaves in place keeps them too; +/// thresholds are read as written; a cut to another sheet names the source sheet's cells. +#[test] +fn rules_moved_whole_or_left_in_place_keep_their_formulas() { + let cf = |s: &Session, sheet: usize| -> Vec { + s.doc().unwrap().wb.sheets[sheet] + .cond_formats + .iter() + .map(|c| match &c.rule { + gridcraft_model::CfRule::Expression { formula, .. } => { + format!("{}@{}", formula.trim_start_matches('='), c.ranges.iter().map(|r| r.a1()).collect::>().join(",")) + } + gridcraft_model::CfRule::DataBar { min: gridcraft_model::CfValueKind::Formula(f), .. } => format!("bar {f}"), + _ => String::new(), + }) + .collect() + }; + let rule = |s: &mut Session, range: &str, f: &str| { + s.execute("home.clearRules", json!({"whole": true})).ok(); + s.execute("home.conditionalFormat", json!({"range": range, "rule": {"type": "expression", "formula": f}, "style": {"fill": "#FFC7CE"}})) + .unwrap(); + }; + let mut s = s(); + rule(&mut s, "B1:B5", "=C1>0"); + s.execute("sheet.moveColumns", json!({"cols": "B:B", "before": 4})).unwrap(); + // The column moved whole: the rule tests the column that was beside it (C, now B), as a + // formula there would. + assert_eq!(cf(&s, 0), vec!["B1>0@D1:D5".to_string()]); + let mut s = super::tests::s(); + rule(&mut s, "A1:C1", "=B1>0"); + s.execute("home.deleteCells", json!({"range": "A1", "shift": "up"})).unwrap(); + assert_eq!(cf(&s, 0), vec!["B1>0@A1:C1".to_string()]); + // A data bar's threshold formula is read as written: deleting the first row only moves it. + let mut s = super::tests::s(); + s.execute("home.conditionalFormat", json!({"range": "A1:A10", "rule": {"type": "dataBar", "min": {"type": "formula", "value": "MIN(C1:C10)"}}})) + .unwrap(); + assert_eq!(cf(&s, 0), vec!["bar MIN(C1:C10)".to_string()]); + s.execute("home.deleteRows", json!({"rows": "1:1"})).unwrap(); + assert_eq!(cf(&s, 0), vec!["bar MIN(C1:C9)".to_string()]); + // A cut to another sheet: the rule still reads the source sheet's cells. + let mut s = super::tests::s(); + s.execute("home.insertSheet", json!({"name": "Two"})).unwrap(); + let one = s.doc().unwrap().wb.sheet_index("Sheet1").unwrap(); + let two = s.doc().unwrap().wb.sheet_index("Two").unwrap(); + s.execute("sheet.activate", json!({"sheet": one})).ok(); + s.execute( + "home.conditionalFormat", + json!({"range": "Sheet1!A2:A4", "rule": {"type": "expression", "formula": "=B2>0"}, "style": {"fill": "#FFC7CE"}}), + ) + .unwrap(); + s.execute("edit.cut", json!({"range": "Sheet1!A2:A4"})).unwrap(); + s.execute("sheet.activate", json!({"sheet": two})).unwrap(); + s.execute("edit.paste", json!({"at": "F2"})).unwrap(); + assert_eq!(cf(&s, two), vec!["Sheet1!B2>0@F2:F4".to_string()]); +} diff --git a/crates/formula/src/adjust.rs b/crates/formula/src/adjust.rs index 319474b4e..3168ae38f 100644 --- a/crates/formula/src/adjust.rs +++ b/crates/formula/src/adjust.rs @@ -266,8 +266,9 @@ pub fn rename_sheet(e: Expr, old: &str, new: &str) -> Expr { } // Sheet-qualified defined name `Old!MyName` is stored as one string, with the bare sheet name as the parser // stores it (the printer adds the quotes). - Expr::Name(n) => match n.split_at_checked(old.len()) { - Some((head, rest)) if head.eq_ignore_ascii_case(old) && rest.starts_with('!') => Expr::Name(format!("{new}{rest}")), + // A sheet name may itself hold a '!', so the name splits at its last one. + Expr::Name(n) => match n.rsplit_once('!') { + Some((sheet, rest)) if sheet.eq_ignore_ascii_case(old) => Expr::Name(format!("{new}!{rest}")), _ => Expr::Name(n), }, other => other, diff --git a/crates/formula/src/tests.rs b/crates/formula/src/tests.rs index 8b8215455..6ccfa7865 100644 --- a/crates/formula/src/tests.rs +++ b/crates/formula/src/tests.rs @@ -229,6 +229,10 @@ fn rename_sheet_updates_qualified_names() -> Result<(), Box Vec<&mut String> { + match self { + CfRule::CellIs { a, b, .. } => std::iter::once(a).chain(b.as_mut()).collect(), + CfRule::Expression { formula, .. } => vec![formula], + _ => Vec::new(), + } + } + + /// All the rule's formulas, thresholds included: what an edit that moves references + /// rewrites. + pub fn formulas_mut(&mut self) -> Vec<&mut String> { + let kinds: Vec<&mut CfValueKind> = match self { + CfRule::CellIs { a, b, .. } => return std::iter::once(a).chain(b.as_mut()).collect(), + CfRule::Expression { formula, .. } => return vec![formula], + CfRule::ColorScale { stops } => stops.iter_mut().map(|(k, _)| k).collect(), + CfRule::DataBar { min, max, .. } => vec![min, max], + CfRule::IconSet { thresholds, .. } => thresholds.iter_mut().collect(), + _ => Vec::new(), + }; + kinds + .into_iter() + .filter_map(|k| match k { + CfValueKind::Formula(t) => Some(t), + _ => None, + }) + .collect() + } +} + +impl Validation { + /// The validation's formulas (for its range's top-left cell). + pub fn formulas_mut(&mut self) -> Vec<&mut String> { + std::iter::once(&mut self.f1).chain(self.f2.as_mut()).collect() + } +} + /// Number of icons in an icon set (`3Arrows` → 3, `5Quarters` → 5), always 3 to 5. pub fn icon_count(set: &str) -> usize { set.chars().next().and_then(|c| c.to_digit(10)).unwrap_or(3).clamp(3, 5) as usize diff --git a/crates/model/src/lib.rs b/crates/model/src/lib.rs index 35cfa315f..48c3fd554 100644 --- a/crates/model/src/lib.rs +++ b/crates/model/src/lib.rs @@ -31,7 +31,7 @@ pub use style::{ }; pub use workbook::{ CalcMode, CalcSettings, DefinedName, DocProps, EQUATION_BUDGET_MESSAGE, MAX_EQUATION_LAYOUT_BYTES, PhoneticProps, PhoneticRun, PhoneticString, - ShowObjects, Workbook, WorkbookView, + RefHost, ShowObjects, Workbook, WorkbookView, }; /// Font used for new workbooks. Only a name: renderers substitute an available open font diff --git a/crates/model/src/workbook.rs b/crates/model/src/workbook.rs index c67fe5dff..9fe2d452c 100644 --- a/crates/model/src/workbook.rs +++ b/crates/model/src/workbook.rs @@ -338,7 +338,95 @@ impl std::fmt::Debug for ActiveSheet { } } +/// Where a reference is held, for [`Workbook::rewrite_references`]. +#[derive(Clone, Copy, Debug)] +pub struct RefHost<'a> { + /// The sheet holding it, or a defined name's scope (`None`: the workbook). + pub sheet: Option, + /// The name unqualified references in it are on: its sheet's, or `"\u{0}"` for a defined + /// name (which has none). + pub name: &'a str, +} + +/// Formula text with `f` applied to its references; text that isn't a formula, or that `f` +/// doesn't change, stays as it is (a leading `=` is kept). Whether it changed. +fn rewrite_with(t: &mut String, f: &dyn Fn(Expr) -> Expr, parse: fn(&str) -> Result) -> bool { + let body = t.trim_start_matches('='); + let Ok(e) = parse(body) else { return false }; + let before = gridcraft_formula::print(&e); + let after = gridcraft_formula::print(&f(e)); + if after == before { + return false; + } + *t = if t.starts_with('=') { format!("={after}") } else { after }; + true +} + +fn rewrite_text(t: &mut String, f: &dyn Fn(Expr) -> Expr) { + rewrite_with(t, f, gridcraft_formula::parse); +} + impl Workbook { + /// Rewrites every reference the workbook holds with `f`, given where each is held, in one + /// place: cell formulas (keeping their array and spill kind), defined names, conditional + /// formats and data validation (written for their range's top-left cell, so they move as + /// a cell formula there does), in-workbook links, chart series (a chart's source block + /// that no longer exists is dropped), sparklines and PivotTable sources. Every edit that + /// moves references (renaming and deleting sheets and names, inserting and deleting lines + /// and cells, cut-moves, the names a file reader settles on) goes through it, so no holder + /// of a reference is left out. A legacy array's own range is the caller's to move. + pub fn rewrite_references(&mut self, f: &dyn Fn(RefHost<'_>, Expr) -> Expr) { + for n in &mut self.names { + let host = RefHost { sheet: n.scope, name: "\u{0}" }; + rewrite_with(&mut n.formula, &|e| f(host, e), gridcraft_formula::parse_name); + } + for (si, sh) in self.sheets.iter_mut().enumerate() { + let sh = Arc::make_mut(sh); + let name = sh.name.clone(); + let host = RefHost { sheet: Some(si), name: &name }; + let f = |e: Expr| f(host, e); + let formulas: Vec<_> = sh.cells.iter().filter_map(|(c, cell)| cell.formula.as_ref().map(|x| (c, x.clone()))).collect(); + for (c, old) in formulas { + let Some(e) = old.expr() else { continue }; + let new = Formula::from_expr(f(e)); + if new.text != old.text + && let Some(cell) = sh.cells.get_mut(c) + { + cell.formula = Some(Arc::new(Formula { array: old.array, dynamic: old.dynamic, ..new })); + } + } + for t in sh.cond_formats.iter_mut().flat_map(|cf| cf.rule.formulas_mut()) { + rewrite_text(t, &f); + } + for t in sh.validations.iter_mut().flat_map(|v| v.formulas_mut()) { + rewrite_text(t, &f); + } + for l in sh.hyperlinks.values_mut().filter(|l| !l.external) { + rewrite_text(&mut l.target, &f); + } + for ch in &mut sh.charts { + for se in &mut ch.series { + rewrite_text(&mut se.values, &f); + for t in [&mut se.categories, &mut se.name, &mut se.bubble_sizes].into_iter().flatten() { + rewrite_text(t, &f); + } + } + if let Some(src) = &mut ch.source { + rewrite_text(src, &f); + } + if ch.source.as_deref().is_some_and(|s| s.contains("#REF!")) { + ch.source = None; + } + } + for sp in &mut sh.sparklines { + rewrite_text(&mut sp.source, &f); + } + for pt in &mut sh.pivots { + rewrite_text(&mut pt.source, &f); + } + } + } + /// A new workbook with one sheet, "Sheet1". pub fn new() -> Workbook { Workbook { diff --git a/docs/architecture.md b/docs/architecture.md index 68639541e..f803f6ca6 100644 --- a/docs/architecture.md +++ b/docs/architecture.md @@ -1,6 +1,6 @@ # Architecture -> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-11-02 · **Change:** minor (Python mode in the formula bar; earlier: Python cells as data; earlier: equations: the `math` crate and the layout cache; earlier: recently used functions kept in the preferences; Function Library module; accent icons; earlier: the hidden names that hold macros) · **Target:** Microsoft Excel (Microsoft 365) +> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-11-11 · **Change:** minor (one workbook-wide reference rewrite; earlier: Python mode in the formula bar; earlier: Python cells as data; earlier: equations: the `math` crate and the layout cache; earlier: recently used functions kept in the preferences; Function Library module; accent icons; earlier: the hidden names that hold macros) · **Target:** Microsoft Excel (Microsoft 365) How GridCraft is built today. Rules for contributors are in [`AGENTS.md`](../AGENTS.md). @@ -12,6 +12,7 @@ including tests, 2026-10-10. | Layer | Crate | Lines | Job | |---|---|---|---| +| 2026-11-11 | minor | Reference rewriting: `Workbook::rewrite_references` as the one walker for every reference-moving edit; rule formulas re-hosted by how their ranges moved and moved with a cut | | L0 | `core` | ~1.3k | Cell and range addresses (A1, R1C1, sheet-qualified; 1,048,576 × 16,384), `Value`, `CellError`, Excel coercion, 1900/1904 date serials, typed-input parsing | | L0 | `numfmt` | ~2.1k | Excel number-format codes (sections, conditions, colours, dates, elapsed time, fractions, scientific, fill), General, `TEXT()`; en-US only | | L1 | `formula` | ~1.7k | Tokenizer, parser, AST, printer (A1 and R1C1), reference adjustment for copy, fill and structural edits | @@ -197,6 +198,26 @@ at its sheet again, so it is drawn, pointed from and committed there, and its po message, when its sheet is gone, or when it holds Python code (in Python mode, or begun on a Python cell) that sheet protection now hides, as the Python editor window closes then. +## Reference rewriting + +`Workbook::rewrite_references` is the one walker over every place a workbook holds a reference: +cell formulas (keeping their legacy-array range and spill kind), defined names, conditional +formats, data validation, in-workbook links, chart series and source blocks, sparklines and +PivotTable sources. It hands the rewrite a `RefHost` (the holding sheet or a name's scope, and the +sheet name unqualified references are on). Every edit that moves references goes through it: +renaming and deleting sheets, renaming defined names and tables, inserting and deleting rows, +columns and cells, and cut-and-paste (`engine::cmd::edit::rewrite_all_formulas`, plus Python +`xl()` literals); a legacy array's own range is moved by the caller. + +Conditional-format and validation formulas are written for their range's top-left cell. When an +edit cuts a range short so that its top-left cell goes, the rule's top-left-relative formulas +(`CfRule::relative_formulas_mut`, `Validation::formulas_mut`) are first re-hosted at the cell that +took its place (`rehost_rule`), then moved once by the walker, so deleting a rule's first row no +longer turns it into `#REF!`. A range moved whole or left in place keeps its formulas, and +colour-scale, data-bar and icon-set thresholds are read as written. A cut takes the rules on its +cells with it (the engine's `Rule` trait, `remove_rule_cells`, `moved_rule_parts`), so their ranges and formulas +move together, once; a cut to another sheet qualifies their references with the source sheet. + ## Equations An equation is a shape (`ShapeKind::Equation`) whose `text` is its LaTeX source; it selects,