Jes*_*sse 5 javascript browser monaco-editor
我一直在使用基于浏览器的 Microsoft Monaco 编辑器版本,我在操场上找不到任何文档或任何示例来告诉您如何获取编辑器中特定行的值。
例如:
class Example {
private m:number;
public met(): string {
return "Hello world!";
}
}
Run Code Online (Sandbox Code Playgroud)
第 2 行将是private m:number;.
您将如何获取该行甚至该行的一部分的值,然后使用代码更改它的值。我想将该操作放入键盘快捷键中。
MSe*_*ert 10
获取一行的内容其实很简单: IModel.getLineContent()
line = model.getLineContent(3);
Run Code Online (Sandbox Code Playgroud)
请注意,使用getLineContent().
替换文本有点复杂,但您可以应用编辑操作:
本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"
},
],
[]
);
Run Code Online (Sandbox Code Playgroud)
如果你想在摩纳哥游乐场上测试它,我使用了这个代码(改编自“添加操作”示例):
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"
},
],
[]
);
}
});
Run Code Online (Sandbox Code Playgroud)
在这种情况下,您可以通过以下方式运行操作:
我认为摩纳哥没有这样的内置功能,因为我没有找到它。但我正在使用以下代码来做到这一点:
editor.addAction({
id: 'some_id',
label: 'label',
keybindings: [monaco.KeyMod.CtrlCmd | monaco.KeyCode.KEY_C],
run: function(ed) {
var position = ed.getPosition();
var text = ed.getValue(position);
var splitedText=text.split("\n");
var line = splitedText[position.lineNumber-1];
// now you have current line
// you can also get any other line
// and do something with that line
splitedText[position.lineNumber-1]= _newLineText_
ed.setValue(splitedText.join("\n"));
ed.setPosition(position); // to return the pointer to the a position before editing text
return null;
},
enablement: {
textFocus: true,
}
});
Run Code Online (Sandbox Code Playgroud)
此方法适用于小文件,但对于大文件,整个编辑器将重新突出显示,这是一件坏事。
| 归档时间: |
|
| 查看次数: |
4076 次 |
| 最近记录: |