Monaco Editor get source code index of caret

。_饼干妹妹 提交于 2020-12-12 08:57:36

问题


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)?


回答1:


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);



回答2:


Okay, not sure if this is the best way, but the following seems to work properly:

  1. Get the editor position (line + column).
  2. Get the text until that position.
  3. Get the length of that text

Here is an example code:

var line = window.editor.getPosition().lineNumber;
var col = window.editor.getPosition().column;
var textUntilPosition = window.editor.model.getValueInRange({ startLineNumber: 1, startColumn: 1, endLineNumber: line, endColumn: col });
var currentPos = textUntilPosition.length;


来源:https://stackoverflow.com/questions/50089334/monaco-editor-get-source-code-index-of-caret

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!