Pluto.jl: Base.Display() like result modification

Created on 22 Sep 2020  路  3Comments  路  Source: fonsp/Pluto.jl

In Julia it is possible to modify the representation of a type with Base.Display.
A short example:

struct Rep
     val::Number
end
function Base.Display(a::Rep)
    println("Hi")
end
a = Rep(12)

would just print out Hi in the REPL instead of Rep(12).
I'd like to do similar custom types. What I have in mind is something like:

struct Rep
     val::Number
end
function Pluto.Display(a::Rep)
    md"Hi"
end

which then would give me a markdown string of Hi in the cell where I execute

a = Rep(12)

I know that Pluto tries to find the best representation for any type.
However, from reading the source code I don't understand how it works or even more important,
how I could provide this best representation. Also I couldn't find any other issues asking for
that particular feature.

Is there already a way to have custom representations of types?

Most helpful comment

That's doing the trick, thank you very much!
For any future soul that is stumbling over the topic:
If you want the standard representation of your type being a plot:

struct Test
     a::Array{Number, 1}
end

function Base.show(io::IO, ::MIME"text/html", x::Test)
    show(io, MIME"text/html"(), Plots.plot(x.a))
end

My biggest issue when building this was that I forgot to put the () after the MIME. So take care to write MIME"..."() instead of MIME"..." (The first being an object of type MIME and the second being the type MIME and of type DataType...)

All 3 comments

Show methods are in PlutoRunner.jl
which can be overridden.
fyi, Pluto uses a custom mimetype for displaying hierarchical data

image

馃洃 Don't overload MIME"application/vnd.pluto.tree+xml"!

You want to overload:

  • Base.show(io::IO, ::MIME"text/plain", x::MyType) to provide a custom plaintext display (sounds like your case)
  • Base.show(io::IO, ::MIME"text/html", x::MyType) to provide a custom HTML display

That's doing the trick, thank you very much!
For any future soul that is stumbling over the topic:
If you want the standard representation of your type being a plot:

struct Test
     a::Array{Number, 1}
end

function Base.show(io::IO, ::MIME"text/html", x::Test)
    show(io, MIME"text/html"(), Plots.plot(x.a))
end

My biggest issue when building this was that I forgot to put the () after the MIME. So take care to write MIME"..."() instead of MIME"..." (The first being an object of type MIME and the second being the type MIME and of type DataType...)

Was this page helpful?
0 / 5 - 0 ratings

Related issues

Roger-luo picture Roger-luo  路  7Comments

fonsp picture fonsp  路  5Comments

MikaelSlevinsky picture MikaelSlevinsky  路  6Comments

dpsanders picture dpsanders  路  6Comments

mossr picture mossr  路  6Comments