gpt4 book ai didi

javascript - 浏览器中的 Microsoft Monaco Editor 获取行的值

转载 作者:塔克拉玛干 更新时间:2023-11-02 23:00:54 25 4
gpt4 key购买 nike

我一直在使用基于浏览器的 Microsoft Monaco Editor 版本,我在 playground 中找不到任何文档或任何示例来告诉您如何在编辑器中获取特定行的值。

例如:

class Example {
private m:number;

public met(): string {
return "Hello world!";
}
}

第 2 行将是 private m:number;

您将如何获取该行甚至部分行的值,然后使用代码更改它的值。我想将该操作放入键盘快捷键中。

最佳答案

获取一行内容其实很容易:IModel.getLineContent()

line = model.getLineContent(3);

请注意,使用 getLineContent() 时,行号以 1 开头。

替换文本有点复杂,但您可以应用编辑操作:

applyEdits 不会将编辑添加到撤消堆栈,因此不鼓励使用。然而,所有三个都使用相同的界面进行实际更改:IIdentifiedSingleEditOperation所以实际的调用不会有太大的不同,所以我将使用 pushEditOperations() 来展示它:

model.pushEditOperations(
[],
[
{
forceMoveMarkers: true,
identifier: "mychange",
range: {
startLineNumber: lineNo,
endLineNumber: lineNo,
startColumn: 1,
endColumn: line.length + 1,
},
text: "this will be the new text there"
},
],
[]
);

如果您想在摩纳哥 Playground 上进行测试,我使用了这段代码(改编自“添加 Action ”示例):

var editor = monaco.editor.create(document.getElementById("container"), {
value: [
'',
'class Example {',
'\tprivate m:number;',
'',
'\tpublic met(): string {',
'\t\treturn "Hello world!";',
'\t}',
'}'
].join('\n'),
language: "typescript"
});
var model = editor.getModel();

editor.addAction({
id: 'my-unique-id',
label: 'Replace the second line',
keybindings: [ monaco.KeyMod.CtrlCmd | monaco.KeyCode.F10 ],
contextMenuGroupId: 'custom',
contextMenuOrder: 1,
run: function(ed) {
var lineNo = 3;
var line = model.getLineContent(lineNo);
console.log("These were the contents of the second line before I replaced them:", line);
model.pushEditOperations(
[],
[
{
forceMoveMarkers: true,
identifier: "mychange",
range: {
startLineNumber: lineNo,
endLineNumber: lineNo,
startColumn: 1,
endColumn: line.length + 1,
},
text: "this will be the new text there"
},
],
[]
);
}
});

在这种情况下,您可以通过以下方式运行操作:

  • Ctrl + F10
  • 右键单击编辑器并选择“替换第二行”(至少在您没有隐藏编辑器上下文菜单的情况下)。

关于javascript - 浏览器中的 Microsoft Monaco Editor 获取行的值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38674092/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com