Search code examples
visual-studio-codevscode-extensions

Can I show an image in a HoverProvider?


I am new to vscode extension development so not sure best places to look for help. I want to hover over a word, and if that word matches the name in our icon directory, show a hover with that image. My first try was to use markdown to show the svg image from the web, but I believe that is not allowed for security that code could be executed. Can I show an svg in the markdown in a vscode.Hover? I can either include the svgs in the extension, or expect that the developer has already installed the npm package with the files into the workspace.


Solution

  • There is actually quite rich support for content and styling in MarkdownString in hovers.

    You can use svg's directly this way:

    const icon = new vscode.MarkdownString('<img src="icon.svg"/>');
    icon.baseUri = vscode.Uri.file(path.join(context.extensionPath, 'images', path.sep));
    

    The baseUri property is crucial. Here it gets the svgs from an images folder.

    In the below I added the png images to an extension images folder. You can detect what word is hovered and load the corresponding icon.

    Below is testing in a plaintext file:

    
    // with this require/import
    const path = require('path');
    
    // ...
    
    let disposable4 = vscode.languages.registerHoverProvider('plaintext', {
      provideHover(document, position) {
    
        // one way to find the current hovered word
        // note that what is a 'word' is languaged-defined and typically does not include hyphens
        // const word = document.getText(document.getWordRangeAtPosition(position));
        // first check if there is an icon for the hovered word, if not return undefined
        // glob the images folder and find 'icon'.svg
        // const icon = new vscode.MarkdownString(`<img src="${word}.svg"/>`);
      
        // dimensions not necessary if you aren't changing them
        const content = new vscode.MarkdownString(`<img src="favicon144.png" width=144 height=144/>`);
    
        content.appendMarkdown(`$(zap)`);  // notice the little "zap" icon in the hover
    
        content.supportHtml = true;
    
        content.isTrusted = true;
    
        content.supportThemeIcons = true;  // to supports codicons
        
        // baseUri was necessary, full path in the img src did not work
        // with your icons stroed in the 'images' directory
        content.baseUri = vscode.Uri.file(path.join(context.extensionPath, 'images', path.sep));            
    
        return new vscode.Hover(content, new vscode.Range(position, position));
      }
    });
    

    add an image to a hover pop-up