I have the following code:
using Parameters
import Base.show
const BOLD = "\e[1m"
const RED = "\033[31;1m"
const GREEN = "\033[32;1m"
const NORMAL = "\e[0m"
@with_kw mutable struct ChargerResult
search_strings = String["No buffer space", "CAN1 Error"]
frequency = Int64[0, 0]
end
Base.show(io::IO, res::ChargerResult) = begin
println("\n\n", BOLD, "Charger log(s):\n", NORMAL)
for i in 1:length(res.frequency)
if res.frequency[i] == 0
println(io, GREEN, "Message: \"$(res.search_strings[i])\" not found!", NORMAL)
else
println(io, RED, "Message: \"$(res.search_strings[i])\" found $(res.frequency[i]) times!", NORMAL)
end
end
end
res = ChargerResult()
This allows me to print a struct of type ChargerResult with colors on the command line.
Now I also want to have a similar html representation of this struct.
How can I achieve that?
Can I write different show methods for console and for html representation?
You can pass a MIME
type as the second argument to show
. By default it’s text/plain
i.e. plaintext, so your method above applies to plaintext console output. You can write a method for the text/html
MIME type separately, like:
Base.show(io::IO, ::MIME"text/html", res::ChargerResult) = begin
println("<br> <strong>Charger log(s):</strong> <br>", NORMAL)
for i in 1:length(res.frequency)
if res.frequency[i] == 0
println(io, "<span style=\"color: #270\">Message: \"$(res.search_strings[i])\" not found!</span>")
else
println(io, "<span style=\"color: #D8000C\">Message: \"$(res.search_strings[i])\" found $(res.frequency[i]) times!</span>")
end
end
end
(Untested, and sort of a direct translation of the commandline output version - you might want fancier/more idiomatic HTML in the actual code.)
Separate from your question about HTML output, which was answered above (and is covered in the manual section on pretty-printing), is there a reason you’re not using printstyled(io, s, bold=true)
here?
Even if you do need to print formatting codes directly for some reason in your show
, you should first check get(io, :color, false)
to see whether the io
stream supports the ANSI formatting escapes. The printstyled
function will do this for you.
1 Like
Thank you, I did not know the printstyled function…
Thank you! But how can I print the html version to a file or to a string after adding the new show method?
Call it? show(io, "text/html", mystruct)
The difference between print and show is still not clear to me… Does print also calls show in the end?
By default, yes, print(io, x)
calls show(io, x)
, the 2-argument show
. However, there are some types for which it is different, e.g. for strings:
julia> show("foo\nbar")
"foo\nbar"
julia> print("foo\nbar")
foo
bar
This is explained in the documentation for Base.print
.
There’s also this 2020 JuliaCon talk:
An abstract of the talk, with a link to the slides used, is at:
2 Likes