Monaco-Editor悬停提供程序获取鼠标悬停的单词

8

如何在Monaco编辑器中获取鼠标悬停的单词?

我想显示保存在我的数组中的特定值,以覆盖用户悬停在的单词。因此,当用户悬停在单词上时,我想将该单词与保存在我的数组中的单词进行比较,然后显示该单词的保存值。

我知道以下两种方法:

model.getValue() // gets all the text stored in the model
model.getValueInRange({startLineNumber, startColumn, endLineNumber, endColumn}) // gets the value in Range, but I don't now the start and end column.

以下是我的代码,我只需要在方法getValueInRange上的帮助:

 public variableHoverProvider = <monaco.languages.HoverProvider>{
    // this is for getting the values on hover over context variables and shortcuts
    provideHover: (model, position, token) => {
        if (model.getLineContent(position.lineNumber).trim() !== '') { // if only whitespace don't do anything
            let current = this.store[this.store.length - 1]; // just the place where I store my words and there values

            console.log(model.getValueInRange({
                startLineNumber: position.lineNumber,
                startColumn: 1, // this is the information I am missing
                endLineNumber: position.lineNumber,
                endColumn: 5  // this is the information I am missing
            }));

             // TODO: I have to find somehow the word the mouse is hovering over
            // let getMatchingContextVariableValue = current.contextVariables.map(ctxVariable=>{
            //     if(ctxVariable)
            // });

            let test = current.contextVariables[22].value;

            return {
                contents: [
                    { value: test }
                ],
            };
        }
    }
};

有没有人有好的想法,可以告诉我如何获取我正在悬停的文本?或者如何在getvalueInRange方法中计算startColumn和endColumn?

这里是Monaco-Editor HoverProvider Playground

1个回答

9

您不需要通过model.getValueInRange来获取值,只需使用model.getWordAtPosition即可。

方便的是,HoverProvider会使用modelposition进行调用,所以这不是问题。

为了提供可以在monaco playground中执行的最小示例:

monaco.languages.register({ id: 'mySpecialLanguage' });

monaco.languages.registerHoverProvider('mySpecialLanguage', {
    provideHover: function(model, position) { 
        // Log the current word in the console, you probably want to do something else here.
        console.log(model.getWordAtPosition(position));
    }
});

monaco.editor.create(document.getElementById("container"), {
    value: '\n\nHover over this text',
    language: 'mySpecialLanguage'
});

请注意,这将返回一个 IWordAtPosition 对象,它有三个属性:

endColumn: number

单词结束的列。

startColumn: number

单词开始的列。

word: string

单词。

因此,要获取悬停位置的字符串单词,您需要访问 model.getWordAtPosition(position).word

我寻找这个已经很久了。我知道有一个简单的方法,因为我可以看到Monaco编辑器正确地放置了弹出窗口。谢谢。 - Devid

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