Skip to content

Commit

Permalink
Fix printing of variable names in IJuliaMode (#2423)
Browse files Browse the repository at this point in the history
* Fix printing of variable names in IJuliaMode

* Tweak the regex slightly
  • Loading branch information
odow authored Jan 13, 2021
1 parent e5dbccd commit 24d1316
Show file tree
Hide file tree
Showing 2 changed files with 27 additions and 5 deletions.
19 changes: 15 additions & 4 deletions src/print.jl
Original file line number Diff line number Diff line change
Expand Up @@ -321,12 +321,23 @@ function function_string(::Type{REPLMode}, v::AbstractVariableRef)
end
function function_string(::Type{IJuliaMode}, v::AbstractVariableRef)
var_name = name(v)
if !isempty(var_name)
# TODO: This is wrong if variable name constains extra "]"
return replace(replace(var_name, "[" => "_{", count = 1), "]" => "}")
else
if isempty(var_name)
return "noname"
end
# We need to escape latex math characters that appear in the name.
# However, it's probably impractical to catch everything, so let's just
# escape the common ones:
# Escape underscores to prevent them being treated as subscript markers.
var_name = replace(var_name, "_" => "\\_")
# Escape carets to prevent them being treated as superscript markers.
var_name = replace(var_name, "^" => "\\^")
# Convert any x[args] to x_{args} so that indices on x print as subscripts.
m = match(r"^(.*)\[(.+)\]$", var_name)
if m !== nothing
var_name = m[1] * "_{" * m[2] * "}"
end

return var_name
end

#------------------------------------------------------------------------
Expand Down
13 changes: 12 additions & 1 deletion test/print.jl
Original file line number Diff line number Diff line change
Expand Up @@ -326,7 +326,7 @@ function printing_test(ModelType::Type{<:JuMP.AbstractModel})
io_test(REPLMode, y[2], "bar[2]")
io_test(IJuliaMode, y[2], "bar_{2}")
io_test(REPLMode, z[:red], "color_123[red]")
io_test(IJuliaMode, z[:red], "color_123_{red}")
io_test(IJuliaMode, z[:red], "color\\_123_{red}")
io_test(REPLMode, v[2, 1], "i123123[1,2]")
io_test(IJuliaMode, v[2, 1], "i123123_{1,2}")
io_test(REPLMode, w[1, 3], "symm[1,3]")
Expand Down Expand Up @@ -788,3 +788,14 @@ end
printing_test(JuMPExtension.MyModel)
model_extension_printing_test(JuMPExtension.MyModel)
end

@testset "Print IJulia with math operators" begin
model = Model()
@variable(model, x_ab)
io_test(IJuliaMode, x_ab, "x\\_ab")
@variable(model, y[1:2], base_name = "y[:a]")
io_test(IJuliaMode, y[1], "y[:a]_{1}")
io_test(IJuliaMode, y[2], "y[:a]_{2}")
@variable(model, z, base_name = "z^1")
io_test(IJuliaMode, z, "z\\^1")
end

0 comments on commit 24d1316

Please sign in to comment.