Skip to content

Commit 1424d90

Browse files
authored
Fix show with LaTeX coefficients (#259)
* Fix show with LaTeX coefficients * Fix format
1 parent b86a6f4 commit 1424d90

File tree

2 files changed

+29
-2
lines changed

2 files changed

+29
-2
lines changed

src/show.jl

Lines changed: 26 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -129,13 +129,38 @@ function print_coefficient(io::IO, mime::MIME"text/latex", coeff::AbstractFloat)
129129
end
130130
return print(io, s)
131131
end
132+
133+
function _trim_LaTeX(s::AbstractString)
134+
i = firstindex(s)
135+
j = lastindex(s)
136+
while true
137+
if i < j && isspace(s[i])
138+
i = nextind(s, i)
139+
elseif i < j && isspace(s[j])
140+
j = prevind(s, j)
141+
elseif i < j && s[i] == '$' && s[j] == '$'
142+
i = nextind(s, i)
143+
j = prevind(s, j)
144+
elseif i < j && (
145+
(s[i:i+1] == "\\(" && s[j-1:j] == "\\)") ||
146+
(s[i:i+1] == "\\[" && s[j-1:j] == "\\]")
147+
)
148+
i = nextind(s, i, 2)
149+
j = prevind(s, j, 2)
150+
else
151+
return s[i:j]
152+
end
153+
end
154+
end
155+
132156
# JuMP expressions supports LaTeX output so `showable` will return `true`
133157
# for them. It is important for anonymous variables to display properly as well:
134158
# https://github.com/jump-dev/SumOfSquares.jl/issues/256
159+
# Since they add `$$` around it, we need to trim it with `_trim_LaTeX`
135160
function print_coefficient(io::IO, mime, coeff)
136161
print(io, "(")
137162
if showable(mime, coeff)
138-
show(io, mime, coeff)
163+
print(io, _trim_LaTeX(sprint(show, mime, coeff)))
139164
else
140165
show(io, coeff)
141166
end

test/show.jl

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -2,7 +2,9 @@ struct CustomLaTeXPrint end
22

33
Base.:-(::CustomLaTeXPrint) = CustomLaTeXPrint()
44
Base.iszero(::CustomLaTeXPrint) = false
5-
Base.show(io::IO, ::MIME"text/latex", ::CustomLaTeXPrint) = print(io, "a_a")
5+
function Base.show(io::IO, ::MIME"text/latex", ::CustomLaTeXPrint)
6+
return print(io, " \$\$ \\[\\(a_a \\) \\]\t \$\$")
7+
end
68

79
@testset "Show" begin
810
Mod.@polyvar x y z

0 commit comments

Comments
 (0)