Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Implement latexescape #67

Open
wants to merge 2 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
31 changes: 30 additions & 1 deletion src/LaTeXStrings.jl
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@ in supporting environments like IJulia.
See in particular the `LaTeXString` type and the `L"..."` constructor macro.
"""
module LaTeXStrings
export LaTeXString, latexstring, @L_str
export LaTeXString, latexstring, @L_str, latexescape

# IJulia supports LaTeX output for any object with a text/latex
# writemime method, but these are annoying to type as string literals
Expand Down Expand Up @@ -133,4 +133,33 @@ Base.match(re::Regex, s::LaTeXString, idx::Integer, add_opts::UInt32=UInt32(0))
Base.findnext(re::Regex, s::LaTeXString, idx::Integer) = findnext(re, s.s, idx)
Base.eachmatch(re::Regex, s::LaTeXString; overlap = false) = eachmatch(re, s.s; overlap=overlap)

const LATEX_ESCAPE_SUB_TABLE = Pair{String,String}[
raw"\\" => raw"\textbackslash{}",
raw"&" => raw"\&",
raw"%" => raw"\%",
raw"$" => raw"\$",
raw"#" => raw"\#",
raw"_" => raw"\_",
raw"{" => raw"\{",
raw"}" => raw"\}",
raw"~" => raw"\textasciitilde{}",
raw"^" => raw"\^{}",
raw"<" => raw"\textless{}",
raw">" => raw"\textgreater{}",
]

@doc raw"""
latexscape(s::AbstractString)

This function escapes common text so it can be included directly into ``\TeX`` code[^so16259923].

## References

[^so16259923]:
Stack Overflow: ["How can I escape LaTeX special characters inside django templates?"](https://stackoverflow.com/questions/16259923)
"""
function latexescape(s::AbstractString)
return replace(s, LATEX_ESCAPE_SUB_TABLE...)
end

end # module
4 changes: 4 additions & 0 deletions test/runtests.jl
Original file line number Diff line number Diff line change
Expand Up @@ -84,6 +84,10 @@ end
@test tst1[OneTo(5)] == tst1[1:5]
end

@testset "escaping" begin
@test latexescape(raw"A\&%$#_{}~^<>z") == raw"A\textbackslash{}\&\%\$\#\_\{\}\textasciitilde{}\^{}\textless{}\textgreater{}z"
end

using Documenter
DocMeta.setdocmeta!(LaTeXStrings, :DocTestSetup, :(using LaTeXStrings); recursive=true)
doctest(LaTeXStrings; manual = false)