Learn how to insert some text into a specific position in ACE Editor.

Ace is an embeddable code editor written in JavaScript that can be easily embedded in any web page and JavaScript application. In some scenarios you will need to insert some text inside your editor from external sources, whatever the kind of sources they are, they probably will need to be inserted in a position that matches to your needs (not where the editor want). Through the API of Ace Editor you will be able to specify easily in which row (line) of the editor and in which column should your text be placed.

Inserting text in custom position

To insert some text in the editor in a custom position, you need to access the insert method in the session object of the editor. This method expects 2 arguments, the first is an object with 2 properties row and column, these values are integers that specify the position where the text should be inserted (the row is the number of the line -1 and the column the number of characters to the right on which the text will be placed), see the following example:

// Create an editor
var editor = ace.edit("editorID");
editor.setTheme("ace/theme/monokai");
editor.getSession().setMode("ace/mode/javascript");


// Add some text in a custom position
var customPosition = {
    row: 0,
    column: 0
};

var text = "This text has been dinamically inserted";

editor.session.insert(customPosition , text);

Note that in the same way an array does, the position (lines and columns) in the editor starts with 0 (line 1 will be row 0).

Inserting text where the cursor is located

In this example we want to insert some text in the editor exactly where the caret (cursor) is located, that would be inside the double quotes in the 4th line:

ACE Editor insert text where cursor is located

To achieve it, we will use the same method insert of the editor.session object, however the first argument won't be generated by you but another method. You can retrieve the position of the cursor using the getCursorPosition method of the editor that returns an object with 2 properties, row and column. To insert some text where the cursor is located, provide as first argument in the insert method of editor.session the object retrieved by getCursorPosition and as second argument the text that you want to insert:

// Retrieve cursor position
// In the example would be an object like
// {row: 3, column: 18}
var cursorPosition = editor.getCursorPosition();
// Insert text (second argument) with given position
editor.session.insert(cursorPosition,"#fff");

That should insert the string #fff inside the double quotes of our editor:

Insert text where cursor is located ACE Editor

Happy coding !


Senior Software Engineer at Software Medico. Interested in programming since he was 14 years old, Carlos is a self-taught programmer and founder and author of most of the articles at Our Code World.

Sponsors