engine, model: one workbook-wide reference rewrite; rule formulas follow their ranges (ODS groundwork) (#4136)

* engine, model: one workbook-wide reference rewrite; rule formulas follow their ranges

Workbook::rewrite_references(&dyn Fn(RefHost, Expr) -> Expr) is the single
walker over every place a workbook holds a reference: cell formulas (keeping
array range and spill kind), defined names, conditional formats, validation,
in-workbook links, chart series and sources, sparklines and PivotTable
sources. Sheet rename and delete, defined-name and table rename, row/column
and cell insert/delete and cut-paste all go through it instead of their own
lists of holders, so a rename now also reaches pivot sources, rules and
validations; inserting rows above a rule moves its formulas; deleting a sheet
makes rule/validation references #REF! and no longer turns legacy arrays into
spills; table rename keeps legacy arrays. A copied sheet's charts plot the copy.

Conditional-format and validation formulas are re-hosted by how their ranges
moved (rehost_rule, CfRule::relative_formulas_mut/formulas_mut,
Validation::formulas_mut): deleting a rule's first row no longer makes it
#REF!, ranges moved whole or left in place keep their formulas, thresholds are
read as written. A cut takes rules with its cells (Rule trait,
remove_rule_cells, moved_rule_parts) and moves their references once.

A sheet-qualified name splits at its last '!' when a sheet is renamed.

* engine, model: review fixes for the workbook-wide reference rewrite

- rehost_rule takes the rule's top-left from all its ranges before the edit,
  so removing the range that held it (deleting its rows or cells) re-hosts
  the formulas instead of leaving #REF!.
- Internal hyperlink targets are no longer rewritten: they keep the place they
  name as typed, as main and Excel do.
- A cut can't be transposed or tiled by Paste Special (as in Excel); its rules
  and references followed the block unturned.
- rewrite_references copies a sheet only when something on it changes, so
  untouched sheets stay shared with undo snapshots.
- docs/architecture.md: revision row moved under Revision history; section
  updated.

* engine, model: re-review touch-ups for the reference rewrite

- The multi-area rehost test checks deleting the first area's cells both
  shifting up and shifting left (the comment said up, the test did left).
- rewrite_references checks rules, validations, charts, sparklines and pivots
  on the borrowed sheet and copies a list only when something in it changes
  (CfRule::formulas, Validation::formulas, read-only). A chart source already
  holding #REF! is dropped by any rewrite again.

* engine, model: round-2 review fixes for the reference rewrite

- A cut to another sheet names the source sheet in all of a conditional format's formulas,
  thresholds included: a colour scale's, data bar's or icon set's threshold formula kept
  reading the destination sheet's cells.
- A chart series name that is a bare word and not a defined name is a label, as the chart
  reads it: renaming a table of that name no longer rewrites it. Renaming a defined name
  rewrites formulas before the old name is dropped, so a series named by it still follows.
- The walker's doc no longer lists deleting names among the edits that go through it; a test
  comment says what it checks.

* engine, model: round-3 review fixes for the reference rewrite

- A chart series name is left as written unless the chart reads it as a reference: it starts
  with `=`, names a sheet, or is a defined name its own sheet sees. A name scoped to another
  sheet, or a label shaped like a cell (`Q1`), is no longer rewritten (corrects round 2's
  check, which looked at names in every scope and only exempted bare words).
- A chart source block is dropped as gone only when its formula holds `#REF!`, not its text:
  a sheet may be named `#REF!`.
- Defined names are handed to the rewrite on `NAME_HOST` (`[]`), which no sheet name can be,
  instead of a NUL that a sheet could be renamed to.
- The walker's doc and docs/architecture.md list a PivotChart's link and a slicer's table
  among what it does not visit.

* engine: Move Columns takes its columns' rules along as a cut does

A conditional format or validation wider than the moved columns was left in place by the
move step while its formulas were moved as references into the block, so the cells left
behind checked the wrong column and the moved column lost the rule. Move Columns now moves
the rules' parts in the moved columns as Cut and Paste does (`move_cut_rules`), and the rest
of the rule re-hosts from its new top-left cell.

* engine: round-5 review fixes for the reference rewrite

- Move Columns moves its rules before the columns' features shift (corrects round 4): moved
  left, a rule whose whole range was in the moved columns was shifted, re-hosted and then
  re-hosted again from mixed positions, so the parts left behind checked the wrong column.
- Copying a sheet keeps a chart's series and source text as written unless it names the
  copied sheet: a series name `=A1` lost its `=` and was read as the label "A1".
- Docs and comments say what the code does: `move_cut_rules` serves Move Columns too,
  `rewrite_all_formulas` and `rename_name_in_formulas` point at the walker, and
  docs/architecture.md names Move Columns; `sheet_rename_renames_a_pivot_source` is named for
  what it checks.

* docs: architecture: a rule's one formula across a partial shift of its cells

A conditional format or validation keeps one formula for all its cells, so an insert or
delete inside its range, or Move Columns across it, leaves relative references at the
cells on the far side of the shift reading where the top-left cell's reference puts them.

* engine: review fixes for the reference rewrite (CodeRabbit)

A cut moves the rules its cells hold when it is pasted, not the clipboard
snapshot's: a rule cleared after the cut came back at the destination.

A table rename leaves a bare name in a workbook name alone when a
workbook-level defined name of that name exists, as it does in cells.

* engine: a cut is not pasted skipping blanks

A cut's rules replace the destination's under the whole block, so a
Skip Blanks paste of it dropped validation under the cells it left
alone. Paste Special now refuses Skip Blanks for a cut, as it already
refuses Transpose and tiling (Excel offers none of them for a cut).

* table.rename: a PivotTable table source follows even when a defined name shadows it

A bare pivot source binds to the table before a defined name, so the
shadowing that keeps formula names on the defined name does not apply.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* model: rewrite_references keeps a chart source that was already broken

Only a source the edit breaks is dropped. A source already #REF! (from a
file or an earlier edit) stays as it was through an unrelated edit, such
as renaming a defined name it does not use.

* paste: a cut moves on its sheet as it is named now

A cut whose source sheet is renamed before the paste rebased its moved
rules, and the references to its cells, against the name the clipboard
saw, which no longer exists. A cut in the same workbook now uses the
live sheet name.

* formulas: renaming a defined name leaves LET and LAMBDA locals alone

The rename walk now tracks the locals in scope: a LET or LAMBDA local of
the old name is not the defined name and keeps its name, and a rename
that a local of the new name would capture is refused and changes
nothing. It is the one walk for cells, names, rules and Python cells.

* formulas: a name rename renames calls to it and is refused where a sheet name would take it

A call to a defined LAMBDA by name (`FnOld(4)`) now follows a rename of
the name; a called LET or LAMBDA local of the old name stays as it is.
A workbook name renamed to a name a sheet defines for itself would be
read as that sheet's name there, so that rename is refused.

* paste: a cut is refused as Paste Link or into filtered-out rows before its source is cleared

Paste Link would write links to the cells the cut empties, and a
destination in rows the filter hides would skip every cell the cut
writes; both lost the cut cells.

* sheets: a pending cut ends when a sheet edit puts another sheet in its place

A cut names its sheet by its place among the tabs, so after inserting,
deleting or moving a sheet before it, a paste took cells and rules from
whichever sheet had that place. The cut now ends when its place holds
another sheet (or none); a cut whose sheet kept its place stays, and a
copy reads its own snapshot and stays.

* model: a sheet-level name's references are rewritten on its own sheet

Unqualified references in a sheet-level name are read on its scope
sheet, so rewrite_references now hosts them there: inserting a row
above one moves it, as it moves a cell formula on that sheet.
Workbook-level names keep NAME_HOST.

* model: a PivotTable source that names a table is left out of a name's rewrite

A bare source that is a table's name reads the table before a defined
name of that name, so renaming the defined name no longer moves the
PivotTable off its table.

* sheet: a rule follows its top-left cell through a partial cell delete or insert

Deleting cells in only the first column of a rule's range keeps the
range's size, so it was treated as moved whole and its formulas stayed
written for the deleted cell (=A1>0 became =#REF!>0). When the cell the
shift puts at the top-left was one of the rule's own cells, the
formulas now follow it.

* sheet.moveColumns: a moved column's part of a rule reads what the column read

The moved part was taken after the columns were made room for, when the
rule's formula (written for its top-left) no longer said what the moved
cells read: a rule on B1:D1 testing =A1>0, with D moved before B, left
the moved cell testing old B instead of old C. The parts are now taken
from the sheet before the insert and follow it as the cells' formulas
do. move_cut_rules' placing half is place_moved_rules, shared.

* tests: the broken-chart-source test rewrites the chart it checks

A series now reads the renamed name, so the rename takes the branch that
rewrites the chart, and the test checks the series changed while the
broken source stayed.

* Revert "sheets: a pending cut ends when a sheet edit puts another sheet in its place"

This reverts commit 1569394173.

* Revert "paste: a cut is refused as Paste Link or into filtered-out rows before its source is cleared"

This reverts commit 80e7525d29.

* Revert "formulas: a name rename renames calls to it and is refused where a sheet name would take it"

This reverts commit c2ff358b58.

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
Aleksander Helgaker
2026-11-23 16:58:18 -06:00
committed by GitHub
co-authored by Claude Opus 5.5
parent 9bd3b7cf5d
commit 8a7fe1bec2
19 changed files with 1409 additions and 244 deletions
+1 -1
View File
@@ -34,7 +34,7 @@ use tools::split_delimited;
use tools::{remove_duplicates, text_to_columns};
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(super) use validation::{move_rule_formula, moved_rule_parts, remove_rule_cells, remove_validation_cells};
pub fn specs() -> Vec<CommandSpec> {
vec![
+55 -7
View File
@@ -87,19 +87,67 @@ fn subtract_ranges(r: RangeRef, cuts: &[RangeRef]) -> Vec<RangeRef> {
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<RangeRef>, Vec<&mut String>);
}
impl Rule for Validation {
fn parts(&mut self) -> (&mut Vec<RangeRef>, 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<RangeRef>, 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<Validation>, cuts: &[RangeRef]) {
for dv in validations.iter_mut() {
let before = RangeRef::top_left(&dv.ranges);
dv.ranges = dv.ranges.iter().flat_map(|r| subtract_ranges(*r, cuts)).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));
remove_rule_cells(validations, cuts);
}
/// [`remove_validation_cells`] for any kind of rule.
pub(in super::super) fn remove_rule_cells<T: Rule>(rules: &mut Vec<T>, cuts: &[RangeRef]) {
for rule in rules.iter_mut() {
let (ranges, formulas) = rule.parts();
let before = RangeRef::top_left(ranges);
*ranges = ranges.iter().flat_map(|r| subtract_ranges(*r, cuts)).collect();
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<T: Rule>(rules: &[T], block: RangeRef, to: CellRef) -> Vec<T> {
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<RangeRef> = ranges.iter().filter_map(|r| r.intersection(&block)).collect();
let Some(from) = RangeRef::top_left(&inside) else { continue };
let moved: Vec<RangeRef> = 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<Json> {
+1 -1
View File
@@ -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_many, rewrite_cell_links, rewrite_python_refs};
pub(crate) use paste_special::{place_moved_rules, rewrite_all_formulas_many, 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<CommandSpec> {
+97 -83
View File
@@ -79,7 +79,18 @@ pub(super) fn paste_special(s: &mut Session, p: &Json) -> Result<Json> {
let cut_move = clip.cut && same_doc && what == What::All;
let src_wb = clip.wb.clone();
let Some(src_sheet) = src_wb.sheet(clip.sheet) else { return Err(EngineError::Other("The copied sheet no longer exists.".into())) };
let src_sheet_name = src_sheet.name.clone();
// The source sheet's name now: a cut whose sheet was renamed after it moves its cells,
// rules and the references to them on the sheet as it is named, not as the clipboard saw it.
let src_sheet_name = match s.doc()?.wb.sheet(clip.sheet) {
Some(live) if clip.cut && same_doc => live.name.clone(),
_ => src_sheet.name.clone(),
};
// A cut moves its block as it is, as Excel's does: it can't be transposed, tiled over a
// larger selection or pasted skipping blanks (the move's references, rules and arrays follow
// the whole block unturned, and its rules replace the destination's under every cell).
if cut_move && (transpose || skip_blanks || tiles_r > 1 || tiles_c > 1) {
return Err(EngineError::Other("The cut area can only be pasted as it is: paste it without Transpose or Skip Blanks, into one cell.".into()));
}
edit(s, |cx| {
// Styles from another workbook must be re-interned.
let dest_name = cx.wb.sheet(dest_sheet).map(|sh| sh.name.clone()).unwrap_or_default();
@@ -92,6 +103,9 @@ pub(super) fn paste_special(s: &mut Session, p: &Json) -> Result<Json> {
};
let mut moved_formulas = std::collections::BTreeMap::new();
let mut moved_pictures = std::collections::BTreeMap::new();
// A cut moves the rules its cells hold now, not the clipboard's: rules cleared or added
// since the cut would otherwise come back or be lost.
let live_source = if cut_move { cx.wb.sheet(clip.sheet).cloned() } else { None };
if cut_move {
// Remove the source first (contents and formats), and fix references to it.
let source = cx.sheet_mut(clip.sheet)?;
@@ -347,7 +361,8 @@ pub(super) fn paste_special(s: &mut Session, p: &Json) -> Result<Json> {
}
}
let pasted = RangeRef::new(at, at.offset_clamped(i64::from(tiles_r * h) - 1, i64::from(tiles_c * w) - 1));
if !link && matches!(what, What::All | What::AllExceptBorders | What::Validation) {
// A cut takes its rules along itself (`move_cut_rules`, below).
if !link && !cut_move && matches!(what, What::All | What::AllExceptBorders | What::Validation) {
paste_validations(cx, src_sheet, src, dest_sheet, pasted, PasteMode { transpose, skip_blanks, skip_rows: &skip_rows })?;
}
if what == What::ColumnWidths {
@@ -379,7 +394,8 @@ pub(super) fn paste_special(s: &mut Session, p: &Json) -> Result<Json> {
}
}
}
if cut_move {
if let Some(live) = &live_source {
move_cut_rules(cx, live, (clip.sheet, dest_sheet), src, at)?;
// References elsewhere to the moved block now point to its new place.
let e = if dest_sheet == clip.sheet {
gridcraft_formula::adjust::Edit::Move { from: src, to_row: at.row, to_col: at.col }
@@ -564,7 +580,67 @@ fn paste_validations(
Ok(())
}
/// Applies a reference adjustment to every cell formula and defined name in the workbook.
/// A cut, or Move Columns, 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 moved 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 before the block moved.
pub(crate) fn move_cut_rules(
cx: &mut crate::cmd::Ctx,
snapshot: &gridcraft_model::Sheet,
(from, to): (usize, usize),
src: RangeRef,
at: CellRef,
) -> Result<()> {
let mut cfs: Vec<gridcraft_model::CondFormat> = crate::cmd::data::moved_rule_parts(&snapshot.cond_formats, src, at);
let mut dvs: Vec<gridcraft_model::Validation> = 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));
}
};
// Every formula, thresholds included: an unnamed reference would read the destination sheet.
cfs.iter_mut().flat_map(|r| r.rule.formulas_mut()).for_each(name);
dvs.iter_mut().flat_map(|r| r.formulas_mut()).for_each(name);
}
place_moved_rules(cx, (from, to), src, at, (cfs, dvs))
}
/// Takes the rules off the cells of `src` on sheet `from` and puts `parts` (the moved parts of
/// them, as [`move_cut_rules`] builds them) on the block at `at` on sheet `to`, in place of the
/// rules there.
pub(crate) fn place_moved_rules(
cx: &mut crate::cmd::Ctx,
(from, to): (usize, usize),
src: RangeRef,
at: CellRef,
(cfs, dvs): (Vec<gridcraft_model::CondFormat>, Vec<gridcraft_model::Validation>),
) -> Result<()> {
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`]) 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<()> {
rewrite_all_formulas_many(wb, target, std::slice::from_ref(e))
}
@@ -572,90 +648,28 @@ pub(crate) fn rewrite_all_formulas(wb: &mut gridcraft_model::Workbook, target: &
/// [`rewrite_all_formulas`] for several edits applied in order, visiting each formula once.
pub(crate) fn rewrite_all_formulas_many(wb: &mut gridcraft_model::Workbook, target: &str, edits: &[gridcraft_formula::adjust::Edit]) -> Result<()> {
use gridcraft_formula::adjust::Edit;
let adjust_all =
|host: &str, expr: gridcraft_formula::Expr| edits.iter().fold(expr, |expr, e| gridcraft_formula::adjust::adjust(expr, host, target, e));
wb.rewrite_references(&|host, expr| adjust_all(host.name, expr));
// 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 = |e: &Edit| 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<Formula>)> =
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 = host.eq_ignore_ascii_case(target);
let Some(sheet) = wb.sheet_mut(si) else { continue };
for (c, f) in keys {
// Borrows the tree and copies and prints only the formulas the edits change. A formula
// the edits leave alone keeps its stored text, even if that text is not canonical.
let Some(new) = f.with_expr(|x| {
let mut cur: Option<gridcraft_formula::Expr> = None;
for e in edits {
if let Some(n) = gridcraft_formula::adjust::adjust_if_changed(cur.as_ref().unwrap_or(x), &host, target, e) {
cur = Some(n);
}
}
cur
}) else {
continue;
};
let mut array = f.array;
for e in edits {
array = match array {
Some(a) if on_target && moves_arrays(e) => crate::cmd::sheet::map_range(a, e),
a => a,
};
}
let nf = match new {
Some(new) => Formula { array, dynamic: f.dynamic, ..Formula::from_expr(new) },
None if array != f.array => Formula { array, ..(*f).clone() },
None => continue,
};
if let Some(cell) = sheet.cells.get_mut(c) {
cell.formula = Some(std::sync::Arc::new(nf));
let moves_arrays = |e: &&Edit| matches!(e, Edit::Insert { .. } | Edit::Delete { .. } | Edit::InsertCells { .. } | Edit::DeleteCells { .. });
if edits.iter().any(|e| moves_arrays(&e))
&& let Some(si) = wb.sheet_index(target)
&& let Some(sheet) = wb.sheet_mut(si)
{
let arrays: Vec<(CellRef, std::sync::Arc<Formula>)> =
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 = edits.iter().filter(moves_arrays).fold(f.array, |a, e| a.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() }));
}
}
}
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 = edits.iter().fold(expr, |expr, e| gridcraft_formula::adjust::adjust(expr, "\u{0}", target, e));
n.formula = gridcraft_formula::print(&new);
}
}
rewrite_cell_links(wb, |host, expr| edits.iter().fold(expr, |expr, e| gridcraft_formula::adjust::adjust(expr, host, target, e)));
rewrite_python_refs(wb, &|host, expr| edits.iter().fold(expr, |expr, e| 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, and a form control's linked
/// cell). 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() || !s.controls.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(),
}
};
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);
}
}
for c in sh.controls.iter_mut() {
c.link = c.link.as_deref().map(fix);
}
}
rewrite_python_refs(wb, &adjust_all)
}
/// Rewrites the `xl("…")` literals in every Python cell with `f`, which maps a reference held on
+112 -35
View File
@@ -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::{
@@ -408,10 +408,12 @@ fn define_name(s: &mut Session, p: &Json) -> Result<Json> {
};
edit(s, |cx| {
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));
// Formulas are renamed while the old name is still defined, so a chart series named
// by it is still read as a reference.
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(old_name) && n.scope == *old_scope));
}
cx.wb.names.retain(|n| !(n.name.eq_ignore_ascii_case(&name) && n.scope == scope));
cx.wb.names.push(DefinedName { name: name.clone(), scope, formula: refers.clone(), comment: comment.clone(), hidden: false });
@@ -420,49 +422,124 @@ fn define_name(s: &mut Session, p: &Json) -> Result<Json> {
})
}
/// Formulas that use a renamed name follow it: cell formulas and other names' definitions, on
/// References to a renamed name follow it: every one the workbook holds
/// ([`gridcraft_model::Workbook::rewrite_references`]) and Python cells' `xl()` references, 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<usize>, new: &str) {
fn rename_name_in_formulas(wb: &mut gridcraft_model::Workbook, old: &str, old_scope: Option<usize>, new: &str) -> Result<()> {
let shadowed: Vec<usize> = 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,
None => !shadowed.contains(&sheet),
};
// The renamed expression, or `None` when the name doesn't occur in it.
// Set when an occurrence would be captured by a LET or LAMBDA local of the new name.
let captured = std::cell::Cell::new(false);
let rename = |e: gridcraft_formula::Expr| {
let mut hit = false;
let out = e.map(&mut |x| match x {
gridcraft_formula::Expr::Name(n) if n.eq_ignore_ascii_case(old) => {
hit = true;
gridcraft_formula::Expr::Name(new.to_string())
}
o => o,
});
hit.then_some(out)
let mut bound = Vec::new();
rename_free_name(e, old, new, &mut bound, &captured, 0)
};
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<Formula>)> = 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));
}
}
// 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) } else { e });
// Python cells' `xl("…")` references too.
let sheet_of: std::collections::HashMap<String, usize> = 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) } else { e }
})?;
if captured.get() {
return Err(EngineError::Other(format!(
"The name can't be changed to {new}: a LET or LAMBDA in a formula that uses it already has a local name {new}."
)));
}
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);
Ok(())
}
/// `e` with every free occurrence of the name `old` renamed to `new`. A LET or LAMBDA local is not
/// the defined name, so its own occurrences (of `old`) are left alone, and a free occurrence
/// inside the scope of a local named `new` would be captured by it: that sets `captured`. `bound`
/// holds the locals in scope. Nesting deeper than any formula the parser accepts is left as it is.
fn rename_free_name(
e: gridcraft_formula::Expr,
old: &str,
new: &str,
bound: &mut Vec<String>,
captured: &std::cell::Cell<bool>,
depth: usize,
) -> gridcraft_formula::Expr {
use gridcraft_formula::Expr;
const MAX_DEPTH: usize = 512;
if depth > MAX_DEPTH {
return e;
}
let is_bound = |bound: &[String], n: &str| bound.iter().any(|b| b.eq_ignore_ascii_case(n));
let walk = |e: Expr, bound: &mut Vec<String>| rename_free_name(e, old, new, bound, captured, depth + 1);
match e {
Expr::Name(n) if n.eq_ignore_ascii_case(old) && !is_bound(bound, &n) => {
if is_bound(bound, new) {
captured.set(true);
}
Expr::Name(new.to_string())
}
Expr::Call(name, args) if name == "LET" && args.len() >= 3 && !args.len().is_multiple_of(2) => {
let saved = bound.len();
let mut args = args;
// The arguments are odd in number: pairs of a declaration and its value, then the body.
let body = args.pop();
let mut out = Vec::with_capacity(args.len() + 1);
let mut pairs = args.into_iter();
while let (Some(declaration), Some(value)) = (pairs.next(), pairs.next()) {
// A value comes before its own local is in scope; the declaration is the local's
// own name, never the defined name.
let value = walk(value, bound);
if let Expr::Name(n) = &declaration {
bound.push(n.clone());
}
out.push(declaration);
out.push(value);
}
out.extend(body.map(|b| walk(b, bound)));
bound.truncate(saved);
Expr::Call(name, out)
}
Expr::Call(name, args) if name == "LAMBDA" => {
let saved = bound.len();
let last = args.len().saturating_sub(1);
let mut out = Vec::with_capacity(args.len());
for (i, arg) in args.into_iter().enumerate() {
if i == last {
out.push(walk(arg, bound));
} else {
if let Expr::Name(n) = &arg {
bound.push(n.clone());
}
out.push(arg);
}
}
bound.truncate(saved);
Expr::Call(name, out)
}
Expr::Call(name, args) => Expr::Call(name, args.into_iter().map(|a| walk(a, bound)).collect()),
Expr::Invoke(callee, args) => Expr::Invoke(Box::new(walk(*callee, bound)), args.into_iter().map(|a| walk(a, bound)).collect()),
Expr::Array(rows) => Expr::Array(rows.into_iter().map(|r| r.into_iter().map(|x| walk(x, bound)).collect()).collect()),
Expr::Unary(op, x) => Expr::Unary(op, Box::new(walk(*x, bound))),
Expr::Binary(op, a, b) => {
// A long operator chain is unwound, not recursed into once per operand (as
// `Expr::map` does), so its length doesn't count toward the nesting limit.
let mut spine = vec![(op, b)];
let mut node = *a;
while let Expr::Binary(op, a, b) = node {
spine.push((op, b));
node = *a;
}
let mut acc = walk(node, bound);
while let Some((op, b)) = spine.pop() {
let b = walk(*b, bound);
acc = Expr::Binary(op, Box::new(acc), Box::new(b));
}
acc
}
Expr::Paren(x) => Expr::Paren(Box::new(walk(*x, bound))),
other => other,
}
}
+6 -17
View File
@@ -1,7 +1,7 @@
use super::{
Anchor, BorderLine, BorderStyle, Borders, CellRef, CfOperator, CfRule, CfValueKind, Color, CondFormat, EngineError, Fill, Json, RangeRef, Result,
Session, Shape, ShapeKind, Style, anchor_mode_param, bad, bool_param, cell_param, edit, f64_param, json, ok, str_param, target_ranges,
target_sheet, u32_param,
Anchor, BorderLine, BorderStyle, Borders, CfOperator, CfRule, CfValueKind, Color, CondFormat, EngineError, Fill, Json, RangeRef, Result, Session,
Shape, ShapeKind, Style, anchor_mode_param, bad, bool_param, cell_param, edit, f64_param, json, ok, str_param, target_ranges, target_sheet,
u32_param,
};
#[cfg(test)]
@@ -282,7 +282,9 @@ pub(super) fn clear_cf(s: &mut Session, p: &Json) -> Result<Json> {
// 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());
@@ -291,19 +293,6 @@ pub(super) fn clear_cf(s: &mut Session, p: &Json) -> Result<Json> {
})
}
/// 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),
_ => {}
}
}
pub(super) fn manage_cf(s: &mut Session, p: &Json) -> Result<Json> {
let sheet = target_sheet(s, p)?;
if p.get("delete").is_none() && p.get("moveUp").is_none() && p.get("moveDown").is_none() {
+29 -18
View File
@@ -293,28 +293,39 @@ pub(super) fn table_rename(s: &mut Session, p: &Json) -> Result<Json> {
if let Some(t) = cx.sheet_mut(si)?.tables.get_mut(ti) {
t.name = name.clone();
}
// Structured references follow the rename.
// 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; in a
// workbook name, that is a workbook-level defined name.
let shadowed: Vec<bool> = (0..cx.wb.sheets.len()).map(|i| cx.wb.name(&old, i).is_some()).collect();
let shadowed_in_book = cx.wb.names.iter().any(|n| n.scope.is_none() && n.name.eq_ignore_ascii_case(&old));
let sheet_of: std::collections::HashMap<String, usize> =
cx.wb.sheets.iter().enumerate().map(|(i, s)| (s.name.to_ascii_lowercase(), i)).collect();
let rename = |sheet: Option<usize>, e: gridcraft_formula::Expr| {
let shadow = sheet.map_or(shadowed_in_book, |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));
// A bare PivotTable source binds to a table before a defined name (`pivot::resolve_source`),
// so a defined name with the old name doesn't shadow it: it follows the rename regardless.
for i in 0..cx.wb.sheets.len() {
let keys: Vec<(CellRef, std::sync::Arc<Formula>)> =
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)));
let names_old = |src: &str| src.trim().trim_start_matches('=').trim().eq_ignore_ascii_case(&old);
if !cx.wb.sheet(i).is_some_and(|sh| sh.pivots.iter().any(|pt| names_old(&pt.source))) {
continue;
}
for pt in &mut cx.sheet_mut(i)?.pivots {
if names_old(&pt.source) {
pt.source = name.clone();
}
}
}
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)
})
+35
View File
@@ -1428,3 +1428,38 @@ fn legacy_count_numbers_caption_follows_the_function() {
assert_eq!(text(&s, "E3"), after, "{legacy}");
}
}
/// A defined name with a table's name doesn't stop a PivotTable's table source following a rename
/// of the table: a bare source binds to the table first.
#[test]
fn a_table_rename_moves_a_pivot_source_a_defined_name_shadows() {
let mut s = sales();
s.execute("insert.table", json!({"range": "A1:E13"})).unwrap();
s.execute("selection.set", json!({"range": "B2"})).unwrap();
s.execute("table.summarizePivot", json!({"rows": ["Product"], "values": ["Units"]})).unwrap();
assert_eq!(pt(&s).source, "Table1");
s.execute("formulas.defineName", json!({"name": "Table1", "refersTo": "=Sheet1!$A$1:$B$3"})).unwrap();
s.execute("table.rename", json!({"table": "Table1", "name": "Data"})).unwrap();
assert_eq!(pt(&s).source, "Data");
s.execute("pivot.refresh", json!({})).unwrap();
let gt = find_row(&s, "Grand Total").unwrap();
assert_eq!(val(&s, &CellRef::new(gt, 1).a1()), Value::Number(72.0));
}
/// A PivotTable source that is a table's name reads the table before a defined name of that name,
/// so renaming the defined name leaves it on the table; a source that is the defined name's own
/// follows the rename.
#[test]
fn renaming_a_defined_name_leaves_a_table_source_on_its_table() {
let mut s = sales();
s.execute("insert.table", json!({"range": "A1:E13", "name": "Data"})).unwrap();
s.execute("formulas.defineName", json!({"name": "Data", "refersTo": "=Sheet1!$A$1:$E$3"})).unwrap();
s.execute("selection.set", json!({"range": "B2"})).unwrap();
s.execute("table.summarizePivot", json!({"rows": ["Product"], "values": ["Units"]})).unwrap();
assert_eq!(pt(&s).source, "Data");
s.execute("formulas.defineName", json!({"name": "Choices", "oldName": "Data", "refersTo": "=Sheet1!$A$1:$E$3"})).unwrap();
assert_eq!(pt(&s).source, "Data");
s.execute("pivot.refresh", json!({})).unwrap();
let gt = find_row(&s, "Grand Total").unwrap();
assert_eq!(val(&s, &CellRef::new(gt, 1).a1()), Value::Number(72.0));
}
+109 -35
View File
@@ -154,7 +154,10 @@ 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 before = std::mem::take(&mut cf.ranges);
let moves: Vec<(RangeRef, RangeRef)> = before.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(), &before, &moves, &e);
}
for er in sh.edit_ranges.iter_mut() {
er.ranges = er.ranges.iter().filter_map(|r| map_range(*r)).collect();
@@ -162,7 +165,10 @@ 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 before = std::mem::take(&mut dv.ranges);
let moves: Vec<(RangeRef, RangeRef)> = before.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(), &before, &moves, &e);
}
sh.validations.retain(|dv| !dv.ranges.is_empty());
for t in sh.tables.iter_mut() {
@@ -239,8 +245,7 @@ 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<()> {
rewrite_many(cx, target, std::slice::from_ref(e))
}
@@ -248,34 +253,7 @@ pub(super) fn rewrite(cx: &mut Ctx, target: &str, e: &Edit) -> Result<()> {
/// [`rewrite`] for several edits applied in order, parsing each reference once.
fn rewrite_many(cx: &mut Ctx, target: &str, edits: &[Edit]) -> Result<()> {
cx.edits.extend(edits.iter().map(|e| (target.to_string(), e.clone())));
let wb = &mut cx.wb;
super::edit::rewrite_all_formulas_many(wb, target, edits)?;
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(&edits.iter().fold(expr, |expr, e| 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(&edits.iter().fold(expr, |expr, e| gridcraft_formula::adjust::adjust(expr, &host, target, e)));
if after != before {
pt.source = after;
}
}
}
}
Ok(())
super::edit::rewrite_all_formulas_many(&mut cx.wb, target, edits)
}
/// Inserting or deleting cells moves the copied block away from the stored source range, so, like
@@ -442,15 +420,37 @@ fn move_columns(s: &mut Session, p: &Json) -> Result<Json> {
let out = edit(s, |cx| {
let name = cx.wb.sheet(sheet).map(|sh| sh.name.clone()).unwrap_or_default();
cx.protection_checked = true;
// The moved columns' rules go with them as a cut's do, so a rule wider than them stays on
// its other cells and checks what it did. Their parts are taken from the sheet before the
// columns are made room for: a rule's formulas are written for its top-left cell, and
// after the insert they no longer say what the moved cells read (a reference between the
// rule's top-left and the moved columns has moved, the top-left has not).
let insert = Edit::Insert { axis: Axis::Cols, at: before, count };
let original = cx.wb.sheets.get(sheet).cloned().ok_or_else(|| bad("sheet.moveColumns", "no such sheet"))?;
let at = CellRef::new(0, destination);
let block = RangeRef::cols(from, end - 1);
let mut cfs: Vec<gridcraft_model::CondFormat> = crate::cmd::data::moved_rule_parts(&original.cond_formats, block, at);
let mut dvs: Vec<gridcraft_model::Validation> = crate::cmd::data::moved_rule_parts(&original.validations, block, at);
// Each part's formulas, written for the moved cells where they stood, follow the insert
// as those cells' formulas do; the move and delete below then rewrite them in place.
let follow_insert = |t: &mut String| {
if let Ok(e) = gridcraft_formula::parse(t.trim_start_matches('=')) {
let e = gridcraft_formula::adjust::adjust(e, &name, &name, &insert);
*t = format!("{}{}", if t.starts_with('=') { "=" } else { "" }, gridcraft_formula::print(&e));
}
};
cfs.iter_mut().flat_map(|r| r.rule.formulas_mut()).for_each(follow_insert);
dvs.iter_mut().flat_map(|r| r.formulas_mut()).for_each(follow_insert);
{
let sh = cx.sheet_mut(sheet)?;
sh.cells.shift_cols(before, count as i64);
shift_sheet_features(sh, Axis::Cols, before, count, true);
}
rewrite(cx, &name, &Edit::Insert { axis: Axis::Cols, at: before, count })?;
rewrite(cx, &name, &insert)?;
let mut touched = Vec::new();
crate::cmd::edit::place_moved_rules(cx, (sheet, sheet), source, at, (cfs, dvs))?;
{
let sh = cx.sheet_mut(sheet)?;
let pictures: Vec<_> =
@@ -458,6 +458,7 @@ fn move_columns(s: &mut Session, p: &Json) -> Result<Json> {
let cells = sh.take_cells(source);
let moved_lines: Vec<_> = (0..count).filter_map(|offset| sh.cols.remove(&(moved_from + offset)).map(|info| (offset, info))).collect();
let movement = Edit::Move { from: source, to_row: 0, to_col: destination };
// (Its conditional formats and validation no longer touch the moved columns.)
shift_cell_features(sh, &movement);
for object in sh
.charts
@@ -752,13 +753,83 @@ pub(crate) fn map_range(r: RangeRef, e: &Edit) -> Option<RangeRef> {
}
}
/// 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;
/// one cut short (its first cells deleted), or one whose own cells an insert or delete of cells
/// shifted only in part into its top-left, takes the cell that moved into its place.
/// `before` is every range the rule had before the edit (the formulas are written for their
/// top-left cell, which may lie in a range the edit removed).
fn rehost_rule(formulas: Vec<&mut String>, before: &[RangeRef], moves: &[(RangeRef, RangeRef)], e: &Edit) {
let (Some(from), Some(to)) = (RangeRef::top_left(before), RangeRef::top_left(&moves.iter().map(|(_, m)| *m).collect::<Vec<_>>())) 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,
});
// Inserting or deleting cells can shift part of a range and keep its size (cells deleted in
// its first column only, say): when the cell the shift put at its top-left was one of the
// rule's own cells, the formulas follow that cell.
let shifted_in = matches!(e, Edit::InsertCells { .. } | Edit::DeleteCells { .. })
.then(|| pre_image(e, to))
.filter(|p| *p != to && before.iter().any(|r| r.contains(*p)));
let at = match holder {
Some(_) if shifted_in.is_some() => shifted_in.unwrap_or(to),
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 before = std::mem::take(&mut cf.ranges);
let moves: Vec<(RangeRef, RangeRef)> = before.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(), &before, &moves, e);
}
for er in sh.edit_ranges.iter_mut() {
er.ranges = er.ranges.iter().filter_map(|r| map_range(*r, e)).collect();
@@ -766,7 +837,10 @@ 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 before = std::mem::take(&mut dv.ranges);
let moves: Vec<(RangeRef, RangeRef)> = before.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(), &before, &moves, e);
}
sh.validations.retain(|dv| !dv.ranges.is_empty());
for t in sh.tables.iter_mut() {
+35 -43
View File
@@ -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<Json> {
if s.doc()?.wb.protected_structure {
@@ -50,37 +50,16 @@ pub(super) fn delete_sheet(s: &mut Session, p: &Json) -> Result<Json> {
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<gridcraft_model::Formula>)> =
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 {
// Only formulas whose tree changes are rewritten; the others keep their text.
let changed = f.with_expr(|e| Some(gridcraft_formula::adjust::delete_sheet(e.clone(), &name, &order)).filter(|ne| ne != e));
if let Some(Some(ne)) = changed
&& 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)));
@@ -105,21 +84,17 @@ pub(super) fn rename_sheet(s: &mut Session, p: &Json) -> Result<Json> {
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));
// A PivotChart follows its PivotTable's sheet. Only a sheet holding such a chart is
// copied, so the others stay shared with undo snapshots.
let on_old = |link: Option<&str>| link.and_then(crate::pivot::parse_chart_link).is_some_and(|(sheet, _)| sheet.eq_ignore_ascii_case(&old));
for si in 0..cx.wb.sheets.len() {
let keys: Vec<(CellRef, Arc<gridcraft_model::Formula>)> =
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 {
// Compares trees, so unchanged formulas are not printed; they keep their text.
let changed = f.with_expr(|e| Some(gridcraft_formula::adjust::rename_sheet(e.clone(), &old, &name)).filter(|ne| ne != e));
if let Some(Some(ne)) = changed
&& let Some(cell) = sh.cells.get_mut(c)
{
cell.formula = Some(Arc::new(gridcraft_model::Formula::from_expr(ne)));
}
if !cx.wb.sheets.get(si).is_some_and(|sh| sh.charts.iter().any(|ch| on_old(ch.pivot.as_deref()))) {
continue;
}
let Some(sh) = cx.wb.sheet_mut(si) else { continue };
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)
&& sheet.eq_ignore_ascii_case(&old)
{
@@ -127,12 +102,6 @@ pub(super) fn rename_sheet(s: &mut Session, p: &Json) -> Result<Json> {
}
}
}
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)
@@ -164,6 +133,29 @@ pub(super) fn move_sheet(s: &mut Session, p: &Json) -> Result<Json> {
.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).
// Text that names no other sheet is kept as written (a leading `=` included).
let copy = sh.name.clone();
let fix = |t: &mut String| {
let Ok(e) = gridcraft_formula::parse(t.trim_start_matches('=')) else { return };
let before = gridcraft_formula::print(&e);
let after = gridcraft_formula::print(&gridcraft_formula::adjust::rename_sheet(e, &base, &copy));
if after != before {
*t = if t.starts_with('=') { format!("={after}") } else { after };
}
};
for ch in &mut sh.charts {
for se in &mut ch.series {
fix(&mut se.values);
for t in [&mut se.categories, &mut se.name, &mut se.bubble_sizes].into_iter().flatten() {
fix(t);
}
}
if let Some(t) = ch.source.as_mut() {
fix(t);
}
}
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
+533
View File
@@ -155,6 +155,65 @@ fn editing_a_name_renames_it_in_formulas() {
assert!(s.execute("formulas.defineName", json!({"name": "X", "oldName": "Missing"})).is_err());
}
/// A LET or LAMBDA local is not the defined name: renaming the name leaves a local of the same
/// name alone, in cells and in rules.
#[test]
fn renaming_a_name_leaves_let_and_lambda_locals_alone() {
let mut s = s();
s.execute("formulas.defineName", json!({"name": "Rate", "refersTo": "=2"})).unwrap();
s.execute("cell.set", json!({"cell": "A1", "input": "=LET(Rate, 3, Rate*10)+Rate"})).unwrap();
s.execute("cell.set", json!({"cell": "A2", "input": "=LAMBDA(Rate, Rate+1)(Rate)"})).unwrap();
s.execute(
"home.conditionalFormat",
json!({"range": "B1:B3", "rule": {"type": "expression", "formula": "=LET(Rate, 1, Rate)<Rate"}, "style": {"fill": "#FFC7CE"}}),
)
.unwrap();
s.execute("formulas.defineName", json!({"name": "Fee", "refersTo": "=2", "oldName": "Rate"})).unwrap();
let formula =
|s: &Session, at: &str| s.doc().unwrap().wb.sheets[0].cell(CellRef::parse(at).unwrap()).and_then(|c| c.formula.clone()).unwrap().text.clone();
assert_eq!(formula(&s, "A1"), "LET(Rate,3,Rate*10)+Fee");
assert_eq!(formula(&s, "A2"), "LAMBDA(Rate,Rate+1)(Fee)");
assert_eq!(v(&s, "A1"), Value::number(32.0));
let rule = match &s.doc().unwrap().wb.sheets[0].cond_formats[0].rule {
gridcraft_model::CfRule::Expression { formula, .. } => formula.trim_start_matches('=').to_string(),
other => panic!("{other:?}"),
};
assert_eq!(rule, "LET(Rate,1,Rate)<Fee");
}
/// Renaming a name to one a LET local already uses where the name occurs would make the local
/// capture it: the rename is refused and changes nothing.
#[test]
fn renaming_a_name_onto_a_let_local_is_refused() {
let mut s = s();
s.execute("formulas.defineName", json!({"name": "Rate", "refersTo": "=2"})).unwrap();
s.execute("data.validation", json!({"range": "C1:C3", "type": "custom", "formula1": "=LET(Total, 1, Rate*Total)>0"})).unwrap();
let before = s.doc().unwrap().wb.clone();
let err = s.execute("formulas.defineName", json!({"name": "Total", "refersTo": "=2", "oldName": "Rate"}));
assert!(err.is_err(), "the LET local would capture the renamed name");
assert!(std::sync::Arc::ptr_eq(&s.doc().unwrap().wb, &before) || *s.doc().unwrap().wb == *before);
assert_eq!(s.doc().unwrap().wb.names[0].name, "Rate");
assert_eq!(s.doc().unwrap().wb.sheets[0].validations[0].f1.trim_start_matches('='), "LET(Total, 1, Rate*Total)>0");
}
/// A sheet-level name's unqualified references are read on its sheet, so they move with edits
/// there, and stay put for edits on other sheets.
#[test]
fn a_sheet_level_name_follows_edits_on_its_sheet() {
let mut s = s();
s.execute("home.insertSheet", json!({"name": "Other", "before": 1})).unwrap();
s.execute("range.setValues", json!({"range": "Sheet1!A2", "values": [[5]]})).unwrap();
s.execute("formulas.defineName", json!({"name": "LocalRef", "refersTo": "=$A$2", "scope": "Sheet1"})).unwrap();
let formula = |s: &Session| s.doc().unwrap().wb.names.iter().find(|n| n.name == "LocalRef").unwrap().formula.clone();
s.execute("home.insertRows", json!({"rows": "1:1", "sheet": "Other"})).unwrap();
assert_eq!(formula(&s), "$A$2");
s.execute("home.insertRows", json!({"rows": "1:1", "sheet": "Sheet1"})).unwrap();
assert_eq!(formula(&s), "$A$3");
s.execute("sheet.activate", json!({"sheet": 0})).unwrap();
s.execute("cell.set", json!({"cell": "C1", "input": "=LocalRef"})).unwrap();
assert_eq!(v(&s, "C1"), Value::number(5.0));
}
#[test]
fn chart_recommendations_follow_the_data_shape() {
// #215: Recommended Charts lists chart types for the data; programmatic insert stays dialog-free.
@@ -2143,6 +2202,20 @@ fn table_rename_keeps_a_defined_name_with_the_same_name() {
assert_eq!((v(&s, "E1"), v(&s, "F1")), (Value::Number(100.0), Value::Number(7.0)));
}
/// A workbook name that reads a same-named workbook name keeps reading it when the table is renamed.
#[test]
fn table_rename_keeps_a_workbook_name_reading_a_same_named_name() {
let mut s = s();
s.execute("range.setValues", json!({"range": "A1", "values": [["Qty"], [7]]})).unwrap();
s.execute("cell.set", json!({"cell": "D1", "input": "100"})).unwrap();
s.execute("insert.table", json!({"range": "A1:A2", "header": true, "name": "Data"})).unwrap();
s.execute("formulas.defineName", json!({"name": "Data", "refersTo": "=Sheet1!$D$1"})).unwrap();
s.execute("formulas.defineName", json!({"name": "Twice", "refersTo": "=Data*2"})).unwrap();
s.execute("table.rename", json!({"table": "Data", "name": "Later"})).unwrap();
let twice = s.doc().unwrap().wb.names.iter().find(|n| n.name == "Twice").map(|n| n.formula.clone());
assert_eq!(twice.as_deref(), Some("Data*2"));
}
#[test]
fn table_names_are_limited_to_255_characters() {
let mut s = s();
@@ -3929,6 +4002,41 @@ fn switch_row_column_follows_inserted_and_deleted_lines() {
assert_eq!(s.doc().unwrap().wb.active().unwrap().charts[0].source, None);
}
/// Sets the first chart's source on Sheet1 as a file might have left it.
fn set_chart_source(s: &mut Session, source: &str) {
let wb = std::sync::Arc::make_mut(&mut s.active_mut().unwrap().wb);
wb.sheet_mut(0).unwrap().charts[0].source = Some(source.into());
}
#[test]
fn a_chart_source_already_broken_survives_an_unrelated_edit() {
let mut s = s();
s.execute("range.setValues", json!({"range": "A1", "values": [["", "Q1", "Q2"], ["North", 1, 2], ["South", 3, 4]]})).unwrap();
s.execute("insert.chart", json!({"range": "A1:C3", "type": "column", "at": "F1"})).unwrap();
s.execute("formulas.defineName", json!({"name": "Rate", "refersTo": "=Sheet1!$A$1"})).unwrap();
set_chart_source(&mut s, "#REF!");
// A series reads the name, so the rename rewrites this chart; the source it doesn't use is
// left broken as it was.
let wb = std::sync::Arc::make_mut(&mut s.active_mut().unwrap().wb);
wb.sheet_mut(0).unwrap().charts[0].series[0].values = "=Rate".into();
s.execute("formulas.defineName", json!({"name": "Fee", "oldName": "Rate", "refersTo": "=Sheet1!$A$1"})).unwrap();
let chart = s.doc().unwrap().wb.sheet(0).unwrap().charts[0].clone();
assert_eq!(chart.series[0].values, "=Fee");
assert_eq!(chart.source.as_deref(), Some("#REF!"));
}
#[test]
fn deleting_a_chart_source_sheet_drops_the_source() {
let mut s = s();
s.execute("range.setValues", json!({"range": "A1", "values": [["", "Q1", "Q2"], ["North", 1, 2], ["South", 3, 4]]})).unwrap();
s.execute("insert.chart", json!({"range": "A1:C3", "type": "column", "at": "F1"})).unwrap();
s.execute("home.insertSheet", json!({})).unwrap();
set_chart_source(&mut s, "Sheet2!A1:C3");
// The edit breaks the source, so it goes.
s.execute("home.deleteSheet", json!({"sheet": "Sheet2"})).unwrap();
assert_eq!(s.doc().unwrap().wb.sheet(0).unwrap().charts[0].source, None);
}
#[test]
fn ink_strokes_and_ink_to_shape() {
let mut s = s();
@@ -7089,6 +7197,431 @@ 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 a PivotTable's source to it, and the PivotTable still refreshes.
#[test]
fn sheet_rename_renames_a_pivot_source() {
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();
}
/// A defined name's references are on no sheet, whatever a sheet is called: inserting rows on
/// a sheet named with a control character leaves a name's unqualified reference alone.
#[test]
fn names_are_on_no_sheet_whatever_the_sheet_is_called() {
let mut s = s();
s.execute("formulas.defineName", json!({"name": "Nm", "refersTo": "=$A$1"})).unwrap();
let before = s.doc().unwrap().wb.names.iter().find(|n| n.name == "Nm").map(|n| n.formula.clone());
s.execute("sheet.rename", json!({"sheet": 0, "name": "\u{0}"})).unwrap();
s.execute("home.insertRows", json!({"rows": "1:1"})).unwrap();
let after = s.doc().unwrap().wb.names.iter().find(|n| n.name == "Nm").map(|n| n.formula.clone());
assert!(before.is_some());
assert_eq!(before, after);
}
/// Renaming a sheet copies only the sheets whose references change: a sheet that doesn't name
/// it stays shared with the undo snapshot.
#[test]
fn sheet_rename_leaves_untouched_sheets_shared() {
let mut s = s();
s.execute("home.insertSheet", json!({"name": "Other"})).unwrap();
s.execute("home.insertSheet", json!({"name": "Third"})).unwrap();
s.execute("cell.set", json!({"cell": "Other!A1", "input": "=Sheet1!A1+1"})).unwrap();
// A constant: the full recalculation after a rename writes every formula cell's value, which
// copies a sheet that holds formulas whatever the rewrite does.
s.execute("cell.set", json!({"cell": "Third!A1", "input": "5"})).unwrap();
let before = s.doc().unwrap().wb.clone();
s.execute("sheet.rename", json!({"sheet": "Sheet1", "name": "Data"})).unwrap();
let wb = &s.doc().unwrap().wb;
let shared = |name: &str| std::sync::Arc::ptr_eq(&wb.sheets[wb.sheet_index(name).unwrap()], &before.sheets[before.sheet_index(name).unwrap()]);
assert!(shared("Third"), "Third doesn't name Sheet1");
assert!(!shared("Other"), "Other's formula names Sheet1");
}
/// 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::<Vec<_>>());
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();
// A series name written as a formula on no sheet keeps its `=`, and stays a reference.
std::sync::Arc::make_mut(&mut s.doc_mut().unwrap().wb).sheet_mut(0).unwrap().charts[0].series[0].name = Some("=A1".into());
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(&copy.name), "{}", copy.charts[0].series[0].values);
assert_eq!(copy.charts[0].series[0].name.as_deref(), Some("=A1"));
}
/// 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<String>, Vec<String>) {
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::<Vec<_>>().join(","))
}
_ => String::new(),
});
let dv = sh
.validations
.iter()
.map(|v| format!("{}@{}", v.f1.trim_start_matches('='), v.ranges.iter().map(|r| r.a1()).collect::<Vec<_>>().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<String> {
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::<Vec<_>>().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()]);
// A data bar's threshold goes along too: its cells into the block, the others on Sheet1.
s.execute("sheet.activate", json!({"sheet": one})).unwrap();
s.execute(
"home.conditionalFormat",
json!({"range": "Sheet1!H1:H10", "rule": {"type": "dataBar", "min": {"type": "formula", "value": "MIN(H1:H10,C1:C10)"}}}),
)
.unwrap();
s.execute("edit.cut", json!({"range": "Sheet1!H1:H10"})).unwrap();
s.execute("sheet.activate", json!({"sheet": two})).unwrap();
s.execute("edit.paste", json!({"at": "K1"})).unwrap();
assert_eq!(cf(&s, two).last().map(String::as_str), Some("bar MIN(Two!K1:K10,Sheet1!C1:C10)"));
}
/// A cut moves the rules its cells hold when it is pasted, not those they held when it was cut.
#[test]
fn a_cut_moves_the_rules_its_cells_hold_at_paste() {
let mut s = s();
s.execute("home.conditionalFormat", json!({"range": "A1:A3", "rule": {"type": "expression", "formula": "=A1>0"}, "style": {"fill": "#FFC7CE"}}))
.unwrap();
s.execute("edit.cut", json!({"range": "A1:A3"})).unwrap();
s.execute("home.clearRules", json!({"whole": true})).unwrap();
s.execute("data.validation", json!({"range": "A1:A3", "type": "custom", "formula1": "=A1>0"})).unwrap();
s.execute("edit.paste", json!({"at": "D1"})).unwrap();
let sh = &s.doc().unwrap().wb.sheets[0];
assert!(sh.cond_formats.is_empty(), "a cleared rule came back: {:?}", sh.cond_formats);
let dv: Vec<String> = sh.validations.iter().flat_map(|v| v.ranges.iter().map(|r| r.a1())).collect();
assert_eq!(dv, vec!["D1:D3".to_string()]);
}
/// A cut whose sheet is renamed before the paste still moves its rules and the references to
/// its cells: the move is made on the sheet as it is now named, not as the clipboard saw it.
#[test]
fn a_cut_pasted_after_its_sheet_is_renamed_moves_its_rules() {
let mut s = s();
s.execute("home.conditionalFormat", json!({"range": "A1:A3", "rule": {"type": "expression", "formula": "=A1>0"}, "style": {"fill": "#FFC7CE"}}))
.unwrap();
s.execute("data.validation", json!({"range": "A1:A3", "type": "custom", "formula1": "=A1>0"})).unwrap();
s.execute("cell.set", json!({"cell": "B5", "input": "=A1"})).unwrap();
s.execute("edit.cut", json!({"range": "A1:A3"})).unwrap();
s.execute("sheet.rename", json!({"name": "Data"})).unwrap();
s.execute("edit.paste", json!({"at": "D1"})).unwrap();
let sh = &s.doc().unwrap().wb.sheets[0];
let cf: Vec<String> = sh
.cond_formats
.iter()
.map(|c| match &c.rule {
gridcraft_model::CfRule::Expression { formula, .. } => format!("{}@{}", formula.trim_start_matches('='), c.ranges[0].a1()),
_ => String::new(),
})
.collect();
assert_eq!(cf, vec!["D1>0@D1:D3".to_string()]);
let dv: Vec<String> = sh.validations.iter().map(|v| format!("{}@{}", v.f1.trim_start_matches('='), v.ranges[0].a1())).collect();
assert_eq!(dv, vec!["D1>0@D1:D3".to_string()]);
assert_eq!(s.execute("cell.get", json!({"cell": "B5"})).unwrap()["formula"], "=D1");
}
/// Moving a column out of a wider rule takes its part of the rule with it, as a cut does: every
/// cell, moved or not, still checks itself.
#[test]
fn moving_a_column_out_of_a_rule_keeps_every_cell_checking_itself() {
let mut s = s();
s.execute("data.validation", json!({"range": "A1:C3", "type": "custom", "formula1": "=A1>0"})).unwrap();
s.execute("sheet.moveColumns", json!({"cols": "A:A", "before": 4})).unwrap();
let ok = |s: &Session, at: &str, input: &str| {
crate::cmd::data::check_validation(&s.doc().unwrap().wb, 0, gridcraft_core::CellRef::parse(at).unwrap(), input).is_none()
};
// Old A is now D; old B and C are A and B.
for at in ["A1", "B2", "D3"] {
assert!(ok(&s, at, "5"), "{at} takes 5");
assert!(!ok(&s, at, "-5"), "{at} refuses -5");
}
// Moved left, a whole range of the rule becomes its top-left: the parts left behind still
// check themselves.
let mut s = super::tests::s();
s.execute("data.validation", json!({"range": "B1:B3,D1:D3", "type": "custom", "formula1": "=B1>0"})).unwrap();
s.execute("sheet.moveColumns", json!({"cols": "D:D", "before": 1})).unwrap();
for at in ["B1", "C2"] {
assert!(ok(&s, at, "5"), "{at} takes 5");
assert!(!ok(&s, at, "-5"), "{at} refuses -5");
}
}
/// A rule's formulas are written for the top-left of all its ranges: when an edit removes the
/// range holding that cell, the rest re-host from it, not from their own top-left.
#[test]
fn rules_rehost_from_the_top_left_of_all_their_ranges() {
let texts = |s: &Session| -> (Vec<String>, Vec<String>) {
let sh = s.doc().unwrap().wb.sheets[0].clone();
let at = |ranges: &[gridcraft_core::RangeRef]| ranges.iter().map(|r| r.a1()).collect::<Vec<_>>().join(",");
let cf = sh.cond_formats.iter().map(|c| match &c.rule {
gridcraft_model::CfRule::Expression { formula, .. } => format!("{}@{}", formula.trim_start_matches('='), at(&c.ranges)),
_ => String::new(),
});
let dv = sh.validations.iter().map(|v| format!("{}@{}", v.f1.trim_start_matches('='), at(&v.ranges)));
(cf.collect(), dv.collect())
};
let setup = || {
let mut s = super::tests::s();
s.execute(
"home.conditionalFormat",
json!({"range": "A1:A5,C10:C12", "rule": {"type": "expression", "formula": "=A1>0"}, "style": {"fill": "#FFC7CE"}}),
)
.unwrap();
s.execute("data.validation", json!({"range": "A1:A5,E10:E12", "type": "custom", "formula1": "=A1>0"})).unwrap();
s
};
// Deleting the rows of the first area: the second keeps testing itself.
let mut s = setup();
s.execute("home.deleteRows", json!({"rows": "1:5"})).unwrap();
assert_eq!(texts(&s), (vec!["C5>0@C5:C7".to_string()], vec!["E5>0@E5:E7".to_string()]));
// Deleting the cells of the first area, shifting up or left: the second area stays put.
for shift in ["up", "left"] {
let mut s = setup();
s.execute("home.deleteCells", json!({"range": "A1:A5", "shift": shift})).unwrap();
assert_eq!(texts(&s), (vec!["C10>0@C10:C12".to_string()], vec!["E10>0@E10:E12".to_string()]), "shift {shift}");
}
}
/// A cut is pasted as it is: a transposed, tiled or skip-blanks paste of it is refused and
/// changes nothing, so its rules never land on a block of another shape than its cells, nor
/// replace a destination rule under a cell the paste leaves alone.
#[test]
fn a_cut_is_not_transposed_or_tiled() {
let mut s = s();
s.execute("range.setValues", json!({"range": "A1:C1", "values": [[1, 2, 3]]})).unwrap();
s.execute("home.conditionalFormat", json!({"range": "A1:C1", "rule": {"type": "expression", "formula": "=A1>0"}, "style": {"fill": "#FFC7CE"}}))
.unwrap();
s.execute("edit.cut", json!({"range": "A1:C1"})).unwrap();
assert!(s.execute("edit.pasteSpecial", json!({"what": "all", "transpose": true, "at": "E1"})).is_err());
assert!(s.execute("edit.pasteSpecial", json!({"what": "all", "skipBlanks": true, "at": "E1"})).is_err());
s.execute("selection.set", json!({"range": "E1:G2"})).unwrap();
assert!(s.execute("edit.pasteSpecial", json!({"what": "all"})).is_err());
let sh = s.doc().unwrap().wb.sheets[0].clone();
assert_eq!(sh.value(CellRef::new(0, 0)), Value::Number(1.0));
assert_eq!(sh.cond_formats[0].ranges.iter().map(|r| r.a1()).collect::<Vec<_>>(), vec!["A1:C1".to_string()]);
// Pasted as it is, the rule goes with the cells.
s.execute("edit.paste", json!({"at": "E1"})).unwrap();
assert_eq!(s.doc().unwrap().wb.sheets[0].cond_formats[0].ranges.iter().map(|r| r.a1()).collect::<Vec<_>>(), vec!["E1:G1".to_string()]);
}
/// Deleting cells in only the first column of a rule's range shifts its top-left cell and keeps the
/// range's size: the rule's formula follows the cell now there, not the deleted one.
#[test]
fn a_rule_follows_its_top_left_through_a_partial_cell_delete() {
let mut s = s();
s.execute("home.conditionalFormat", json!({"range": "A1:C3", "rule": {"type": "expression", "formula": "=A1>0"}, "style": {"fill": "#FFC7CE"}}))
.unwrap();
s.execute("data.validation", json!({"range": "A1:C3", "type": "custom", "formula1": "=A1<>B1"})).unwrap();
s.execute("home.deleteCells", json!({"range": "A1", "shift": "up"})).unwrap();
let sh = s.doc().unwrap().wb.sheets[0].clone();
let rule = match &sh.cond_formats[0].rule {
gridcraft_model::CfRule::Expression { formula, .. } => formula.trim_start_matches('=').to_string(),
other => panic!("{other:?}"),
};
assert_eq!(rule, "A1>0");
// The cell now at A1 came from A2, which compared itself with B2 (column B didn't move).
assert_eq!(sh.validations[0].f1.trim_start_matches('='), "A1<>B2");
}
/// A column moved out of a rule's range takes its part of the rule reading what the column read:
/// a rule on B1:D1 testing the cell to its left, with D moved before B, still tests old C (now D)
/// at the moved cell, and a rule on the moved column alone still tests that column.
#[test]
fn a_moved_column_keeps_what_its_part_of_a_rule_reads() {
let mut s = s();
s.execute("home.conditionalFormat", json!({"range": "B1:D1", "rule": {"type": "expression", "formula": "=A1>0"}, "style": {"fill": "#FFC7CE"}}))
.unwrap();
s.execute("data.validation", json!({"range": "D2", "type": "custom", "formula1": "=D2>0"})).unwrap();
s.execute("sheet.moveColumns", json!({"cols": "D:D", "before": 1})).unwrap();
let sh = s.doc().unwrap().wb.sheets[0].clone();
let mut rules: Vec<String> = 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::<Vec<_>>().join(","))
}
other => format!("{other:?}"),
})
.collect();
rules.sort();
assert_eq!(rules, vec!["A1>0@C1:D1".to_string(), "D1>0@B1".to_string()]);
assert_eq!(sh.validations[0].f1.trim_start_matches('='), "B2>0");
}
/// Internal hyperlinks keep the place they name as typed, as Excel's "Place in This Document"
/// links do: renaming or deleting a sheet, or inserting rows, leaves them as they were.
#[test]
fn internal_link_targets_stay_as_typed() {
let mut s = s();
s.execute("home.insertSheet", json!({"name": "Lists"})).unwrap();
let one = s.doc().unwrap().wb.sheet_index("Sheet1").unwrap();
s.execute("insert.link", json!({"cell": "Sheet1!A1", "target": "Lists!B5"})).unwrap();
s.execute("insert.link", json!({"cell": "Sheet1!A2", "target": "Sheet1!C9"})).unwrap();
s.execute("home.insertRows", json!({"rows": "1:1", "sheet": "Sheet1"})).unwrap();
let lists = s.doc().unwrap().wb.sheet_index("Lists").unwrap();
s.execute("sheet.rename", json!({"sheet": lists, "name": "Data"})).unwrap();
s.execute("home.deleteSheet", json!({"sheet": lists})).unwrap();
let wb = &s.doc().unwrap().wb;
let one = wb.sheet_index("Sheet1").unwrap_or(one);
let mut targets: Vec<String> = wb.sheets[one].hyperlinks.values().map(|h| h.target.clone()).collect();
targets.sort();
assert_eq!(targets, vec!["Lists!B5".to_string(), "Sheet1!C9".to_string()]);
}
#[test]
fn circle_invalid_says_when_its_scan_allowance_ended_early() {
let mut s = s();
+47
View File
@@ -252,6 +252,53 @@ fn chart_series_follow_cut_moves_renames_and_sheet_deletes() {
assert_eq!(values(&s), "Inputs!$A$1:$A$3");
}
/// A series name that is a bare word is a label, as a chart reads it: renaming a table of that
/// name leaves it be, while a series named by a defined name follows the name's rename.
#[test]
fn chart_series_names_follow_names_but_not_labels() {
let mut s = s();
s.execute("range.setValues", json!({"range": "A1", "values": [["v"], [5], [2]]})).unwrap();
s.execute("insert.table", json!({"range": "A1:A3", "name": "Sales"})).unwrap();
s.execute("formulas.defineName", json!({"name": "Title", "refersTo": "=Sheet1!$A$1"})).unwrap();
let chart = id_of(&s.execute("insert.chart", json!({"range": "A2:A3", "type": "column"})).unwrap(), "chart");
let set = |s: &mut Session, label: &str, named: &str| {
let ch = std::sync::Arc::make_mut(&mut s.doc_mut().unwrap().wb).sheet_mut(0).unwrap().charts.iter_mut().find(|c| c.id == chart).unwrap();
ch.series.truncate(1);
let mut second = ch.series[0].clone();
ch.series[0].name = Some(label.into());
second.name = Some(named.into());
ch.series.push(second);
};
let names = |s: &Session| -> Vec<String> {
sheet(s, 0).charts.iter().find(|c| c.id == chart).map(|c| c.series.iter().filter_map(|se| se.name.clone()).collect()).unwrap_or_default()
};
// A name another sheet holds isn't one this chart sees.
s.execute("home.insertSheet", json!({"name": "Two"})).unwrap();
s.execute("formulas.defineName", json!({"name": "Sales", "refersTo": "=Two!$A$1", "scope": "Two"})).unwrap();
set(&mut s, "Sales", "Title");
s.execute("table.rename", json!({"table": "Sales", "name": "Revenue"})).unwrap();
assert_eq!(names(&s), ["Sales", "Title"], "a label isn't the table");
s.execute("formulas.defineName", json!({"name": "Heading", "refersTo": "=Sheet1!$A$1", "oldName": "Title"})).unwrap();
assert_eq!(names(&s), ["Sales", "Heading"], "a defined name follows its rename");
// A label shaped like a cell is a label too.
set(&mut s, "Q1", "Sheet1!$A$1");
s.execute("home.insertRows", json!({"rows": "1:1", "sheet": "Sheet1"})).unwrap();
assert_eq!(names(&s), ["Q1", "Sheet1!$A$2"]);
}
/// A sheet may be named `#REF!`: a chart's source on it is not taken for one that's gone.
#[test]
fn a_chart_source_on_a_sheet_named_ref_error_is_kept() {
let mut s = s();
s.execute("range.setValues", json!({"range": "A1", "values": [[3], [5]]})).unwrap();
s.execute("insert.chart", json!({"range": "A1:A2", "type": "column"})).unwrap();
s.execute("sheet.rename", json!({"sheet": 0, "name": "#REF!"})).unwrap();
s.execute("home.insertSheet", json!({"name": "Other"})).unwrap();
s.execute("sheet.rename", json!({"sheet": "Other", "name": "Else"})).unwrap();
let source = sheet(&s, s.doc().unwrap().wb.sheet_index("#REF!").unwrap()).charts[0].source.clone();
assert_eq!(source.as_deref(), Some("'#REF!'!A1:A2"));
}
#[test]
fn a_copied_sheet_gives_its_objects_fresh_ids() {
let mut s = s();
+15
View File
@@ -531,6 +531,21 @@ fn python_code_with_an_empty_value_counts_as_content() {
assert!(s.execute("edit.paste", json!({"at": "R2"})).is_err_and(|e| e.to_string().contains("part of an array")));
}
/// Renaming a defined name or a table renames it in Python cells' `xl()` references too.
#[test]
fn xl_references_follow_name_and_table_renames() {
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("formulas.defineName", json!({"name": "Opts", "refersTo": "=Sheet1!$A$2:$A$3"})).unwrap();
plant(&mut s, 0, "E1", &format!("a = xl(\"Opts\")\nb = xl(\"{table}[v]\")"));
s.execute("formulas.defineName", json!({"name": "Choices", "oldName": "Opts", "refersTo": "=Sheet1!$A$2:$A$3"})).unwrap();
assert_eq!(code(&s, 0, "E1").as_deref(), Some(format!("a = xl(\"Choices\")\nb = xl(\"{table}[v]\")").as_str()));
s.execute("table.rename", json!({"table": table, "name": "Data"})).unwrap();
assert_eq!(code(&s, 0, "E1").as_deref(), Some("a = xl(\"Choices\")\nb = xl(\"Data[v]\")"));
}
#[test]
fn inserting_a_link_without_text_preserves_an_empty_python_cell() {
let mut s = s();
+3 -2
View File
@@ -293,8 +293,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,
+4
View File
@@ -238,6 +238,10 @@ fn rename_sheet_updates_qualified_names() -> Result<(), Box<dyn std::error::Erro
let e = rename_sheet(parse("Data!MyName")?, "Data", "It's");
assert_eq!(e, Expr::Name("It's!MyName".into()));
assert_eq!(print(&rename_sheet(e, "It's", "Totals")), "Totals!MyName");
// A sheet whose name holds a '!' splits at the last one: renaming "A" leaves "A!B"'s names alone.
let e = Expr::Name("A!B!MyName".into());
assert_eq!(rename_sheet(e.clone(), "A", "Z"), e);
assert_eq!(rename_sheet(e, "a!b", "Z"), Expr::Name("Z!MyName".into()));
Ok(())
}
+62
View File
@@ -234,6 +234,56 @@ pub enum CfRule {
}
impl CfRule {
/// The formulas written for the rule's range's top-left cell (and read at each cell
/// relative to it): a cell-value rule's values and an expression. What moving the rule
/// re-hosts. Thresholds (colour scale, data bar, icon set) are read as written.
pub fn relative_formulas_mut(&mut self) -> 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(),
}
}
/// [`CfRule::formulas_mut`], read only.
pub fn formulas(&self) -> Vec<&String> {
let kinds: Vec<&CfValueKind> = match self {
CfRule::CellIs { a, b, .. } => return std::iter::once(a).chain(b.as_ref()).collect(),
CfRule::Expression { formula, .. } => return vec![formula],
CfRule::ColorScale { stops } => stops.iter().map(|(k, _)| k).collect(),
CfRule::DataBar { min, max, .. } => vec![min, max],
CfRule::IconSet { thresholds, .. } => thresholds.iter().collect(),
_ => Vec::new(),
};
kinds
.into_iter()
.filter_map(|k| match k {
CfValueKind::Formula(t) => Some(t),
_ => None,
})
.collect()
}
/// 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()
}
/// The differential style a matching rule applies; colour scales, data bars and icon sets have none.
pub fn style(&self) -> Option<&Style> {
match self {
@@ -257,6 +307,18 @@ impl CfRule {
}
}
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()
}
/// [`Validation::formulas_mut`], read only.
pub fn formulas(&self) -> Vec<&String> {
std::iter::once(&self.f1).chain(self.f2.as_ref()).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
+1 -1
View File
@@ -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
+232
View File
@@ -343,7 +343,209 @@ 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<usize>,
/// The name unqualified references in it are on: its sheet's (a sheet-level defined name's
/// scope sheet, where they are read), or [`NAME_HOST`] for a workbook-level defined name
/// (read on whichever sheet uses it).
pub name: &'a str,
}
/// [`RefHost::name`] for a workbook-level defined name: `[` and `]` can't be in a sheet's name, so
/// no sheet's references are taken for a name's.
pub const NAME_HOST: &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<E>(t: &mut String, f: &dyn Fn(Expr) -> Expr, parse: fn(&str) -> Result<Expr, E>) -> 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) -> bool {
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), chart series (a chart's source block
/// the edit breaks is dropped; one already broken is kept), sparklines, PivotTable sources
/// (not one that is a table's name alone, which reads the table first) and form controls'
/// linked cells. The engine's reference-moving edits (renaming sheets and names, deleting sheets,
/// renaming tables, inserting and deleting lines and cells, cut-moves) go through it. Not
/// visited: table calculated-column and totals formulas, a PivotChart's link to its
/// PivotTable, a slicer's table, and Python cells' `xl()` references (the engine rewrites
/// the last itself, and a PivotChart's link on a sheet rename). A legacy array's own range is the
/// caller's to move. Internal
/// hyperlinks keep the place they name as typed, as Excel's do. A sheet nothing changes on
/// stays shared.
pub fn rewrite_references(&mut self, f: &dyn Fn(RefHost<'_>, Expr) -> Expr) {
let sheet_names: Vec<String> = self.sheets.iter().map(|s| s.name.clone()).collect();
for n in &mut self.names {
let name = n.scope.and_then(|i| sheet_names.get(i)).map_or(NAME_HOST, String::as_str);
let host = RefHost { sheet: n.scope, name };
rewrite_with(&mut n.formula, &|e| f(host, e), gridcraft_formula::parse_name);
}
// A series name is read by the chart as a reference when it starts with `=`, names a
// sheet (`!`) or is a defined name its sheet sees; anything else (a word, a table's
// name, `Q1`) is a label and is left as written.
let names: Vec<(String, Option<usize>)> = self.names.iter().map(|n| (n.name.to_lowercase(), n.scope)).collect();
// A PivotTable source that is a table's name alone reads the table before any defined
// name of that name (`pivot::resolve_source`), so a name's edit doesn't reach it.
let tables: Vec<String> = self.sheets.iter().flat_map(|s| s.tables.iter().map(|t| t.name.to_lowercase())).collect();
let table_source = |t: &str| tables.contains(&t.trim().trim_start_matches('=').trim().to_lowercase());
let label = |t: &str, si: usize| {
let t = t.trim();
let defined = || names.iter().any(|(n, scope)| scope.is_none_or(|s| s == si) && *n == t.to_lowercase());
!t.starts_with('=') && !t.contains('!') && !defined()
};
for (si, shared) in self.sheets.iter_mut().enumerate() {
// Worked out on the shared sheet; a list is copied only when something in it
// changes, and a sheet nothing changes on stays shared with undo snapshots.
let sh: &Sheet = shared;
let host = RefHost { sheet: Some(si), name: &sh.name };
let f = |e: Expr| f(host, e);
let changes = |t: &str| rewrite_with(&mut t.to_string(), &f, gridcraft_formula::parse);
let cells: Vec<(gridcraft_core::CellRef, Formula)> = sh
.cells
.iter()
.filter_map(|(c, cell)| {
// Trees are compared, not printed text: a formula the edit leaves alone keeps
// its stored text, even text that isn't canonical, and isn't printed.
let old = cell.formula.as_ref()?;
let new = old.with_expr(|e| Some(f(e.clone())).filter(|n| n != e))??;
Some((c, Formula { array: old.array, dynamic: old.dynamic, ..Formula::from_expr(new) }))
})
.collect();
let cond_formats = sh.cond_formats.iter().any(|cf| cf.rule.formulas().into_iter().any(|t| changes(t))).then(|| {
let mut v = sh.cond_formats.clone();
v.iter_mut().flat_map(|cf| cf.rule.formulas_mut()).for_each(|t| {
rewrite_text(t, &f);
});
v
});
let validations = sh.validations.iter().any(|dv| dv.formulas().into_iter().any(|t| changes(t))).then(|| {
let mut v = sh.validations.clone();
v.iter_mut().flat_map(|dv| dv.formulas_mut()).for_each(|t| {
rewrite_text(t, &f);
});
v
});
// A chart's source block that no longer exists is dropped.
// (Read from the tree: a sheet may be named `#REF!`.)
let dead = |src: Option<&str>| {
src.and_then(|s| gridcraft_formula::parse(s.trim_start_matches('=')).ok()).is_some_and(|e| {
let mut hit = false;
e.walk(&mut |x| hit |= matches!(x, Expr::Error(gridcraft_core::CellError::Ref)));
hit
})
};
let charts = sh
.charts
.iter()
.any(|ch| {
ch.source.as_deref().is_some_and(changes)
|| ch.series.iter().any(|se| {
changes(&se.values)
|| [&se.categories, &se.bubble_sizes].into_iter().flatten().any(|t| changes(t))
|| se.name.as_deref().is_some_and(|t| !label(t, si) && changes(t))
})
})
.then(|| {
let mut v = sh.charts.clone();
for ch in &mut v {
for se in &mut ch.series {
rewrite_text(&mut se.values, &f);
for t in [&mut se.categories, &mut se.bubble_sizes].into_iter().flatten() {
rewrite_text(t, &f);
}
if let Some(t) = se.name.as_mut().filter(|t| !label(t, si)) {
rewrite_text(t, &f);
}
}
// A source this edit breaks is dropped; one already broken before it
// (from a file, or an earlier edit) is kept as it was.
let was_dead = dead(ch.source.as_deref());
if let Some(src) = &mut ch.source {
rewrite_text(src, &f);
}
if !was_dead && dead(ch.source.as_deref()) {
ch.source = None;
}
}
v
});
let sparklines = sh.sparklines.iter().any(|sp| changes(&sp.source)).then(|| {
let mut v = sh.sparklines.clone();
v.iter_mut().for_each(|sp| {
rewrite_text(&mut sp.source, &f);
});
v
});
let pivots = sh.pivots.iter().any(|pt| !table_source(&pt.source) && changes(&pt.source)).then(|| {
let mut v = sh.pivots.clone();
v.iter_mut().filter(|pt| !table_source(&pt.source)).for_each(|pt| {
rewrite_text(&mut pt.source, &f);
});
v
});
// A form control's linked cell.
let controls = sh.controls.iter().any(|c| c.link.as_deref().is_some_and(changes)).then(|| {
let mut v = sh.controls.clone();
v.iter_mut().flat_map(|c| c.link.as_mut()).for_each(|t| {
rewrite_text(t, &f);
});
v
});
if cells.is_empty()
&& cond_formats.is_none()
&& validations.is_none()
&& charts.is_none()
&& sparklines.is_none()
&& pivots.is_none()
&& controls.is_none()
{
continue;
}
let sh = Arc::make_mut(shared);
for (c, formula) in cells {
if let Some(cell) = sh.cells.get_mut(c) {
cell.formula = Some(Arc::new(formula));
}
}
if let Some(v) = cond_formats {
sh.cond_formats = v;
}
if let Some(v) = validations {
sh.validations = v;
}
if let Some(v) = charts {
sh.charts = v;
}
if let Some(v) = sparklines {
sh.sparklines = v;
}
if let Some(v) = pivots {
sh.pivots = v;
}
if let Some(v) = controls {
sh.controls = v;
}
}
}
/// A new workbook with one sheet, "Sheet1".
pub fn new() -> Workbook {
Workbook {
@@ -600,6 +802,36 @@ mod tests {
Ok(())
}
/// A rewrite copies only the sheets it changes: the others stay shared (with undo snapshots).
#[test]
fn rewrite_references_leaves_untouched_sheets_shared() -> Result<(), Box<dyn std::error::Error>> {
let mut wb = Workbook::new();
let mut other = Sheet::new("Other");
other.set_cell(gridcraft_core::CellRef::new(0, 0), crate::Cell::formula(Formula::new("Sheet1!A1+1")));
wb.sheets.push(Arc::new(other));
let mut third = Sheet::new("Third");
third.set_cell(gridcraft_core::CellRef::new(0, 0), crate::Cell::formula(Formula::new("A1+1")));
// A rule that doesn't name the sheet leaves its sheet shared; one that does is rewritten.
third.validations.push(crate::Validation { f1: "=A1>0".into(), ..Default::default() });
wb.sheets.push(Arc::new(third));
let mut fourth = Sheet::new("Fourth");
fourth.validations.push(crate::Validation { f1: "=Sheet1!A1>0".into(), ..Default::default() });
wb.sheets.push(Arc::new(fourth));
let snapshot = wb.clone();
wb.rewrite_references(&|_, e| gridcraft_formula::adjust::rename_sheet(e, "Sheet1", "Data"));
let shared = |i: usize| -> Result<bool, Box<dyn std::error::Error>> {
Ok(Arc::ptr_eq(wb.sheets.get(i).ok_or("sheet")?, snapshot.sheets.get(i).ok_or("sheet")?))
};
assert!(shared(0)?, "nothing on Sheet1 names it");
assert!(!shared(1)?, "Other's formula names Sheet1");
assert!(shared(2)?, "Third's formula and rule are unqualified");
assert!(!shared(3)?, "Fourth's rule names Sheet1");
assert_eq!(wb.sheets.get(3).and_then(|s| s.validations.first()).map(|v| v.f1.as_str()), Some("=Data!A1>0"));
let f = wb.sheets.get(1).and_then(|s| s.cell(gridcraft_core::CellRef::new(0, 0))).and_then(|c| c.formula.clone()).ok_or("formula")?;
assert_eq!(f.text, "Data!A1+1");
Ok(())
}
#[test]
fn sheet_names() {
let wb = Workbook::new();
+32 -1
View File
@@ -1,6 +1,6 @@
# Architecture
> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-11-03 · **Change:** minor (shared CJK fallback baselines; 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)
> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-11-13 · **Change:** minor (one workbook-wide reference rewrite; earlier: shared CJK fallback baselines; 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).
@@ -203,6 +203,36 @@ 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 the places a workbook holds a reference:
cell formulas (keeping their legacy-array range and spill kind), defined names, conditional
formats, data validation, chart series and source blocks, sparklines, PivotTable sources and form
controls' linked cells. It hands the rewrite a `RefHost` (the holding sheet or a name's scope, and
the sheet name unqualified references are on). A formula whose tree the rewrite leaves alone keeps
its stored text. Not visited: table calculated-column and totals formulas, a PivotChart's link to its PivotTable (a sheet rename moves it itself) and a slicer's table. The engine's
reference-moving edits go 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. Internal hyperlinks keep the place they name as typed,
as Excel's do. A sheet nothing changes on stays shared with undo snapshots.
Conditional-format and validation formulas are written for the top-left cell of all the rule's
ranges. When an edit moves that cell (cuts a range short, or removes the range holding it), the
rule's top-left-relative formulas (`CfRule::relative_formulas_mut`, `Validation::formulas_mut`)
are first re-hosted at the cell that takes its place (`rehost_rule`, given the ranges as they were
before the edit), then moved once by the walker, so deleting a rule's first row leaves its formulas reading
the same cells. 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 rule keeps one formula for all its cells, so when an
edit shifts some of a rule's cells and not others (lines inserted or deleted inside its range, Move
Columns across it), a relative reference read at cells on the far side of the shift lands where the
top-left cell's reference puts it, not on the data that cell read before; rules whose cells read
themselves, and absolute references, are unaffected. A cut, and Move Columns, take the rules on their
cells with them (`move_cut_rules`, on the engine's `Rule` trait, `remove_rule_cells` and
`moved_rule_parts`), so their ranges and formulas move together, once; a cut to another sheet qualifies their references with the source sheet. A cut is
pasted as it is: Paste Special refuses to transpose it, tile it over a larger selection or skip its
blanks, as Excel offers none of those for a cut.
## Equations
An equation is a shape (`ShapeKind::Equation`) whose `text` is its LaTeX source; it selects,
@@ -242,6 +272,7 @@ rpm, tarball), FreeBSD, and web (WASM; WebGPU or WebGL2). Release workflows in
| Date | Change | Summary |
|---|---|---|
| 2026-11-13 | 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 |
| 2026-11-02 | minor | Python mode in the formula bar: Python mode on the shared editor, `code_field` and its stop keys; drafts follow their sheet by `model::SheetUid` |
| 2026-11-02 | minor | Python cells as data: `model::PyCode`, the file forms, calc laying out kept results, the limits on open, and what copying, filling and sorting do to `xl()` references; edits that would push code past the limit are refused |
| 2026-11-01 | trivial | Equations: the layout cache answers for a source over the cap by its length alone, without hashing it |