显示Monaco编辑器中错误的快速修复方法

9

我正在尝试使用Monaco作为自定义语言的编辑器。

我在playground中使用以下代码展示示例错误(省略部分内容):

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);
});

这将在编辑器中产生所需的错误:

Error hover

如何使快速修复选项出现?(而不是“无可用快速修复”)

我已经查看了monaco.languages.registerCodeActionProvider(),但我不知道它如何与错误检测代码相关联。

更一般地说,我很难找到使用Monaco实现快速修复的示例。

1个回答

9

我使用代码操作提供程序解决了它。

关键是在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: () => {}
        }
    }
});

快速修复

仍然想知道我是否错过了Monaco的明显文档或示例来源。我是通过使用https://microsoft.github.io/monaco-editor/api/index.htmlmonaco.d.ts来拼凑出来的,但这需要很多试错。


谢谢!如果有人需要的话,Monaco的API与Visual Code相当不同。例如,在'https://github.com/microsoft/monaco-json'上的Monaco-for-JSON示例使用`vscode-languageserver-types`,这就需要来回适应。 - Sean
这个快速修复的更改是否已经被推入了您的撤销堆栈中?当我在应用快速修复后按Ctrl-Z时,它会恢复到快速修复之前的状态。我尝试在编辑中设置版本ID,但似乎没有帮助。 - ehdv
看起来不错,但是在我的情况下没有起作用,除非你将最内层的 edits: [{...}] 更改为 edit: {},如 https://microsoft.github.io/monaco-editor/api/interfaces/monaco.languages.codeaction.html 中所述。 - mwag
在你的代码中,什么将特定的快速修复与其特定的错误联系起来? - cs_pupil
由于 API 在 0.20.0 版本中发生了重大变化,因此必须是 edit: { edits: [{ edit: {... - PAX

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