/** * Tests for the mapping between engine text (line breaks as on disk) and * CodeMirror documents (one position per line break). */ import { ChangeSet, Text } from "@codemirror/state"; import { describe, expect, it } from "vitest"; import { diffDocs, EngineText, separatorOf } from "../../src/components/editor/engineText"; describe("EngineText", () => { it("maps positions past CRLF breaks and keeps mixed endings", () => { const text = EngineText.fromEngine("a\r\nb\nc\rd\r\n"); expect(text.doc.toString()).toBe("a\nb\nc\nd\n"); expect(text.toEngine(0)).toBe(0); expect(text.toEngine(2)).toBe(3); expect(text.toEngine(4)).toBe(5); expect(text.toEngine(8)).toBe(10); expect(text.toEngine(99)).toBe(10); expect(text.engineString()).toBe("a\r\nb\nc\nd\r\n"); }); it("is the identity for text without CRLF", () => { const text = EngineText.fromEngine("x😀\ny"); expect(text.toEngine(4)).toBe(4); }); it("turns changes into engine edits with the buffer's line ending", () => { const text = EngineText.fromEngine("ab\r\ncd\r\n"); const changes = ChangeSet.of( [ { from: 1, insert: "\n" }, { from: 3, to: 5, insert: "X" }, ], text.doc.length, ); expect(text.edits(changes, "\r\n")).toEqual([ { from: 1, to: 1, insert: "\r\n" }, { from: 4, to: 6, insert: "X" }, ]); const after = text.apply(changes, "\r\n"); expect(after.doc.toString()).toBe("a\nb\nX\n"); expect(after.engineString()).toBe("a\r\nb\r\nX\r\n"); }); it("diffs documents into one replacement", () => { const a = Text.of(["hello", "world"]); const b = Text.of(["hello", "brave", "world"]); const diff = diffDocs(a, b); expect(diff.apply(a).toString()).toBe(b.toString()); expect(diffDocs(a, a).empty).toBe(true); }); it("names separators", () => { expect(separatorOf("crlf")).toBe("\r\n"); expect(separatorOf("cr")).toBe("\r"); expect(separatorOf("lf")).toBe("\n"); expect(separatorOf("?")).toBe("\n"); }); });