Monaco 中如何使用 OnTypeFormattingEditProvider,OnTypeFormat 是指输入指定字符后 Monaco 会自动进行格式化,例如换行、大括号、分号。效果如下:
首先通过 registerOnTypeFormattingEditProvider 注册 OnTypeFormattingEditProvider 处理函数
实现 autoFormatTriggerCharacters 和 provideOnTypeFormattingEdits,autoFormatTriggerCharacters 返回触发格式化的字符。provideOnTypeFormattingEdits 返回格式化后的文档。
代码实现如下
首先开启 TypeOnFormat
添加启动配置 formatOnType: true
<Editor
height="90vh"
defaultLanguage="mySpecialLanguage"
defaultValue=""
options={{ 'semanticHighlighting.enabled': true, 'linkedEditing': true,
'formatOnType': true }}
onMount={handleEditorDidMount}
/>
添加自定义语言
首先需要自定义需要配置的语言,例如 mySpecialLanguage。
monaco.languages.register({ id: "mySpecialLanguage" });
实现注册函数
export function onTypeFormattingEditProvider(editor: monacoEditor.editor.IStandaloneCodeEditor, monaco: typeof monacoEditor){
return monaco.languages.registerOnTypeFormattingEditProvider('mySpecialLanguage', {
autoFormatTriggerCharacters: ['a', '\n'],
provideOnTypeFormattingEdits: (model, position, ch, options, token) => {
const edits: monacoEditor.languages.TextEdit[] = [];
// Example: Auto indent on typing '}' or newline
if (ch === '}' || ch === '\n') {
const lineContent = model.getLineContent(position.lineNumber);
const indentMatch = lineContent.match(/^(\s*)/);
if (indentMatch) {
const indent = indentMatch[1];
const newIndent = ch === '}' ? indent.substring(0, indent.length - 2) : indent + ' ';
// Insert formatting edit
edits.push({
range: new monaco.Range(position.lineNumber, 1, position.lineNumber, position.column),
text: newIndent
});
}
}
return edits;
}
})
}