单击获取 Monaco Editor CodeLens 信息

Get Monaco Editor CodeLens info on click

以此 CodeLens provider example 为起点,我一直在尝试弄清楚如何在单击 link 时获取与 CodeLens 关联的范围信息。

var commandId = editor.addCommand(0, function() {
    // services available in `ctx`
    alert('my command is executing!');

}, '');

monaco.languages.registerCodeLensProvider('json', {
    provideCodeLenses: function(model, token) {
        return [
            {
                range: {
                    startLineNumber: 1,
                    startColumn: 1,
                    endLineNumber: 2,
                    endColumn: 1
                },
                id: "First Line",
                command: {
                    id: commandId,
                    title: "First Line"
                }
            }
        ];
    },
    resolveCodeLens: function(model, codeLens, token) {
        return codeLens;
    }
});

我不确定 ctx 评论指的是什么。我已经尝试将它作为参数添加到 addCommand 中的那个匿名函数参数,但我没有从中得到任何东西。甚至有可能获得 provideCodeLenses 函数中指定的范围信息吗?

为了解决这个问题,我在 provideCodeLenses 中的返回对象的 command 属性 中添加了一个 arguments 属性:

provideCodeLenses: function(model, token) {
    return [
        {
            range: {
                startLineNumber: 1,
                startColumn: 1,
                endLineNumber: 2,
                endColumn: 1
            },
            id: "First Line",
            command: {
                id: commandId,
                title: "First Line",
                arguments: { from: 1, to: 2 },
            }
        }
    ];
}

然后可以在 addCommand 匿名函数中访问它:

var commandId = editor.addCommand(0, function(ctx, args) {
    console.log(args); // { from: 1, to: 2 }
}, '');