Conditional use of VSCode plot pane in `Base.show`?

Hi, I have a type that can usually, but not always, be displayed nicely (through Latexify) in the VSCode plot pane. I can use conditionals/error handling in my Base.show(::IO, ::MIME"juliavscode/html", ::MyType) overload to fall back on MIME"text/plain" if it turns out that the neat display won’t work. So far, so good, and here is an MWE:

struct MWEType 
    toggle::Bool
end

function Base.show(io::IO, mime::MIME"juliavscode/html", x::MWEType)
  if x.toggle
      print(io, "<h1> Hello there! </h1>")
  else
      show(stdout, MIME("text/plain"), x)
  end
end

MWEType(true)    ## Displays nicely in the plot pane
MWEType(false)   ## Falls back on a safer display

However, even when I fall back on stdout, I still generate a new, empty “plot”. Is there a way to avoid this?

Yes, via showable:

struct Foo 
    html::Bool
end

Base.showable(::MIME"juliavscode/html", f::Foo) = f.html
Base.show(io::IO, ::MIME"juliavscode/html", f::Foo) = print(io, "<h1>pretty!</h1>")
Base.show(io::IO, ::MIME"text/plain", f::Foo) = print(io, "a bit plain, don't you think?")

Foo(false)
Foo(true)

or by throwing a MethodError to make the display system think your show method doesn’t exist:

struct Bar 
    html::Bool
end

function Base.show(io::IO, m::MIME"juliavscode/html", f::Bar)
    if f.html
        print(io, "<h1>pretty!</h1>")
    else
        throw(MethodError(show, (io, m, f)))
    end
end

Bar(false)
Bar(true)
2 Likes

Perfect, thank you very much! :tada:

To anyone coming after to see this: the call signature to MethodError should be MethodError(show, (io, m, f)).

Fixed above :slight_smile:
FWIW, the showable implementation is preferable unless it causes you to duplicate a bunch of work you’d ideally only do in show.

Indeed, I would certainly have preferred that method if it was easily done. In my case, however, the second version could be used plug-and-play whereas the first one would require refactoring and I would still need to rely on try/catch since I don’t have a robust way of telling whether the nicer approach will actually work.

1 Like