Monaco编辑器:在插入文本时更新光标位置

6
我正在使用位于编辑器外部的按钮(即“hello world”)向Monaco编辑器添加一些文本,然后尝试将光标位置设置为下一行。我尝试使用编辑器中的“setPosition({column:x, lineNumber:y})”函数来实现,但它不起作用。以下是我的实现方式:
insertInPosition(textToInsert:string, cursorPosition:any){
    this.editorInstance.setPosition(cursorPosition);
    var allInstructions = this.instructionSet.split("\n")
    allInstructions.splice(cursorPosition.lineNumber - 1, 0, textToInsert);
    allInstructions.splice(cursorPosition.lineNumber, 1);
    allInstructions = allInstructions.join("\n");
    this.editorInstance.setPosition(cursorPosition);
}

我期望看到光标处于由cursorPosition定义的行和列,但实际上我看到光标指向第1行第1列(在编辑器顶部)。

我还尝试在onDidChangeModelContent()方法内使用相同的API editor.setPosition(),但它不起作用。当我在控制台中打印editor.getPosition()时,我收到了正确的位置。

对此有什么想法吗?

2个回答

3
this.editor?.trigger('keyboard', 'type', {text: 'value'});
this.editor?.focus();
const position: any  = this.editor?.getPosition();
this.editor?.setPosition(position);

5
请说明您的代码。 - mishsx

0
一些 Monaco 编辑器事件(包括 onDidChangeModelContent()),在执行后会更改光标位置。我从这里 获取了这个信息
要防止这种情况发生,你可以像这样做:
var overridenPosition = null;

editor.onDidChangeModelContent(e => {
    if (/* your condition here */) {
        // your logic here
        overridenPosition = { lineNumber: 4, column: 2 }; // put your value here
    }
});

editor.onDidChangeCursorPosition(e => {
    if (overridenPosition != null) {
        editor.setPosition(overridenPosition);
        overridenPosition = null;
    }
});

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接