I want to modify a custom pretty printing function for a type defined by another package. However, I don’t want to override their printing function, I just want to post-process the string before it is printed.
In particular, I want to take their latex output, modify it somehow, then print it as a latex string again (in say IJulia).
Here’s what I’ve tried so far:
function Base.show(io::IO, ::MIME"text/latex", x::MyType)
ltx = repr("text/latex", x)
ltx = replace(ltx, "abc" => "def")
print(io, ltx)
end
This however leads to a StackOverflowError, as I believe repr
must call Base.show
somewhere, leading to an infinite loop. I’m not sure how else to get the output before it is printed.
Any idea on how I can do this?
I think you want invoke
, which you can use to call the old method, despite defining a new and more specialised one. Something like this:
function Base.show(io::IO, m::MIME"text/latex", x::MyType)
io = IOBuffer()
invoke(show, Tuple{IO, MIME"text/latex", Any}, io, m, x) # need the exact signature here
ltx = String(take!(io))
ltx = replace(ltx, "abc" => "def")
invoke
does look useful, but I don’t think it does exactly what I need here.
If I understand this function right, it is calling the show
function for latex for the generic Any
type. What I really need is the specific call for the type (in this case ::Vector{Equation}
), then do some extra changes before displaying the result.
In other words, I want to call the original version of the specialised show
function, before it was overloaded by my new function. Is it possible to do that in Julia?
I ended up fixing my problem in a much more straightforward way. Rather than getting the output of the previous method, I could just as easily call latexify
again in my new function, like so:
using Latexify
function Base.show(io::IO, m::MIME"text/latex", x::MyType)
ltx = latexify(x)
ltx = replace(ltx, "abc" => "def")
print(io, ltx)
end
Turns out the simplest solution is sometimes the best!
1 Like