diff --git a/src/editor/core/model/document.test.ts b/src/editor/core/model/document.test.ts index c86306a9d3..23ef30d0b1 100644 --- a/src/editor/core/model/document.test.ts +++ b/src/editor/core/model/document.test.ts @@ -1,5 +1,5 @@ import { afterEach, describe, expect, it, vi } from "vitest"; -import { EditorState, StateEffect } from "@codemirror/state"; +import { ChangeSet, EditorState, StateEffect } from "@codemirror/state"; import { showTooltip, type Tooltip } from "@codemirror/view"; import { indentUnit, language as languageFacet } from "@codemirror/language"; import { HEAVY_LIMIT, onEditorEvent, registerSaveParticipant, remoteChange, shownAgain } from "@/editor/api"; @@ -675,6 +675,24 @@ describe("DocumentManager + slots", () => { }); }); +describe("modified ranges", () => { + it("drops a range past the end instead of throwing out of the edit", () => { + const m = new ModifiedRanges(); + m.ranges = [ + [2, 4], + [580, 587], + ]; + const warn = vi.spyOn(console, "warn").mockImplementation(() => {}); + m.add(ChangeSet.of({ from: 0, insert: "ab" }, 10)); + expect(m.ranges).toEqual([ + [4, 6], + [0, 2], + ]); + expect(warn).toHaveBeenCalledOnce(); + warn.mockRestore(); + }); +}); + describe("save cleanup", () => { it("keeps the caret line and untouched lines", () => { const state = EditorState.create({ doc: "a \nb \nc " }); diff --git a/src/editor/core/model/document.ts b/src/editor/core/model/document.ts index ba166b5e9c..d456a6aeb5 100644 --- a/src/editor/core/model/document.ts +++ b/src/editor/core/model/document.ts @@ -146,7 +146,12 @@ export class ModifiedRanges { map(changes: ChangeSet) { if (this.all) return; - this.ranges = this.ranges.map(([a, b]): [number, number] => [changes.mapPos(a, -1), changes.mapPos(b, 1)]); + // A range past the end belongs to another version of the text; mapping it would throw out of the + // edit (before the document is marked dirty, so the edit would never be saved). Drop it instead. + const kept = this.ranges.filter(([, b]) => b <= changes.length); + if (kept.length < this.ranges.length) + console.warn(`modified ranges past the end (${changes.length}) dropped`, this.ranges.length - kept.length); + this.ranges = kept.map(([a, b]): [number, number] => [changes.mapPos(a, -1), changes.mapPos(b, 1)]); } add(changes: ChangeSet) {