[英]Microsoft Monaco Editor in browser get value of line
我一直在使用基於瀏覽器的Microsoft Monaco Editor版本,我在操場上找不到任何文檔或任何示例,告訴您如何獲取編輯器中特定行的值。
例如:
class Example {
private m:number;
public met(): string {
return "Hello world!";
}
}
第2行是private m:number;
。
你如何獲得該行的值,甚至是行的一部分,然后使用代碼更改它的值。 我想將該動作放入鍵盤快捷鍵。
獲取一行的內容實際上非常簡單: IModel.getLineContent()
line = model.getLineContent(3);
請注意,使用getLineContent()
時行號以1 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"
},
],
[]
);
如果你想在Monaco游樂場測試它,我使用了這段代碼(改編自“添加動作”示例):
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"
},
],
[]
);
}
});
在這種情況下,您可以按以下方式運行操作:
我認為摩納哥沒有這樣的內置功能,因為我沒有找到它。 但我正在使用以下代碼:
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,
}
});
這個方法適用於小文件,但對於大文件,整個編輯器將重新突出顯示並且這是一件壞事。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.