Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Monaco Editor get source code index of caret

Is there a way to get the caret position as index in the source code string? I know I can get the position, which will give me an object, containing the line and column, but is there a way to either get or convert line + column to string char index?

For example if I have:

using System;
using System.Data;

and I place the caret to be just before ".Data", I know how to get the line + col coordinate (line 1, col 13), but how to get the char array index (should be something like 25)?

like image 268
Pavel Donchev Avatar asked Mar 07 '23 07:03

Pavel Donchev


1 Answers

You can use the following sample code in the Monaco Playground to try things out.

The function you are looking for is ITextModel's getOffsetAt(IPosition) function.

var model = monaco.editor.createModel(
    "using System;\n" +
    "using System.Data;",
    "csharp"
); 

var editor = monaco.editor.create(document.getElementById("container"), {
    model
});

var offset = model.getOffsetAt({ lineNumber: 2, column: 13 });
alert(offset);
like image 60
rcjsuen Avatar answered May 21 '23 11:05

rcjsuen