获取行内容实际上非常简单:
IModel.getLineContent()
。
line = model.getLineContent(3)
请注意,使用
getLineContent()
时,行号从1开始。
替换文本有点复杂,但是您可以应用编辑操作:
- 通过编辑器:
IStandaloneCodeEditor.executeEdits
- 通过模型:
IModel.applyEdits()
和
IModel.pushEditOperations()
。
尽管如此,
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"
},
],
[]
);
如果你想在Monaco playground上测试它,可以使用以下代码(改编自“添加操作”示例):
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
- 右键单击编辑器并选择“替换第二行”(至少如果您没有隐藏编辑器上下文菜单)。