Develop a vscode image hover preview plug-in

Posted by VapiD on Tue, 01 Feb 2022 23:02:31 +0100

In front-end projects, images are often used, either directly in the project or using cdn address, but they all need to click to see what the specific content of the image is, which is cumbersome. Can they be displayed directly when hovering over the mouse like the code prompt?

At present, the most used is Image Preview This plug-in, but when I used it, I found that I didn't see the picture when hovering. Naturally, I wanted to implement one myself.

It can be achieved in three simple steps

After the code is completed, it is abnormally simple,

  1. Specify a language to add additional hover content
  2. Gets whether the current line has a picture link when the mouse hovers
  3. Construct additional hover content
# Create a project folder and enter the folder
mkdir image-preview && cd image-preview
# Initialize package JSON file
npm init -y
# Add entry file
touch index.js

Edit Package JSON add the fields of engines and activationEvents

{
  "name": "image-preview",
  "version": "1.0.0",
  "description": "",
  "main": "index.js",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1"
  },
  "keywords": [],
  "author": "",
  "engines": {
    "vscode": "^1.54.0"
  },
  "activationEvents": [
    "*"
  ],
  "license": "ISC"
}

In this way, we have initialized our project, and then proceed to our first step, "specify a language to add additional hover content"

Specify a language to add additional hover content

// index.js
const vscode = require("vscode");

module.exports.activate = function (context) {
  context.subscriptions.push(
    vscode.languages.registerHoverProvider("javascript", {
      provideHover: (document, position) => {
        return new vscode.Hover("hello");
      },
    })
  );
};

This means that in all js files, the text hello will be displayed when the mouse hovers. Next, let's see the effect.

After clicking, a new vscode window will be opened, and our plug-in will take effect in this window. This window is equivalent to an ordinary vscode window, which can also open projects.

We can create a new file and specify the language as JavaScript, write any content in it, and you can see hello when hover. Or open any of your own projects, just be js file, you can see hello when hovering.

Go back to our image preview project window to complete our second step, "get whether there is a picture link in the current line when the mouse hovers". How to get it? Regular, of course

Gets whether the current line has a picture link when the mouse hovers

// index.js
const vscode = require("vscode");

module.exports.activate = function (context) {
  context.subscriptions.push(
    vscode.languages.registerHoverProvider("javascript", {
      provideHover: (document, position) => {
        const { _line } = position;
        const lineContent = document.lineAt(_line).text;
        const regexp =
          /((https?):)?\/\/[-A-Za-z0-9+&@#/%?=~_|!:,.;]+[-A-Za-z0-9+&@#/%=~_|]/;
        const res = lineContent.match(regexp);
        console.log("1", res);
        if (res === null) {
          return;
        }
        const url = res[0];
        console.log("2", url);
        return new vscode.Hover('hello');
      },
    })
  );
};

Next, we can see that the debug mode window is still in the lower part of the current orange mode, so we can continue to see the debug mode window.

If not, you can do it again according to the above process of entering the debug mode.

Next, click the green button to restart debugging. It will refresh the previously opened debug window. In the debug window, the mouse hovers over the link, and hello still appears. In addition, the DEBUG CONSOLE at the bottom of our project window will also print out the content

The test content is const url = 'https://ai-sample.oss-cn-hangzhou.aliyuncs.com/test/695fd240c6c011eb99f4db4397160818.png ';, If there is no DEBUG CONSOLE panel, you can open it through View Terminal

We can see that our picture path is recognized

Then we can continue with our last step, "constructing additional hover content"

Construct additional hover content

new vscode. The parameter of hover indicates the displayed content. In addition to the string, it also supports markdown syntax, but it cannot be written directly. It also needs to use new vscode Markdownstring construction, so our final code is as follows

// index.js
const vscode = require("vscode");

module.exports.activate = function (context) {
  context.subscriptions.push(
    vscode.languages.registerHoverProvider("javascript", {
      provideHover: (document, position) => {
        const { _line } = position;
        const lineContent = document.lineAt(_line).text;
        const regexp =
          /((https?):)?\/\/[-A-Za-z0-9+&@#/%?=~_|!:,.;]+[-A-Za-z0-9+&@#/%=~_|]/;
        const res = lineContent.match(regexp);
        console.log("1", res);
        if (res === null) {
          return;
        }
        const url = res[0];
        console.log("2", url);
        return new vscode.Hover(new vscode.MarkdownString(`![](${url})`));
      },
    })
  );
};

Similarly, click the green refresh button and continue to hover over the link. After waiting for a while, the picture will be displayed successfully!

The picture is a little big. We can limit its height or width, and then click the green button to refresh. Is the effect better?

 return new vscode.Hover(new vscode.MarkdownString(`![](${url}|width=240)`));

Packaging and publishing

After the vsce dependency is installed in the project, execute the yarn vsce package to package the project into a vslx file, which can be directly installed by others.

Although the publishing process is simple, it is troublesome to register an account. You can refer to other blogs. After configuring the account, you can also publish it to the plug-in market by using the command yarn vsce publish.

Remaining problems

Although the amount of code is small, it is also a usable product. Although the product is still very simple, you can add more functions to it and fix some known problems

1. http protocol pictures are not supported

2. Non picture addresses are rendered as pictures, such as API addresses

3. For more language support, the reason why * is not written when registering the HoverProvider above is that all contents will be processed, including the contents in the DEBUG CONSOLE panel

vscode.languages.registerHoverProvider("*"

4. Allows you to configure the width or height of the picture

5. Allows you to customize which files to turn on picture preview

Wait, there's actually a lot to do. If you feel that the current functions have been met, you can directly use the ready-made plug-ins Image Hover Preview

This article is composed of one article multi posting platform ArtiPub Automatic publishing