In Polyglot notebook, treat code output as markdown?

184 views Asked by At

Is it possible in Polyglot (.NET Interactive) notebook in VS Code for a code cell to create or display a markdown output?

let myMd = "## Title\nText"
myMd |> displayAsMarkdown

Someone seems to be able to do this with mermaid: Display Mermaid diagram from C# variable in Polyglot notebook Someone else uses a Python library to format programmatic markdown: https://data-dive.com/jupyterlab-markdown-cells-include-variables/#:~:text=Surprisingly%2C%20Jupyter%20Notebooks%20do%20not,easy%20to%20install%20and%20configure.

I'd like to use the full power of the Notebook markdown including LaTex mathematics. Since the capability to render markdown is there it seems perverse that it wouldn't be accessible. I can't find any examples or documentation.

The Kernel.Root.SendAsync(new SubmitCode("markdown", "My markdown text")) route doesn't seem to work.

2

There are 2 answers

2
Paul Whiting On

A hacky solution, inspired by: How can I mix LaTeX in with Markdown?

I use MarkdownSharp and MathJax to synthesize my desired behaviour:

#r "nuget: MarkdownSharp"
open Microsoft.DotNet.Interactive
open Microsoft.DotNet.Interactive.Commands
let jax =
    """
    <style TYPE="text/css">
    code.has-jax {font: inherit; font-size: 100%; background: inherit; border: inherit;}
    </style>
    <script type="text/x-mathjax-config">
    MathJax.Hub.Config({
        tex2jax: {
            inlineMath: [['$','$'], ['\\(','\\)']],
            skipTags: ['script', 'noscript', 'style', 'textarea', 'pre'] // removed 'code' entry
        }
    });
    MathJax.Hub.Queue(function() {
        var all = MathJax.Hub.getAllJax(), i;
        for(i = 0; i < all.length; i += 1) {
            all[i].SourceElement().parentNode.className += ' has-jax';
        }
    });
    </script>
    <script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/mathjax/2.7.4/MathJax.js?config=TeX-AMS_HTML-full"></script>
    """
let formula = @"$$\left( \sum_{k=1}^n a_k b_k \right)^2 \leq \left( \sum_{k=1}^n a_k^2 \right) \left( \sum_{k=1}^n b_k^2 \right)$$"
let text =
    $"## Agency fixed default rate\nAgencies have a fixed annual default probability of {100.0 * assumptions.agencyDefaultRate}%%, designed to capture unmodelled risk including fraud, operational risk, regulatory risk, and so forth.\n"
let html = MarkdownSharp.Markdown().Transform(text)
Kernel.Root.SendAsync(new SubmitCode(jax+html+formula, "html"))
|> Async.AwaitTask
|> Async.RunSynchronously
|> ignore
0
WReach On

One way is to use the DisplayAs extension method with the text/markdown MIME type:

let myMd = "## Title\n$f(x) = x^2$"
myMd.DisplayAs("text/markdown")

polyglot notebook screenshot showing markdown output