我知道如何格式化整个文档,但我遇到一个特定的要求,即如何格式化用户选择的一段代码。
正如“Hello world”游乐场建议我们可以选择一段代码并执行Format Selection上下文菜单,但它并没有按预期工作。
1Cr*_*Ni9 10
这个问题是我自己解决的,如果有人可能遇到这个问题,我会给出一些详细的解释。
我将制作一个不是内置语言的 SQL 编辑器。
如果您尝试使“格式文档”和“格式选择”工作,则需要对此自定义语言进行一些配置。
开始了:
import * as monaco from 'monaco-editor';
// https://github.com/zeroturnaround/sql-formatter
import { format } from 'sql-formatter';
// define a document formatting provider
// then you contextmenu will add an "Format Document" action
monaco.languages.registerDocumentFormattingEditProvider('sql', {
provideDocumentFormattingEdits(model, options) {
var formatted = format(model.getValue(), {
indent: ' '.repeat(options.tabSize)
});
return [
{
range: model.getFullModelRange(),
text: formatted
}
];
}
});
// define a range formatting provider
// select some codes and right click those codes
// you contextmenu will have an "Format Selection" action
monaco.languages.registerDocumentRangeFormattingEditProvider('sql', {
provideDocumentRangeFormattingEdits(model, range, options) {
var formatted = format(model.getValueInRange(range), {
indent: ' '.repeat(options.tabSize)
});
return [
{
range: range,
text: formatted
}
];
}
});
Run Code Online (Sandbox Code Playgroud)
经过这些配置后,您可以:
// mannually trigger document formatting by:
monacoEditor.trigger("editor", "editor.action.formatDocument");
// mannully tirgger selection formatting by:
monacoEditor.trigger("editor", "editor.action.formatSelection");
Run Code Online (Sandbox Code Playgroud)
API参考:
| 归档时间: |
|
| 查看次数: |
7172 次 |
| 最近记录: |