我正在开发 Visual Studio Code 扩展,并面临通过悬停提供程序显示本地图像的问题。目标是当鼠标悬停在我的自定义语言“awscript”识别的 .aws 文件中的特定文件路径上时显示图像。
.aws 文件包含悬停时应显示的图像的路径。路径是相对的,文件驻留在工作空间内。这是示例行,我希望能够将鼠标悬停在图像路径上:
Look at this beautiful scene: ../images/landscape.png
我的 TypeScript 中的悬停提供程序代码如下所示:
import * as vscode from 'vscode';
import * as path from 'path';
export function activateHoverProvider(context: vscode.ExtensionContext) {
const hoverProvider = vscode.languages.registerHoverProvider({ scheme: 'file', language: 'awscript' }, {
provideHover(document: vscode.TextDocument, position: vscode.Position, token: vscode.CancellationToken) {
const wordRange = document.getWordRangeAtPosition(position);
if (!wordRange) {
return;
}
const hoveredText = document.getText(wordRange);
if (isValidImagePath(hoveredText)) {
const documentPath = path.dirname(document.uri.fsPath);
const imagePath = path.resolve(documentPath, hoveredText);
const uri = vscode.Uri.file(imagePath).with({ scheme: 'vscode-resource' });
const markdown = new vscode.MarkdownString(`![Image Preview](${uri})`);
markdown.isTrusted = true;
return new vscode.Hover(markdown);
}
}
});
context.subscriptions.push(hoverProvider);
}
function isValidImagePath(filePath: string): boolean {
return filePath.endsWith('.png') || filePath.endsWith('.jpg') || filePath.endsWith('.gif');
}
当我将鼠标悬停在文件路径上时,图像不显示。 URI 正确解析,并且我已经验证了路径,但我看到的只是 [悬停工具提示中的损坏图像图标]。
我读到较新的 API 可能会使用 vscode-webview-resource 而不是 vscode-resource,但我不确定如何在不属于 webview 的悬停提供程序的上下文中应用它。
如何在 VS Code 扩展中使用悬停提供程序正确显示本地图像?我应该为此目的使用特定的 URI 方案或 API 方法吗?
这里有几个问题。
首先,您的
wordRange
和 hoverText
是否符合您的预期 - 它们是否是完整的相对路径,因此在您的示例中为 ../images/landscape.png
。
这可能取决于您语言中的单词分隔符是什么。如果
.
和 /
是单词分隔符,那么您可能无法获得 wrodRange
中的完整路径,因此您的图像路径构建不正确。
如果您只是将鼠标悬停在
landscape
的 landscape.png
上,则此方法有效:
let hoveredText = document.getText(wordRange) + '.png';
你还需要
markdown.baseUri = vscode.Uri.file(path.join(documentPath, 'images', path.sep));
设置实际图像位置的相对路径。
演示:我没有在演示中使用
isValidImagePath()
功能,因此您会看到它在不应该工作的地方不起作用,而在应该工作的地方工作。
因此,您需要弄清楚如何在将鼠标悬停在图像的任何部分上时获取完整的图像路径,并使用
baseUri
属性。