Replacing editor content with something else breaks the editor

Hi, I am developing a small Svelte application that includes a CodeMirror editor. At the top of my page, I have a menubar allowing the user to load some “tutorial programs”. They are loaded by overriding the current content of the editor:

	/* Overwrite the bulk of the text with the one specified. */
	export function _setText(text: string): void {
		view.dispatch({
			changes: { from: 0, to: view.state.doc.length, insert: text }
		});
	}

The text is stored as a multi-line string somewhere in my application:

let time_tutorial = `
# 1.0: Time, Period and Clocks

# The clock variable is a reference to the clock

clock.tempo # Get tempo
clock.tempo = 130 # Set tempo
clock.cps = 0.5 # Set tempo in cycles per second (see Vortex)
`

After replacing the content of the editor, the insert / delete behavior appears to be slightly broken. Pressing return or delete will trigger the action twice, deleting two letters or adding two new lines.

I am not a JS/TS developer and I know that I keep shooting myself in the foot when developing this application. The full code to the Svelte application can be found here as part of a larger Python application.

What am I doing wrong?

I’m not sure what you are doing wrong. If you can reduce this to a simple plain-CodeMirror script (no Svelte etc) and the problem still isn’t obvious, I can try to debug it.