How can I get the word I am hovering over in Monaco editor ?
I want to show a specific value over a word that is saved in my array. So when the user hovers over the word I want to compare that word with the words saved in my array and then show the saved value of that word.
I know these two methods:
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.
Here is my code, I just need the help with the method 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 }
],
};
}
}
};
Has anyone maybe a good Idea how I can get the text I am hovering over ? Or how to calculate the startColumn and endColumn in getvalueInRange method ?
Here is the Monaco-Editor HoverProvider Playground
You don't need to go through model.getValueInRange you can simply use model.getWordAtPosition.
Conveniently the HoverProvider is called with model and position so that's no problem.
To provide a minimal example that can be executed by the 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'
});
Note that this returns a IWordAtPosition object which has three properties:
endColumn: number
The column where the word ends.
startColumn: number
The column where the word starts.
word: string
The word.
So to get the word as string at the hovered position, you need to access model.getWordAtPosition(position).word.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With