Monaco LinkEdit 功能是指同时修改同样的字符串,例如在编辑 Html 时,修改开始标签时会同时修改闭合标签。Monaco 支持自定义需要一起更新的字符串列表。最终效果如下:
首先,通过 registerLinkedEditingRangeProvider 注册 LinkEdit 处理函数
实现 provideLinkedEditingRanges 并返回位置信息
返回需要同步修改的位置信息
代码实现如下
export function linkedEditingRangeProvider(editor: monacoEditor.editor.IStandaloneCodeEditor, monaco: typeof monacoEditor){
monaco.languages.registerLinkedEditingRangeProvider('javascript', {
provideLinkedEditingRanges(model: monacoEditor.editor.ITextModel, position: monacoEditor.Position, token: monacoEditor.CancellationToken) {
const word = model.getWordAtPosition(position);
if (!word) {
return { ranges: [] };
}
const ranges: monacoEditor.IRange[] = [];
const regex = new RegExp(`\\b${word.word}\\b`, 'g');
const lines = model.getLinesContent();
lines.forEach((line, lineIndex) => {
let match: RegExpExecArray | null;
while ((match = regex.exec(line)) !== null) {
const startColumn = match.index + 1;
const endColumn = startColumn + word.word.length;
ranges.push({
startLineNumber: lineIndex + 1,
startColumn: startColumn,
endLineNumber: lineIndex + 1,
endColumn: endColumn
});
}
});
return {
ranges: ranges
};
}
});
}
修改对应配置信息, linkEditing 默认为关闭状态,需要在配置中进行开启。
<div>
<Editor
height="90vh"
defaultLanguage="javascript"
defaultValue=""
options={{ automaticLayout: true, 'semanticHighlighting.enabled': true, 'linkedEditing': true }}
onMount={handleEditorDidMount}
/>
<button onClick={showValue}>Show Value</button>
</div>