0

I want to get the whole link address, but with the hoverProvider, I can only get the part of hoverd range.

here is the activate code and the result

export function activate(context: vscode.ExtensionContext) {
  // Use the console to output diagnostic information (console.log) and errors (console.error)
  // This line of code will only be executed once when your extension is activated


  const disposal = vscode.languages.registerHoverProvider("javascript", {
    provideHover(document, position, token) {
      const range = document.getWordRangeAtPosition(position);
      const word = document.getText(range);
     
      return new vscode.Hover(
      
        word
      );
    },
  });

  context.subscriptions.push(disposal);
}

enter image description here

so how to get the whole link 'https://www.youtube.com'?

homy
  • 311
  • 2
  • 7

1 Answers1

2

According to the documentation, the getWordRangeAtPosition method allows you to define a custom word definition with a regular expression. A good regular expression to match a URL can be found in this answer.

Thus, in your case, you'd simply have to add a regular expression to the getWordRangeAtPosition method:

provideHover(document, position, token) {
    const URLregex = /(https?:\/\/)*[-a-zA-Z0-9@:%._\+~#=]{1,256}\.[a-zA-Z0-9()]{1,6}\b([-a-zA-Z0-9()@:%_\+.~#?&//=]*)?/gi;
    const range = document.getWordRangeAtPosition(position, URLregex);
    const word = document.getText(range);
    return new vscode.Hover(word);
}
notexactly
  • 918
  • 1
  • 5
  • 21
  • thanks for your reply! I didn't realize the hover word is already split by the `word definition`, I thought it's the exact word – homy Jan 30 '22 at 12:36