Monaco Editor: How to Input Content at Certain Positions

Helios Yuhan Liu
2 min readMay 21, 2024

--

How to insert text at a certain position.

Photo by Riku Lu on Unsplash

This story will show you how to input new content at a position at certain positions.

// Function to insert text at a specific position
function insertTextAtPosition(text, position) {
// Create a range starting from the position to the same position (a point)
const range = new monaco.Range(
position.lineNumber, // Start at the line number of the position
position.column, // Start at the column number of the position
position.lineNumber, // End at the line number of the position
position.column // End at the column number of the position
);

// Define the edit operation
const editOperation = {
range: range,
text: text, // The text to be inserted
forceMoveMarkers: true // This is optional, depending on your needs
};

// Execute the edit operation
editor.executeEdits("mySource", [editOperation]);
}

// Example usage:
// Let's say you want to insert the text "console.log('Hello, World!');" at position { lineNumber: 1, column: 1 }
const position = { lineNumber: 1, column: 1 };
const textToInsert = "console.log('Hello, World!');";
insertTextAtPosition(textToInsert, position);

AI Kimi generated the example code.

This can be implemented by calling the executeEdits method of the editor.

First, we need to define some parameters. Such as which line we will insert the text in, and what text we want to insert.

Second, we need to call this method to execute the code with the parameters we defined before.

--

--

Helios Yuhan Liu

Computer Science Student/Guitarist and Songwriter/Creator/World Explorer, Trying to Make the World a Better Place 🌠