简体   繁体   English

在摩纳哥编辑器中显示错误的快速修复

[英]Show quick fix for an error in Monaco Editor

I'm experimenting with Monaco as an editor for a custom language. 我正在尝试将摩纳哥作为自定义语言的编辑器。

I use this code to show an example error in the playground (some parts omitted): 我使用以下代码来显示操场上的示例错误(省略了某些部分):

const editor = monaco.editor.create(<omitted>);
const model = editor.getModel();
model.onDidChangeContent(event => {
   const value = model.getValue();
   const errors = GetErrors(value); // Implementation of GetErrors() not shown here

    monaco.editor.setModelMarkers(model, "Example", errors);
});

Which results in the desired error in the editor: 在编辑器中导致所需的错误:

错误悬停

How do I make a quick fix appear for that error? 如何针对该错误显示快速修复? (Instead of "No quick fixes available") (而不是“没有快速修复可用”)

I've looked at monaco.languages.registerCodeActionProvider() but I don't see how that ties in to the error detection code. 我看过monaco.languages.registerCodeActionProvider()但是看不到它与错误检测代码的联系。

More generally, I've struggled to find examples for implementing Quick Fix with Monaco. 更笼统地说,我一直在努力寻找与摩纳哥一起实施Quick Fix的示例。

I got it working using a Code Action Provider. 我使用代码操作提供程序来工作。

The key was to use context.markers inside provideCodeActions() to get the errors I raised elsewhere (via setModelMarkers() ). 关键是在provideCodeActions()使用context.markers来获取我在其他地方(通过setModelMarkers() )引发的错误。

monaco.languages.registerCodeActionProvider("myLanguage", {
    provideCodeActions: (
        model /**ITextModel*/,
        range /**Range*/,
        context /**CodeActionContext*/,
        token /**CancellationToken*/
    ) => {

        const actions = context.markers.map(error => {
            return {
                title: `Example quick fix`,
                diagnostics: [error],
                kind: "quickfix",
                edit: {
                    edits: [
                        {
                            resource: model.uri,
                            edits: [
                                {
                                    range: error,
                                    text: "This text replaces the text with the error"
                                }
                            ]
                        }
                    ]
                },
                isPreferred: true
            };
        });
        return {
            actions: actions,
            dispose: () => {}
        }
    }
});

快速解决

Would still love to know if I'm missing an obvious source of documentation or examples for Monaco. 我仍然想知道我是否缺少摩纳哥的明显文献或示例资源。 I pieced this together using https://microsoft.github.io/monaco-editor/api/index.html and monaco.d.ts but it took a lot of trial and error. 我使用https://microsoft.github.io/monaco-editor/api/index.htmlmonaco.d.ts将它们拼凑在一起,但是这花费了大量的试验和错误。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM