Commit d10f852d3e for handsontable.com

commit d10f852d3efe0630964286152a8714cf7d03bc85
Author: Artur Mędrygał <artur.medrygal@handsontable.com>
Date:   Wed Nov 25 10:02:43 2026 +0100

    DEV-4200: Clear merge meta on the undo of a step that alters rows or columns (#14450)

    * DEV-4190: Clear merge meta from the cells of an undone merge

    * DEV-4190: Clear copyable on the top-left of a merge the undo restores

    * DEV-4190: Clear the inner merge's span on the redo of a merge over it

    * DEV-4190: Share one clipboard read helper across the page objects

    * DEV-4200: Clear merge meta on undo of a step that also alters rows or columns

    * DEV-4200: Describe the restore index translator in AGENTS.md

    * DEV-4200: Match unchanged merges by a footprint key on a replayed undo

    * DEV-4200: Describe the mapped recorded side in the AGENTS.md files

    * DEV-4200: Treat a merge that lost a row or column as changed

    * DEV-4200: Note the partly mapped merge rule in AGENTS.md

    * DEV-4200: Map the anchor column first and share the restored index mapper

    (cherry picked from commit f8c203948869fb39e67f1a02087798823e69805a)

diff --git a/handsontable/src/plugins/base/AGENTS.md b/handsontable/src/plugins/base/AGENTS.md
index f28b677944..adb3961d7c 100644
--- a/handsontable/src/plugins/base/AGENTS.md
+++ b/handsontable/src/plugins/base/AGENTS.md
@@ -608,7 +608,7 @@ State the undo stack cannot see on its own - neither an index map nor cell meta
 `captureState(previous)` / `restoreState(state, context?)`, and for a plugin that reshapes the source
 array itself, `captureSourceStructure(previous)` / `restoreSourceStructure(state)`. Return `previous`
 by reference when nothing changed. `context` (`PluginRestoreContext`: `other`, `direction`,
-`reordered`) names the step being restored, so a plugin can apply only what the step changed and
+`reordered`, `toRestoredIndex`) names the step being restored, so a plugin can apply only what the step changed and
 keep a change made outside any step. A plugin with `captureState()` should also implement
 `getStateColumns(state, other)` - the physical columns its state differs in across a step - or every
 step that changed its state is dropped on a `columns` settings update that changes a column's field.
diff --git a/handsontable/src/plugins/base/base.ts b/handsontable/src/plugins/base/base.ts
index 5a16c68878..7da9ade739 100644
--- a/handsontable/src/plugins/base/base.ts
+++ b/handsontable/src/plugins/base/base.ts
@@ -44,9 +44,16 @@ export interface PluginRestoreContext {
   direction?: 'undo' | 'redo';
   /**
    * `true` when the restore replayed row or column insertions or removals first. The grid's live state
-   * is then numbered like the restored side, not like `other`, so the two cannot be compared.
+   * is then numbered like the restored side, not like `other`, so the two cannot be compared without
+   * `toRestoredIndex`.
    */
   reordered?: boolean;
+  /**
+   * Given with `reordered`: maps a physical index `other` records to the grid the restore leaves behind,
+   * through the rows and columns the step inserted or removed. Answers `null` for a row or column that
+   * does not exist there.
+   */
+  toRestoredIndex?: (physicalIndex: number, axis: 'row' | 'column') => number | null;
 }

 /**
diff --git a/handsontable/src/plugins/mergeCells/AGENTS.md b/handsontable/src/plugins/mergeCells/AGENTS.md
index 8205bf8d32..8ee9e0c09c 100644
--- a/handsontable/src/plugins/mergeCells/AGENTS.md
+++ b/handsontable/src/plugins/mergeCells/AGENTS.md
@@ -325,9 +325,25 @@ hooks). Six rules keep it narrow:
   they are still own, and `copyable`, `rowspan` and `colspan` unless recorded (the `wasInMerge` argument of
   `#clearCoveredFlagsOfTopLeftCell` and `#clearSpanKeysOfCell`). Pinned by `__tests__/undoMergeMeta.unit.js` and
   `tests/e2e/merge-cells-undo-copy.spec.ts`. The cleanup does nothing
-  without a recorded other side (no `context.other`), for a merge captured with no `physicalColumns`, or when
-  the replay inserted or removed rows or columns (`context.reordered`): the recorded physical indexes are
-  numbered like the grid before that replay. A row move's redo was already clean, because dropping the live merge cleans it by the
+  without a recorded other side (no `context.other`) or for a merge captured with no `physicalColumns`.
+  **A step that also inserted or removed rows or columns (`context.reordered`) cannot use the recorded sides**:
+  UndoRedo replays that `alter()` first, so the recorded physical indexes are numbered like the grid before the
+  replay. UndoRedo therefore hands the restore `context.toRestoredIndex`, which maps a physical index of the
+  other side through the rows and columns the step inserted or removed (`toFinalIndex()` in
+  `../undoRedo/restoredCells.ts`). `#clearMergeKeysOfCellsReleasedByReplay()` maps every recorded merge's
+  anchor rows and `physicalColumns` with it (`mapRecordedMerge()`), leaves out the merges whose mapped cells
+  equal a restored merge's (`getFootprintKey()`, matched through a `Set` so the match stays linear in the
+  merge count: the step left them alone, and checking them would cost the area of every merge on every
+  structural undo). A recorded merge that lost a row or a column to the mapping never matches: it covered a
+  cell the restored grid lacks, and once that cell is dropped it can look like the merge the undo puts back
+  (an inserted row inside a merge that the step grew), which left that merge's top-left uncleaned. It runs the same per-cell rule
+  (`#clearMergeKeysOfReleasedCells()`) as the path above. **Never read the live merges here**: the replay runs
+  in the physical order and the column order is restored before `restoreState()`, so a live merge's visual
+  columns name other physical columns once a column was moved, and a column `alter()` in the replay
+  re-captures the anchors in the physical order too. A cleanup built from them missed the merge's cells and
+  cleaned cells no merge covered. Pinned by the `of a step that also inserts or removes rows or columns` block
+  of `__tests__/undoMergeMeta.unit.js` (the moved-column cases among them) and the insert-and-merge case of
+  `tests/e2e/merge-cells-undo-copy.spec.ts`. A row move's redo was already clean, because dropping the live merge cleans it by the
   anchor's physical rows. Pinned by the `after the undo and the redo` cases of
   `__tests__/reanchoredTopLeftMeta.unit.js` and `tests/e2e/merge-cells-column-move-redo.spec.ts`.
 - **The cell a merge is no longer drawn from loses its span keys.** `afterGetCellMeta` stores `spanned`,
diff --git a/handsontable/src/plugins/mergeCells/__tests__/undoMergeMeta.unit.js b/handsontable/src/plugins/mergeCells/__tests__/undoMergeMeta.unit.js
index b41769af7f..38f866c5f2 100644
--- a/handsontable/src/plugins/mergeCells/__tests__/undoMergeMeta.unit.js
+++ b/handsontable/src/plugins/mergeCells/__tests__/undoMergeMeta.unit.js
@@ -224,4 +224,359 @@ describe('MergeCells cell meta after the undo of a merge', () => {
     expect(hot.getCellMeta(2, 1).copyable).toBe(true);
     expect(hot.getCopyableText(1, 1, 2, 2)).toBe('B2\tC2\nB3\t');
   });
+
+  /**
+   * A step that also inserts or removes rows or columns is replayed with `alter()` before `restoreState()` runs,
+   * so the merges the step recorded are numbered like the grid before the replay and cannot name the cells.
+   */
+  describe('of a step that also inserts or removes rows or columns', () => {
+    const ALL_CELLS = [0, 0, 8, 8];
+
+    /**
+     * Lists the merges as `[row, col, rowspan, colspan]`.
+     *
+     * @returns {number[][]}
+     */
+    function merges() {
+      return hot.getPlugin('mergeCells').mergedCellsCollection.mergedCells
+        .map(({ row, col, rowspan, colspan }) => [row, col, rowspan, colspan]);
+    }
+
+    /**
+     * Returns the text a copy of the whole grid holds when every cell is copyable.
+     *
+     * @returns {string}
+     */
+    function plainText() {
+      return hot.getData().map(row => row.join('\t')).join('\n');
+    }
+
+    /**
+     * A `cells` function that gives the cell holding `F6` an unrecorded `copyable: false`, wherever the cell is.
+     *
+     * @param {number} row The visual row.
+     * @param {number} column The visual column.
+     * @returns {object}
+     */
+    function notCopyableF6(row, column) {
+      return hot?.getSourceDataAtCell(hot.toPhysicalRow(row), column) === 'F6' ? { copyable: false } : {};
+    }
+
+    it('takes the span and the covered flags off the cells after an insert and a merge in one batch', () => {
+      createGrid({ data: Handsontable.helper.createSpreadsheetData(8, 8) });
+
+      hot.batch(() => {
+        hot.alter('insert_row_above', 0);
+        hot.getPlugin('mergeCells').merge(1, 1, 2, 2);
+      });
+      readMeta([0, 0, 8, 7]);
+      hot.getPlugin('undoRedo').undo();
+
+      expect(merges()).toEqual([]);
+      expect(storedMergeKeys(ALL_CELLS)).toEqual([]);
+      expect(hot.getCopyableText(0, 0, 2, 3)).toBe('A1\tB1\tC1\tD1\nA2\tB2\tC2\tD2\nA3\tB3\tC3\tD3');
+    });
+
+    it.each([
+      ['a row removal before the merge', () => {
+        hot.alter('remove_row', 0);
+        hot.getPlugin('mergeCells').merge(1, 1, 2, 2);
+      }],
+      ['a column insertion before the merge', () => {
+        hot.alter('insert_col_start', 0);
+        hot.getPlugin('mergeCells').merge(1, 1, 2, 2);
+      }],
+      ['a row insertion after the merge', () => {
+        hot.getPlugin('mergeCells').merge(1, 1, 2, 2);
+        hot.alter('insert_row_above', 0);
+      }],
+      ['a removal of a row inside the merge', () => {
+        hot.getPlugin('mergeCells').merge(1, 1, 3, 2);
+        hot.alter('remove_row', 2);
+      }],
+    ])('takes the span and the covered flags off the cells after %s in one batch', (_, step) => {
+      createGrid({ data: Handsontable.helper.createSpreadsheetData(8, 8) });
+
+      hot.batch(step);
+      readMeta([0, 0, hot.countRows() - 1, hot.countCols() - 1]);
+      hot.getPlugin('undoRedo').undo();
+
+      expect(merges()).toEqual([]);
+      expect(storedMergeKeys(ALL_CELLS)).toEqual([]);
+      expect(hot.getCopyableText(0, 0, 7, 7)).toBe(plainText());
+    });
+
+    it.each([
+      ['a row insertion', () => hot.alter('insert_row_above', 0)],
+      ['a row removal', () => hot.alter('remove_row', 0)],
+      ['a column insertion', () => hot.alter('insert_col_start', 0)],
+    ])('takes the keys off the cells after %s and a merge over moved columns in one batch', (_, alter) => {
+      createGrid({ data: Handsontable.helper.createSpreadsheetData(8, 8), manualColumnMove: true });
+
+      // The merge spans visual columns whose physical columns are not the same numbers, or not next to each other.
+      hot.getPlugin('manualColumnMove').moveColumn(5, 0);
+      hot.batch(() => {
+        alter();
+        hot.getPlugin('mergeCells').merge(1, 1, 2, 2);
+      });
+      readMeta([0, 0, hot.countRows() - 1, hot.countCols() - 1]);
+      hot.getPlugin('undoRedo').undo();
+
+      expect(merges()).toEqual([]);
+      expect(storedMergeKeys(ALL_CELLS)).toEqual([]);
+      expect(hot.getCopyableText(0, 0, 7, 7)).toBe(plainText());
+
+      hot.getPlugin('undoRedo').redo();
+      readMeta([0, 0, hot.countRows() - 1, hot.countCols() - 1]);
+
+      expect(merges()).toEqual([[1, 1, 2, 2]]);
+      expect(hot.getCellMeta(1, 1).rowspan).toBe(2);
+      expect(hot.getCellMeta(2, 2).copyable).toBe(false);
+
+      hot.getPlugin('undoRedo').undo();
+
+      expect(storedMergeKeys(ALL_CELLS)).toEqual([]);
+      expect(hot.getCopyableText(0, 0, 7, 7)).toBe(plainText());
+    });
+
+    it.each([
+      ['a row', () => hot.alter('insert_row_above', 2)],
+      ['a column', () => hot.alter('insert_col_start', 2)],
+    ])('takes the keys off the cells after a merge and an insertion of %s inside it in one batch', (_, alter) => {
+      createGrid({ data: Handsontable.helper.createSpreadsheetData(8, 8) });
+
+      // The undo removes the inserted row or column, so part of the merge it recorded maps to nothing.
+      hot.batch(() => {
+        hot.getPlugin('mergeCells').merge(1, 1, 3, 3);
+        alter();
+      });
+      readMeta([0, 0, hot.countRows() - 1, hot.countCols() - 1]);
+      hot.getPlugin('undoRedo').undo();
+
+      expect(merges()).toEqual([]);
+      expect(storedMergeKeys(ALL_CELLS)).toEqual([]);
+      expect(hot.getCopyableText(0, 0, 7, 7)).toBe(plainText());
+    });
+
+    it('keeps the cells clean through a redo and a second undo', () => {
+      createGrid({ data: Handsontable.helper.createSpreadsheetData(8, 8) });
+
+      hot.batch(() => {
+        hot.alter('insert_row_above', 0);
+        hot.getPlugin('mergeCells').merge(1, 1, 2, 2);
+      });
+      readMeta([0, 0, 8, 7]);
+      hot.getPlugin('undoRedo').undo();
+      hot.getPlugin('undoRedo').redo();
+      readMeta([0, 0, 8, 7]);
+
+      expect(merges()).toEqual([[1, 1, 2, 2]]);
+      expect(hot.getCellMeta(1, 1).rowspan).toBe(2);
+      expect(hot.getCellMeta(2, 2).copyable).toBe(false);
+
+      hot.getPlugin('undoRedo').undo();
+
+      expect(storedMergeKeys(ALL_CELLS)).toEqual([]);
+      expect(hot.getCopyableText(0, 0, 7, 7)).toBe(plainText());
+    });
+
+    it('cleans the cell a merge the undo puts back is drawn from, when the step merged over it', () => {
+      createGrid({ data: Handsontable.helper.createSpreadsheetData(8, 8) });
+
+      hot.getPlugin('mergeCells').merge(2, 1, 3, 2);
+      readMeta([0, 0, 7, 7]);
+      hot.batch(() => {
+        hot.alter('insert_row_above', 0);
+        hot.selectCell(1, 0, 4, 3);
+        hot.getPlugin('mergeCells').mergeSelection();
+      });
+      readMeta([0, 0, 8, 7]);
+      // The render of the undo would run `afterGetCellMeta`, which writes the keys of the restored merge again.
+      hot.suspendRender();
+      hot.getPlugin('undoRedo').undo();
+
+      expect(merges()).toEqual([[2, 1, 2, 2]]);
+      // The outer merge covered C3, and the inner merge it puts back is drawn from it.
+      expect(storedMergeKeys([2, 1, 2, 1])).toEqual(['2,1:spanned']);
+      expect(storedMergeKeys([0, 0, 1, 3])).toEqual([]);
+      expect(storedMergeKeys([2, 0, 3, 0])).toEqual([]);
+      expect(storedMergeKeys([2, 3, 3, 3])).toEqual([]);
+
+      hot.resumeRender();
+      readMeta([0, 0, 7, 7]);
+
+      expect(hot.getCellMeta(2, 1).rowspan).toBe(2);
+      expect(hot.getCellMeta(2, 1).copyable).toBe(true);
+      expect(hot.getCellMeta(3, 2).copyable).toBe(false);
+      expect(hot.getCopyableText(0, 0, 1, 3)).toBe('A1\tB1\tC1\tD1\nA2\tB2\tC2\tD2');
+    });
+
+    it('takes the keys off the cells when the undo removes the first column of the merge', () => {
+      createGrid({ data: Handsontable.helper.createSpreadsheetData(8, 8) });
+
+      // The merge starts on the inserted column, so its anchor column maps to nothing after the undo.
+      hot.batch(() => {
+        hot.alter('insert_col_start', 1);
+        hot.getPlugin('mergeCells').merge(1, 1, 2, 2);
+      });
+      readMeta([0, 0, 7, 8]);
+      hot.getPlugin('undoRedo').undo();
+
+      expect(merges()).toEqual([]);
+      expect(storedMergeKeys(ALL_CELLS)).toEqual([]);
+      expect(hot.getCopyableText(0, 0, 7, 7)).toBe(plainText());
+    });
+
+    it('cleans a recorded merge that lost a row while the restored side holds a merge with no anchor', () => {
+      createGrid({ data: Handsontable.helper.createSpreadsheetData(8, 8) });
+
+      [[1, 1], [1, 2], [2, 1], [2, 2]].forEach(([row, column]) => {
+        // Unrecorded, as `afterGetCellMeta` writes it.
+        hot.getCellMeta(row, column).copyable = false;
+      });
+      hot.getPlugin('mergeCells').restoreState([{ row: 5, col: 5, rowspan: 2, colspan: 2, anchor: null }], {
+        other: [{
+          row: 1,
+          col: 1,
+          rowspan: 3,
+          colspan: 2,
+          anchor: { physicalRows: [1, 2, 3], physicalColumn: 1 },
+          physicalColumns: [1, 2],
+        }],
+        direction: 'undo',
+        reordered: true,
+        toRestoredIndex: (index, axis) => (axis === 'row' && index === 3 ? null : index),
+      });
+
+      expect(storedMergeKeys([1, 1, 2, 2])).toEqual([]);
+    });
+
+    it('cleans nothing for a recorded merge with no anchor or no recorded columns', () => {
+      createGrid({ data: Handsontable.helper.createSpreadsheetData(8, 8) });
+
+      const cells = [[1, 1], [1, 2], [2, 1], [2, 2], [4, 4], [4, 5], [5, 4], [5, 5]];
+
+      cells.forEach(([row, column]) => {
+        hot.getCellMeta(row, column).copyable = false;
+      });
+      hot.getPlugin('mergeCells').restoreState([], {
+        other: [
+          { row: 1, col: 1, rowspan: 2, colspan: 2, anchor: null, physicalColumns: [1, 2] },
+          { row: 4, col: 4, rowspan: 2, colspan: 2, anchor: { physicalRows: [4, 5], physicalColumn: 4 } },
+        ],
+        direction: 'undo',
+        reordered: true,
+        toRestoredIndex: index => index,
+      });
+
+      // Neither merge names its cells, so the cleanup cannot tell which ones it covered.
+      expect(storedMergeKeys([1, 1, 5, 5])).toEqual(cells.map(([row, column]) => `${row},${column}:copyable`));
+    });
+
+    it('cleans the cell a restored merge is drawn from when the step grew it by an inserted row', () => {
+      createGrid({ data: Handsontable.helper.createSpreadsheetData(8, 8) });
+
+      hot.getPlugin('mergeCells').merge(1, 1, 2, 2);
+      readMeta([0, 0, 7, 7]);
+      // The undo removes the inserted row, so the larger merge maps onto the same cells as the one it puts back.
+      hot.batch(() => {
+        hot.alter('insert_row_above', 1);
+        hot.getPlugin('mergeCells').unmerge(2, 1, 3, 2);
+        hot.getPlugin('mergeCells').merge(1, 1, 3, 2);
+      });
+      readMeta([0, 0, 8, 7]);
+      hot.getPlugin('undoRedo').undo();
+      readMeta([0, 0, 7, 7]);
+
+      expect(merges()).toEqual([[1, 1, 2, 2]]);
+      expect(hot.getCellMeta(1, 1).copyable).toBe(true);
+      expect(hot.getCopyableText(1, 1, 2, 2)).toBe('B2\t\n\t');
+    });
+
+    it('takes the span and the covered flags off the cells on the redo of an insert and an unmerge', () => {
+      createGrid({ data: Handsontable.helper.createSpreadsheetData(8, 8) });
+
+      hot.getPlugin('mergeCells').merge(1, 1, 2, 2);
+      readMeta([0, 0, 7, 7]);
+      hot.batch(() => {
+        hot.alter('insert_row_above', 0);
+        hot.getPlugin('mergeCells').unmerge(2, 1, 3, 2);
+      });
+      hot.getPlugin('undoRedo').undo();
+      readMeta([0, 0, 7, 7]);
+
+      expect(merges()).toEqual([[1, 1, 2, 2]]);
+
+      hot.getPlugin('undoRedo').redo();
+
+      expect(merges()).toEqual([]);
+      expect(storedMergeKeys(ALL_CELLS)).toEqual([]);
+    });
+
+    it('leaves the keys of a merge the step did not change', () => {
+      createGrid({
+        data: Handsontable.helper.createSpreadsheetData(8, 8),
+        // An unrecorded key on the top-left of the unchanged merge, which `afterGetCellMeta` never writes there.
+        cells: notCopyableF6,
+      });
+
+      hot.getPlugin('mergeCells').merge(5, 5, 6, 6);
+      readMeta([0, 0, 7, 7]);
+      hot.batch(() => {
+        hot.alter('insert_row_above', 0);
+        hot.getPlugin('mergeCells').merge(1, 1, 2, 2);
+      });
+      readMeta([0, 0, 8, 7]);
+      hot.suspendRender();
+      hot.getPlugin('undoRedo').undo();
+
+      expect(merges()).toEqual([[5, 5, 2, 2]]);
+      expect(storedMergeKeys([0, 0, 4, 7])).toEqual([]);
+      expect(storedMergeKeys([5, 5, 6, 6])).toEqual([
+        '5,5:copyable', '5,5:spanned', '5,5:rowspan', '5,5:colspan',
+        '5,6:hidden', '5,6:copyable', '6,5:hidden', '6,5:copyable', '6,6:hidden', '6,6:copyable',
+      ]);
+
+      hot.resumeRender();
+    });
+
+    it('keeps a `copyable`, a `rowspan` and a `colspan` the user set before the step', () => {
+      createGrid({ data: Handsontable.helper.createSpreadsheetData(8, 8) });
+
+      hot.setCellMeta(1, 1, 'rowspan', 3);
+      hot.setCellMeta(1, 1, 'colspan', 4);
+      hot.setCellMeta(2, 2, 'copyable', false);
+      hot.batch(() => {
+        hot.alter('insert_row_above', 0);
+        hot.getPlugin('mergeCells').merge(2, 1, 3, 2);
+      });
+      readMeta([0, 0, 8, 7]);
+      hot.getPlugin('undoRedo').undo();
+
+      expect(storedMergeKeys([1, 1, 2, 2])).toEqual(['1,1:rowspan', '1,1:colspan', '2,2:copyable']);
+      expect(hot.getCellMeta(2, 2).copyable).toBe(false);
+      expect(hot.getCellMeta(2, 1).copyable).toBe(true);
+    });
+
+    it('keeps a `copyable` a `cells` function gives a cell the merge did not cover', () => {
+      createGrid({
+        data: Handsontable.helper.createSpreadsheetData(8, 8),
+        cells: notCopyableF6,
+      });
+
+      hot.batch(() => {
+        hot.alter('insert_row_above', 0);
+        hot.getPlugin('mergeCells').merge(1, 1, 2, 2);
+      });
+      readMeta([0, 0, 8, 7]);
+      // The render of the undo would run the `cells` function again and put the key back.
+      hot.suspendRender();
+      hot.getPlugin('undoRedo').undo();
+
+      expect(storedMergeKeys([5, 5, 5, 5])).toEqual(['5,5:copyable']);
+      expect(storedMergeKeys([0, 0, 4, 4])).toEqual([]);
+
+      hot.resumeRender();
+    });
+  });
 });
diff --git a/handsontable/src/plugins/mergeCells/mergeCells.ts b/handsontable/src/plugins/mergeCells/mergeCells.ts
index 359a8965cb..26bee1cf15 100644
--- a/handsontable/src/plugins/mergeCells/mergeCells.ts
+++ b/handsontable/src/plugins/mergeCells/mergeCells.ts
@@ -158,6 +158,55 @@ function isMergeState(value: unknown): value is readonly MergeStateEntry[] {
   return Array.isArray(value);
 }

+/**
+ * Maps the physical cells a captured merge names to another numbering of the rows and columns. A row or
+ * column that does not exist there is dropped. The anchor keeps its own column, mapped, or takes the first
+ * recorded column that is left when its own does not exist there. A merge with no row or no column left has
+ * no anchor.
+ *
+ * @param {object} entry The captured merge.
+ * @param {Function} toIndex Maps a physical index, or answers `null` for one that does not exist there.
+ * @returns {object} The merge with its anchor and `physicalColumns` mapped.
+ */
+function mapRecordedMerge(
+  entry: MergeStateEntry,
+  toIndex: (physicalIndex: number, axis: 'row' | 'column') => number | null,
+): MergeStateEntry {
+  const physicalColumns = entry.physicalColumns?.map(column => (column === null ? null : toIndex(column, 'column')));
+
+  if (entry.anchor === null) {
+    return { ...entry, physicalColumns };
+  }
+
+  const physicalRows = entry.anchor.physicalRows
+    .map(row => toIndex(row, 'row'))
+    .filter((row): row is number => row !== null);
+  const physicalColumn = toIndex(entry.anchor.physicalColumn, 'column') ??
+    physicalColumns?.find(column => column !== null) ?? null;
+
+  return {
+    ...entry,
+    anchor: physicalRows.length === 0 || physicalColumn === null ? null : { physicalRows, physicalColumn },
+    physicalColumns,
+  };
+}
+
+/**
+ * Returns a key for the physical cells a captured merge names (its anchor rows, its anchor column and its
+ * columns), so two merges with the same key name the same cells. A merge with no anchor or no recorded columns
+ * has none.
+ *
+ * @param {object} entry The captured merge.
+ * @returns {string | null}
+ */
+function getFootprintKey(entry: MergeStateEntry): string | null {
+  if (entry.anchor === null || entry.physicalColumns === undefined) {
+    return null;
+  }
+
+  return `${entry.anchor.physicalRows.join(',')}|${entry.anchor.physicalColumn}|${entry.physicalColumns.join(',')}`;
+}
+
 /**
  * What a row move does to one merge, decided before the move's fragments exist.
  *
@@ -1973,10 +2022,11 @@ export class MergeCells extends BasePlugin {
     }

     const other = context?.other;
+    const isReplayed = context?.reordered === true;
     // The restore replaces merges, and a step can leave the cell a merge was drawn from in no merge.
     const drawnFromBefore = this.#snapshotDrawnFromCells();

-    if (!isMergeState(other) || context?.reordered === true || !this.#restoreChangedMerges(state, other)) {
+    if (!isMergeState(other) || isReplayed || !this.#restoreChangedMerges(state, other)) {
       this.mergedCellsCollection.clear();
       this.#mergeAnchors = new WeakMap();
       this.#purgedMerges = new WeakSet();
@@ -1986,9 +2036,12 @@ export class MergeCells extends BasePlugin {
     this.#reanchorMergesToVisibleRows();
     this.#clearSpanKeysOfCellsNoLongerDrawnFrom(drawnFromBefore);

-    // A replay that inserted or removed columns renumbered the physical indexes the recorded merges name.
-    if (isMergeState(other) && context?.reordered !== true) {
+    if (isMergeState(other) && !isReplayed) {
       this.#clearCoveredFlagsOfCellsReleasedByStep(state, other);
+
+    } else if (isMergeState(other) && context?.toRestoredIndex) {
+      // A replay that inserted or removed rows or columns renumbered the physical indexes the other side records.
+      this.#clearMergeKeysOfCellsReleasedByReplay(state, other, context.toRestoredIndex);
     }

     this.hot.markAllCellsChanged();
@@ -2048,11 +2101,85 @@ export class MergeCells extends BasePlugin {
     }

     const restored = state.filter(entry => !isMergeListed(other, entry));
-    const covered = this.#collectRecordedCoveredCells(restored);
-    const restoredTopLefts = this.#collectRecordedTopLeftCells(restored);
-    const leftTopLefts = this.#collectRecordedTopLeftCells(left);

-    this.#collectRecordedCoveredCells(left).forEach((key) => {
+    this.#clearMergeKeysOfReleasedCells(
+      this.#collectRecordedCoveredCells(left),
+      this.#collectRecordedTopLeftCells(left),
+      this.#collectRecordedCoveredCells(restored),
+      this.#collectRecordedTopLeftCells(restored),
+    );
+  }
+
+  /**
+   * Does what {@link MergeCells#clearCoveredFlagsOfCellsReleasedByStep} does, after a replay that inserted or
+   * removed rows or columns. The physical indexes the other side records are numbered like the grid before that
+   * replay, so each merge's anchor rows and recorded columns are first mapped to the restored grid through the
+   * rows and columns the step inserted or removed. Neither the live merges nor their visual columns can stand in:
+   * the replay runs in the physical order and the column order is restored before this runs. A merge whose
+   * mapped cells equal those of a restored merge is one the step left alone, and both are left out.
+   *
+   * @param {Array} state The merges on the restored side of the step.
+   * @param {Array} other The merges on the other side of the step.
+   * @param {Function} toRestoredIndex Maps a physical index of `other` to the restored grid.
+   */
+  #clearMergeKeysOfCellsReleasedByReplay(
+    state: readonly MergeStateEntry[],
+    other: readonly MergeStateEntry[],
+    toRestoredIndex: NonNullable<PluginRestoreContext['toRestoredIndex']>,
+  ) {
+    const mapped = other.map((entry) => {
+      const mappedEntry = mapRecordedMerge(entry, toRestoredIndex);
+      // A merge that lost a row or a column to the mapping covered a cell the restored grid lacks, so it is
+      // not the same merge as one of the restored side with the cells that are left.
+      const isWhole = mappedEntry.anchor?.physicalRows.length === entry.anchor?.physicalRows.length &&
+        !mappedEntry.physicalColumns?.includes(null);
+
+      return { entry: mappedEntry, key: isWhole ? getFootprintKey(mappedEntry) : null };
+    });
+    const restoredKeys = new Set(state.map(getFootprintKey));
+    const left = mapped
+      .filter(({ key }) => key === null || !restoredKeys.has(key))
+      .map(({ entry }) => entry);
+
+    if (left.length === 0) {
+      return;
+    }
+
+    const mappedKeys = new Set(mapped.map(({ key }) => key));
+    const restored = state.filter((entry) => {
+      const key = getFootprintKey(entry);
+
+      return key === null || !mappedKeys.has(key);
+    });
+
+    this.#clearMergeKeysOfReleasedCells(
+      this.#collectRecordedCoveredCells(left),
+      this.#collectRecordedTopLeftCells(left),
+      this.#collectRecordedCoveredCells(restored),
+      this.#collectRecordedTopLeftCells(restored),
+    );
+  }
+
+  /**
+   * Removes the merge keys from cells a merge covered on the other side of an undo step. A cell the restored
+   * side covers keeps what its merge put on it, except the cell a restored merge is drawn from: it loses `hidden`
+   * and `copyable` and keeps its span keys, because `afterGetCellMeta` never writes `copyable` back on a top-left.
+   * A covered cell a merge of the other side was drawn from loses its span keys and keeps its covered flags,
+   * because the hook never takes a span off a covered cell. Neither removal waits for the `hidden` or `spanned`
+   * mark (see {@link MergeCells#clearCoveredFlagsOfCellsReleasedByStep}).
+   *
+   * @param {Set<number>} released The cells a merge covered on the other side of the step.
+   * @param {Set<number>} leftTopLefts The cells the merges of the other side were drawn from.
+   * @param {Set<number>} covered The cells the restored merges cover.
+   * @param {Set<number>} restoredTopLefts The cells the restored merges are drawn from.
+   */
+  #clearMergeKeysOfReleasedCells(
+    released: Set<number>,
+    leftTopLefts: Set<number>,
+    covered: Set<number>,
+    restoredTopLefts: Set<number>,
+  ) {
+    released.forEach((key) => {
       const isRestoredTopLeft = restoredTopLefts.has(key);
       const isCovered = covered.has(key);
       // A restored merge drawn from the cell keeps its span keys; one that covers it keeps its covered flags.
diff --git a/handsontable/src/plugins/undoRedo/AGENTS.md b/handsontable/src/plugins/undoRedo/AGENTS.md
index b1a6e8ff30..56b4d67c34 100644
--- a/handsontable/src/plugins/undoRedo/AGENTS.md
+++ b/handsontable/src/plugins/undoRedo/AGENTS.md
@@ -207,7 +207,11 @@ is part of the undo, and a recorded step there would empty the redo stack the un
   `restoreState()` runs; a key a hook wrote straight onto the stored meta is in no journal and still there.
   MergeCells gated its undo cleanup on its own `hidden`/`spanned` marks, which the journal had already removed,
   and left `rowspan`, `colspan` and `copyable: false` on the cells of an undone merge. Key such a cleanup on the
-  recorded state (`context.other`) instead.
+  recorded state (`context.other`) instead. When `context.reordered` is set, the replay inserted or removed rows
+  or columns first, so the physical indexes `context.other` records name the grid before the replay: map them
+  with `context.toRestoredIndex` (`toFinalIndex()` over the step's journal). The plugin's live state is no
+  substitute: the replay ran in the physical order and the index maps are already restored, so a live visual
+  column names another physical column once a column was moved.
 - **Derived index maps are never captured** (`autoRowSize`, `autoColumnSize`, `stretchColumns`, the
   NestedHeaders widths, `Pagination`, `AsyncValues`, `*.columnMeta` - `DERIVED_INDEX_MAP_NAMES`). They are rebuilt
   from the rest. `AsyncValues` is there because it holds in-flight requests, which an undo must not bring back. Pagination is there because it recomputes its page map on every index cache update:
@@ -370,14 +374,16 @@ Optional methods, found by `typeof plugin.captureState === 'function'`:
   NestedRows (collapsed parents), CustomBorders (a model version - the borders live in the `borders`
   cell meta, and `restoreState()` rebuilds the model from it), Pagination (the page and the page
   size), Formulas (see `../formulas/AGENTS.md`).
-- `restoreState(state, context?)` gets a `PluginRestoreContext` - `{ other, direction, reordered }`:
-  the plugin's state on the other side of the step, `'undo'` or `'redo'`, and whether the replay
-  reset the order. A plugin uses it to apply only what the step changed, so a change made outside
+- `restoreState(state, context?)` gets a `PluginRestoreContext` - `{ other, direction, reordered,
+  toRestoredIndex }`: the plugin's state on the other side of the step, `'undo'` or `'redo'`, whether
+  the replay reset the order, and, with `reordered`, a function that maps a physical index of `other`
+  to the restored grid. A plugin uses it to apply only what the step changed, so a change made outside
   any step survives: MergeCells adds and removes only the merges that differ between `other` and
   `state` (and falls back to a full rebuild when `reordered` or when a merge to remove is not where
-  it was, or when a merge to put back overlaps a live merge the step did not make) and, unless
-  `reordered`, clears the covered-cell flags of the cells `other` covered and `state` does not, by
-  the recorded physical columns (a redo of a column move), Formulas reads
+  it was, or when a merge to put back overlaps a live merge the step did not make) and clears the
+  merge keys of the cells `other` covered and `state` does not: by the recorded physical columns (a
+  redo of a column move), or, when `reordered`, by `other` mapped to the restored grid through
+  `context.toRestoredIndex`. Formulas reads
   the peer rewrites from `other` on undo. No context is passed when the restore puts back a state no
   step changed.
 - `getStateColumns(state, other)` - the physical columns whose state differs between the two sides
diff --git a/handsontable/src/plugins/undoRedo/restore.ts b/handsontable/src/plugins/undoRedo/restore.ts
index bae220e168..612e9188db 100644
--- a/handsontable/src/plugins/undoRedo/restore.ts
+++ b/handsontable/src/plugins/undoRedo/restore.ts
@@ -199,18 +199,36 @@ function readKeptFlags(
 }

 /**
- * Puts back the flags `readKeptFlags()` read, moved through the step's row and column changes to the
- * grid the restore leaves behind. A row the step inserted is never flagged by them.
+ * Returns a function that maps a physical index of the other side of a step to the grid the restore leaves
+ * behind, through the step's row and column changes. It answers `null` for a row or column that does not exist
+ * there.
  *
- * @param {HotInstance} hot The Handsontable instance.
- * @param {KeptFlags[]} kept The flags.
  * @param {JournalOp[]} journal The step journal.
  * @param {RestoreDirection} direction The replay direction.
+ * @returns {Function}
  */
-function applyKeptFlags(hot: HotInstance, kept: KeptFlags[], journal: JournalOp[], direction: RestoreDirection) {
+function createRestoredIndexMapper(
+  journal: JournalOp[], direction: RestoreDirection,
+): (physicalIndex: number, axis: 'row' | 'column') => number | null {
   // An undo leaves the grid as it was before the step, so every entry is reversed; a redo applies them all.
   const fromEntry = direction === 'undo' ? journal.length : -1;

+  return (physicalIndex, axis) => toFinalIndex(journal, fromEntry, physicalIndex, axis, direction);
+}
+
+/**
+ * Puts back the flags `readKeptFlags()` read, moved through the step's row and column changes to the
+ * grid the restore leaves behind. A row the step inserted is never flagged by them.
+ *
+ * @param {HotInstance} hot The Handsontable instance.
+ * @param {KeptFlags[]} kept The flags.
+ * @param {Function} toRestoredIndex Maps a physical index to the restored grid (`createRestoredIndexMapper()`).
+ */
+function applyKeptFlags(
+  hot: HotInstance,
+  kept: KeptFlags[],
+  toRestoredIndex: (physicalIndex: number, axis: 'row' | 'column') => number | null,
+) {
   kept.forEach(({ axis, key, name, physicalIndexes, restoredIndexes }) => {
     const mapper = axis === 'row' ? hot.rowIndexMapper : hot.columnIndexMapper;
     const map = (key === 'trimming' ? mapper.trimmingMapsCollection : mapper.hidingMapsCollection).get(name);
@@ -223,7 +241,7 @@ function applyKeptFlags(hot: HotInstance, kept: KeptFlags[], journal: JournalOp[
     const values = new Array<boolean>(length).fill(false);

     physicalIndexes.forEach((physicalIndex) => {
-      const finalIndex = toFinalIndex(journal, fromEntry, physicalIndex, axis, direction);
+      const finalIndex = toRestoredIndex(physicalIndex, axis);

       if (finalIndex !== null && finalIndex < length) {
         values[finalIndex] = true;
@@ -860,9 +878,17 @@ export function restoreStep(

     announceRowChanges(hot, rowChanges, source);

+    const toRestoredIndex = createRestoredIndexMapper(record.journal, direction);
+
     // Only what the step changed is written back, so a change made outside any step since survives.
-    tracker.restore(target, { changedFrom: other, base: current, forceOrder: reordersForReplay, direction });
-    applyKeptFlags(hot, keptFlags, record.journal, direction);
+    tracker.restore(target, {
+      changedFrom: other,
+      base: current,
+      forceOrder: reordersForReplay,
+      direction,
+      toRestoredIndex: reordersForReplay ? toRestoredIndex : undefined,
+    });
+    applyKeptFlags(hot, keptFlags, toRestoredIndex);

     // A full render when the batch ends. A step that changed only cell meta asks for none itself, and
     // the fast draw the batch ends with would keep every cell as it was painted.
diff --git a/handsontable/src/plugins/undoRedo/snapshot/gridState.ts b/handsontable/src/plugins/undoRedo/snapshot/gridState.ts
index 71e6588d49..651a0febb4 100644
--- a/handsontable/src/plugins/undoRedo/snapshot/gridState.ts
+++ b/handsontable/src/plugins/undoRedo/snapshot/gridState.ts
@@ -1,5 +1,5 @@
 import type { HotInstance } from '../../../core/types';
-import type { BasePlugin } from '../../base';
+import type { BasePlugin, PluginRestoreContext } from '../../base';
 import { getPluginsNames } from '../../registry';
 import {
   IndexMapperStateTracker,
@@ -224,11 +224,14 @@ export class GridStateTracker {
    * @param {boolean} [options.forceOrder=false] Write the row and column order and the trimming maps back
    *   even when the step did not change them – a replay reset them to the physical order.
    * @param {string} [options.direction] `'undo'` or `'redo'`, handed to the plugins with `changedFrom`.
+   * @param {Function} [options.toRestoredIndex] Maps a physical index of `changedFrom` to the restored grid,
+   *   handed to the plugins with `changedFrom` when `forceOrder` is set.
    */
   restore(
     snapshot: GridStateSnapshot,
-    { changedFrom, base, forceOrder = false, direction }: {
+    { changedFrom, base, forceOrder = false, direction, toRestoredIndex }: {
       changedFrom?: GridStateSnapshot, base?: GridStateSnapshot, forceOrder?: boolean, direction?: 'undo' | 'redo',
+      toRestoredIndex?: PluginRestoreContext['toRestoredIndex'],
     } = {},
   ) {
     // Each axis takes the length the data implies, the one `updateData()` fits it to. With no source
@@ -255,6 +258,7 @@ export class GridStateTracker {
           other: changedFrom.plugins.get(name),
           direction,
           reordered: forceOrder,
+          toRestoredIndex,
         });

       } else if (forceOrder && base?.plugins.has(name)) {
diff --git a/tests/e2e/merge-cells-undo-copy.spec.ts b/tests/e2e/merge-cells-undo-copy.spec.ts
index 787b69b82e..2e1c23b459 100644
--- a/tests/e2e/merge-cells-undo-copy.spec.ts
+++ b/tests/e2e/merge-cells-undo-copy.spec.ts
@@ -58,4 +58,21 @@ test.describe('copy after the undo of a merge', () => {

     await expectPlainCellsCopied();
   });
+
+  test('copies every value after Ctrl+Z of a step that inserts a row and merges', async ({ page }) => {
+    // One step: the undo replays the row insertion before the merges are restored.
+    await page.evaluate(() => {
+      window.hot.batch(() => {
+        window.hot.alter('insert_row_above', 0);
+        window.hot.getPlugin('mergeCells').merge(2, 1, 3, 2);
+      });
+      window.hot.selectCell(0, 0);
+    });
+    await expect.poll(() => grid.merges()).toEqual([[2, 1, 2, 2]]);
+
+    await grid.undoWithKeyboard();
+    await expect.poll(() => grid.merges()).toEqual([]);
+
+    await expectPlainCellsCopied();
+  });
 });