在Monaco编辑器中进行自定义语言的语法验证

25

我正在尝试将自定义语言集成到 Monaco 编辑器中,我查看了 https://microsoft.github.io/monaco-editor/monarch.html 以了解语法高亮的情况。

但是我无法找到有关如何通过语法验证来添加错误/警告验证的文档。在 Ace 编辑器中,我们通过编写工作程序并在其中执行验证函数来实现此操作。如果您有任何链接/帮助,请不吝赐教。

2个回答

21
我最近成功地完成了这项任务,我只需使用monaco-css作为样板,现在要做的就是编写我的语言解析器和其他我想要的功能。这是我的code
将您的解析器和其他语言服务添加到项目根目录中的lang_services文件夹中。
我认为这会很有帮助。

4

以下是一个简明且易于自定义的示例,它将在第1行2-5位置显示错误,如下图所示:

enter image description here

只需要将以下代码插入到播放区代码的顶部(不是底部),具体位置请参见https://microsoft.github.io/monaco-editor/playground.html#extending-language-services-custom-languages

monaco.editor.onDidCreateModel(function(model) {
    function validate() {
      var textToValidate = model.getValue();

      // return a list of markers indicating errors to display

      // replace the below with your actual validation code which will build
      // the proper list of markers

      var markers = [{
        severity: monaco.MarkerSeverity.Error,
        startLineNumber: 1,
        startColumn: 2,
        endLineNumber: 1,
        endColumn: 5,
        message: 'hi there'
      }];

      // change mySpecialLanguage to whatever your language id is
      monaco.editor.setModelMarkers(model, 'mySpecialLanguage', markers);
    }

    var handle = null;
    model.onDidChangeContent(() => {
      // debounce
      clearTimeout(handle);
      handle = setTimeout(() => validate(), 500);
    });
    validate();
});

// -- below this is the original canned example code:

// Register a new language

请注意,为了简化起见,此示例忽略了考虑到onDidCreateModelonDidChangeContent都返回IDisposable对象的情况,您可能需要跟踪并处理这些对象。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接