Skip to content

Commit

Permalink
Override default variable latexification with custom [latex = ...] field
Browse files Browse the repository at this point in the history
  • Loading branch information
hersle committed Dec 13, 2024
1 parent 74756eb commit f935c4a
Show file tree
Hide file tree
Showing 2 changed files with 24 additions and 11 deletions.
29 changes: 21 additions & 8 deletions src/latexify_recipes.jl
Original file line number Diff line number Diff line change
Expand Up @@ -52,8 +52,12 @@ recipe(n) = latexify_derivatives(cleanup_exprs(_toexpr(n)))
cdot --> false
fmt --> FancyNumberFormatter(5)
index --> :subscript
snakecase --> true
safescripts --> true

# Prevent Latexify.jl from interfering if variable has custom [latex = ...] field (it should escape its own underscores etc.)
custom = hasmetadata(unwrap(n), VariableLatex)
snakecase --> !custom
safescripts --> !custom
function_name --> false

return recipe(n)
end
Expand Down Expand Up @@ -191,13 +195,22 @@ function _toexpr(O)
return frac_expr
end
end
if issym(O)
sym = string(nameof(O))
sym = replace(sym, NAMESPACE_SEPARATOR => ".")
if length(sym) > 1
sym = string("\\mathtt{", sym, "}")
if issym(O)
name = string(nameof(O))

# If given, use custom [latex = ...] option for the variable name (does not affect subsystem names)
# Otherwise fall back to a sane default, where multi-letter variables are rendered with a fixed width font
name = replace(name, NAMESPACE_SEPARATOR => '.')
if hasmetadata(O, VariableLatex)
seppos = findlast('.', name)
sysname = isnothing(seppos) ? "" : "\\mathtt{$(name[begin:seppos])}" # always \mathtt system names (consistent with multi-letter vars)
varname = getmetadata(O, VariableLatex) # override
name = string(sysname, varname)
elseif length(name) > 1
name = "\\mathtt{$name}"
end
return Symbol(sym)

return Symbol(name)
end
!iscall(O) && return O

Expand Down
6 changes: 3 additions & 3 deletions src/variable.jl
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@ const IndexMap = Dict{Char,Char}(
abstract type AbstractVariableMetadata end
struct VariableDefaultValue <: AbstractVariableMetadata end
struct VariableSource <: AbstractVariableMetadata end
struct VariableLatex <: AbstractVariableMetadata end

function recurse_and_apply(f, x)
if symtype(x) <: AbstractArray
Expand Down Expand Up @@ -252,9 +253,8 @@ function construct_vars(macroname, v, type, call_args, val, prop, transform, isr
lhs, :($lhs = $rhs)
end

function option_to_metadata_type(::Val{opt}) where {opt}
throw(Base.Meta.ParseError("unknown property type $opt"))
end
option_to_metadata_type(::Val{:latex}) = VariableLatex
option_to_metadata_type(::Val{opt}) where {opt} = throw(Base.Meta.ParseError("unknown property type $opt"))

function setprops_expr(expr, props, macroname, varname)
expr = :($setmetadata($expr, $VariableSource, ($(Meta.quot(macroname)), $varname,)))
Expand Down

0 comments on commit f935c4a

Please sign in to comment.