1

I had an idea to develop a simple extension for vscode that will help me to display math functions written in latex when I hover over python's comment.

Simple example:

# $y = x^2$
y = x ** 2

Even though vscode.Hover supports markdown (example), unfortunately, it does not support latex (example). I saw that vscode.MarkdownString partially supports html so I decided to try markdown-it-katex and was able to render something but I have no idea how to add KaTeX stylesheet and now I am getting the following results, while the expected output looks like this.

Even though, I have zero experience in TS, the code seems fairly simple now. I hope someone knows how the functionality can be achieved without some complicated overhead:

import * as markdownIt from 'markdown-it';
const markdownItKatex = require('markdown-it-katex');
const md = markdownIt({ html: true }).use(markdownItKatex);


vscode.languages.registerHoverProvider("python", {
    provideHover(document, position, token) {
        var text = document.lineAt(position).text;

        // if it is a comment in python, return content, otherwise return null
        // use katex to render math equations
        if (text.startsWith('#')) {
            // remove the comment symbol
            text = text.slice(1);

            // use markdown-it-katex to format the content
            const html = md.render(text);

            const contents = new vscode.MarkdownString(html);
            contents.isTrusted = true;
            contents.supportHtml = true;

            return new vscode.Hover(contents);
        }

        return null;
    }

  • Maybe take a look at https://github.com/James-Yu/LaTeX-Workshop which has similar functionality (when you hover over a math formula in LaTeX, it renders it as a hover tip via KaTeX)? It should address the issues you're running into (CSS injection). – edemaine Jun 20 '23 at 14:26
  • @edemaine thank you for your comment, I decided to solve the task differently by generating svg image and displaying it in hover: https://marketplace.visualstudio.com/items?itemName=yermandy.emath – Andy Yermakov Jun 21 '23 at 16:59
  • Oh, neat! I assume that uses MathJax? – edemaine Jun 22 '23 at 18:50
  • 1
    I actually found something simpler, it is called [texsvg](https://github.com/remarkablemark/texsvg) – Andy Yermakov Jun 23 '23 at 22:16

0 Answers0