如何格式化一段代码

时间:2021-02-23 01:05:40

标签: monaco-editor

我知道如何格式化整个文档,但我遇到了一个具体要求,即如何格式化用户选择的一段代码。

"Hello world" playground 建议我们可以选择一段代码并执行 Format Selection 上下文菜单,但它没有按预期工作。

1 个答案:

答案 0 :(得分:0)

这个问题是我自己解决的,如果有人可能会遇到这个问题,我会给出一些详细的解释。

我将制作一个非内置语言的 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
      }
    ];
  }
});

完成这些配置后,您可以:

// mannually trigger document formatting by:
monacoEditor.trigger("editor", "editor.action.formatDocument");

// mannully tirgger selection formatting by:
monacoEditor.trigger("editor", "editor.action.formatSelection");

API 参考:

相关问题