[[扩展名]] 悬停时如何获取 link 地址

[[extension]] how to get link address when hovered

我想获取整个link地址,但是hoverProvider,我只能获取悬停范围的一部分。

这里是activate代码和结果

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

那么如何得到整个link 'https://www.youtube.com'?

根据 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.

因此,在您的情况下,您只需向 getWordRangeAtPosition 方法添加一个正则表达式:

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