What do you use to embed Julia code in LaTeX?

Occasionally I spend a fair amount of time getting LaTeX to do what I want, but it is still the best solution for preparing documents with math in a consistent and reproducible way, with minimum effort.

Nothing else even comes close. I have seen math edited with very pricey DTP programs that looked liked something the dog regurgitated.

And LaTeX is free. I find that miraculous.

11 Likes

It’s true that it’s currently the best solution, once you get it all working.

I ran @Keno’s tricky Julia snippet (Browser problems displaying maths Unicode characters - #24 by cormullion) through LaTeX and it was rendered accurately…

Like the view from the summit of a mountain, it looks good, but it was a struggle to get there… :joy_cat:

7 Likes

@Tamas_Papp I think @cormullion was being nice to people who use LaTeX and need to use it with the excellent JuliaMono package (which he developed for free) but struggle one way or another to make it work. That’s my case. In the house, we have five computers, all installed by me: all updated. The Minted.sty package works in all except on mine. I have been exchanging messages with Geoffrey Poore to overcome this issue, but we have had no success. Everything looks OK, but some mysterious problem subsists. In Stack and TEX forums, there are many questions raised about the issues in Minted and MiKTeX’s interaction (apparently, TeXLive users do not suffer from the same problem). Yes, LaTeX is excellent but not immune to some annoying problems.

@cormullion was just being nice, not disrespectful. And he/she did that with an excellent sense of humor.

1 Like

No worries! I get rewarded with that most priceless of currencies, Github stars… :joy:

8 Likes

I must thank both @cormullion and @lmiq for promptly making available two different approaches to easily embed Julia Unicode characters from the JuliaMono package into LaTeX documents.

I was capable of replicating both examples. My computer (or my Tex installation) continues to boycott the use of minted.sty, but the example was easily replicated in any other single computer in the house. As far as the example using jlcode.sty is concerned, I managed to replicate it using the inside “code environment”, but my Tex installation raised errors when using the “codefile” and “codelink” variations.

Anyway, thanks a lot.

Another option you could try is the julia-tufte-beamer template I put together for presentations: GitHub - mossr/julia-tufte-beamer: Tufte-style beamer template with Julia integration

And the julia-mono-listings package for typesetting Julia code in LaTeX documents: GitHub - mossr/julia-mono-listings: LaTeX listings style for Julia and Unicode support for the JuliaMono font

14 Likes

These are excellent, thanks for sharing!

According to the 2020 Julia survey this is only likely to be directly helpful to 12% of you, but if nothing else as a demonstration of what’s possible I’d like to share what I recently set up for Julia code in my (LaTeX) PDFs.

I was unhappy with the visual quality and slowness of pygments/minted, and so I’ve developed my own solution. I’s currently in early stages I’d like to upstream it within the next few months.

The good news

I find the output great (this can even make use of Tree-Sitter as a highlighting backend, though I haven’t here), the syntax-highlighting ~8x faster than minted/pygments, and PDFs can be generated without --shell-escape

The bad news

(for 88% of you) When I said “upstream” I was talking about Org, in Emacs :stuck_out_tongue:

More info

For those of you who wish to hear more, this is built on a package I made to leverage Emacs major-modes’ font-lock rules to produce syntax highlighting across a variety of export formats (currently only implemented for LaTeX, because that’s the biggest hole in the current offerings as far as I’m concerned).

Then I have configuration which hooks this into Org, and also to switch the compiler to LuaLaTeX and use JuliaMono when Julia code is detected in the document.

With a lot of copy-paste this should be work OOTB for Emacsers, but once I have the conditional preamble generation and engrave-faces support upstreamed it should be as simple as:

(setq org-latex-listings 'engraved)

Links

3 Likes

@Robert_Moss great stuff. Thanks for sharing.

The julia-mono-listings package is easy to use, easy to customize, compiles fast, and has an elegant appearance. As far as the julia-tufte-beamer template is concerned, I think Edward Tufte will like it. The slides’ style looks superb, and all the beamer functionalities available are indeed quite striking for a LaTeX user.

I stumbled across this recently and it looks fantastic. Will definitely be using it for my next presentation.

Folks, for some reason, my code do not compile properly when it has bold letters, e.g.,

\documentclass{article}
\usepackage{minted}
\usepackage{fontspec}
\usepackage{polyglossia}
\usepackage{unicode-math}

\usepackage{xunicode}
\setmonofont{FreeMono} %switched to FreeMono

\begin{document}
\begin{minted}[breaklines,escapeinside=||,mathescape=true, linenos, numbersep=3pt, gobble=2, frame=lines, fontsize=\small, framesep=2mm]{julia}
    using Convex, SCS, Plots, LaTeXStrings

    N = 30 # N in the set {0, 1, ..., N}
    n = 3 # order of the linear dynamical system
    x_des = [7, 2, -6] # constraint -> 𝐱(N) == x_des
    # model parameters
    𝐀 = [-1 .4 .8; 1 0 0; 0 1 0]
    𝐛 = [1, 0, 0.3]

    𝐗 = Variable(n, N+1) # [𝐱(0) 𝐱(1) ... 𝐱(N)]
    𝐮 = Variable(1, N) # [u(0) u(1) ... u(N-1)]
    f0 = sum(max(abs(𝐮), 2abs(𝐮)-1)) # objective function
    constraints = [
        𝐗[:,2:N+1] == 𝐀*𝐗[:,1:N]+𝐛*𝐮, # recursive equation
        𝐗[:,1] == zeros(n), # initial condition
        𝐗[:,N+1] == x_des, # final condition
    ]
    problem = minimize(f0, constraints)
    solve!(problem, SCS.Optimizer; silent_solver = true)

    fig = plot(vec(𝐮.value), xlabel=L"k", title=L"u(k)", line=:steppre)
    savefig(fig, "figs/4.17.png")
\end{minted}
\end{document}

enter image description here

I am suppose that it is caused by the font (I am not an expert on LaTeX). I tried to use Nerd Fonts (MesloLGMDZ Nerd Font) in order to get the right font, but fontspec does not allow patched fonts…

Which font should I use to get a beautiful Julia’s code with bold letter?

This site - https://mono-math.netlify.app/ - will help you browse through fonts that support various maths glyphs. I expect neither FreeMono nor “MesloLGMDZ Nerd Font” has glyphs in the U+1D400…U+1D7FF range (where your 𝐀*𝐗 glyphs live).

Earlier posts in this thread mention some useful resources.

3 Likes

I downloaded JuliaMono, for instance, it does not work:

My code

\documentclass{article}

\usepackage{minted}
\usepackage{fontspec}
\setmonofont{JuliaMono} %switched to FreeMono

\begin{document}
test

\begin{minted}[breaklines,escapeinside=||,mathescape=true, linenos, numbersep=3pt, gobble=2, frame=lines, fontsize=\small, fontfamily=stm, framesep=2mm]{julia}
    using Convex, SCS, Plots, LaTeXStrings

    N = 30 # N in the set {0, 1, ..., N}
    n = 3 # order of the linear dynamical system
    x_des = [7, 2, -6] # constraint -> 𝐱(N) == x_des
    # model parameters
    𝐀 = [-1 .4 .8; 1 0 0; 0 1 0]
    𝐛 = [1, 0, 0.3]

    𝐗 = Variable(n, N+1) # [𝐱(0) 𝐱(1) ... 𝐱(N)]
    𝐮 = Variable(1, N) # [u(0) u(1) ... u(N-1)]
    f0 = sum(max(abs(𝐮), 2abs(𝐮)-1)) # objective function
    constraints = [
        𝐗[:,2:N+1] == 𝐀*𝐗[:,1:N]+𝐛*𝐮, # recursive equation
        𝐗[:,1] == zeros(n), # initial condition
        𝐗[:,N+1] == x_des, # final condition
    ]
    problem = minimize(f0, constraints)
    solve!(problem, SCS.Optimizer; silent_solver = true)

    fig = plot(vec(𝐮.value), xlabel=L"k", title=L"u(k)", line=:steppre)
    savefig(fig, "figs/4.17.png")
\end{minted}

\end{document}

prompts to

❯ lualatex --shell-escape main.tex
This is LuaHBTeX, Version 1.14.0 (TeX Live 2022/dev/Debian) 
 system commands enabled.
(./main.tex
LaTeX2e <2021-11-15> patch level 1
 L3 programming layer <2022-01-21>
(/usr/share/texlive/texmf-dist/tex/latex/base/article.cls
Document Class: article 2021/10/04 v1.4n Standard LaTeX document class
(/usr/share/texlive/texmf-dist/tex/latex/base/size10.clo))
(/usr/share/texlive/texmf-dist/tex/latex/minted/minted.sty
(/usr/share/texlive/texmf-dist/tex/latex/graphics/keyval.sty)
(/usr/share/texlive/texmf-dist/tex/latex/kvoptions/kvoptions.sty
(/usr/share/texlive/texmf-dist/tex/generic/ltxcmds/ltxcmds.sty)
(/usr/share/texlive/texmf-dist/tex/generic/kvsetkeys/kvsetkeys.sty))
(/usr/share/texlive/texmf-dist/tex/latex/fvextra/fvextra.sty
(/usr/share/texlive/texmf-dist/tex/latex/base/ifthen.sty)
(/usr/share/texlive/texmf-dist/tex/latex/etoolbox/etoolbox.sty)
(/usr/share/texlive/texmf-dist/tex/latex/fancyvrb/fancyvrb.sty)
(/usr/share/texlive/texmf-dist/tex/latex/upquote/upquote.sty
(/usr/share/texlive/texmf-dist/tex/latex/base/textcomp.sty))
(/usr/share/texlive/texmf-dist/tex/latex/lineno/lineno.sty))
(/usr/share/texlive/texmf-dist/tex/latex/tools/calc.sty)
(/usr/share/texlive/texmf-dist/tex/latex/tools/shellesc.sty)
(/usr/share/texlive/texmf-dist/tex/latex/ifplatform/ifplatform.sty
(/usr/share/texlive/texmf-dist/tex/generic/pdftexcmds/pdftexcmds.sty
(/usr/share/texlive/texmf-dist/tex/generic/infwarerr/infwarerr.sty)
(/usr/share/texlive/texmf-dist/tex/generic/iftex/iftex.sty))
(/usr/share/texlive/texmf-dist/tex/generic/catchfile/catchfile.sty
(/usr/share/texlive/texmf-dist/tex/generic/etexcmds/etexcmds.sty))
(/usr/share/texlive/texmf-dist/tex/generic/iftex/ifluatex.sty) (./main.w18))
(/usr/share/texlive/texmf-dist/tex/generic/xstring/xstring.sty
(/usr/share/texlive/texmf-dist/tex/generic/xstring/xstring.tex))
(/usr/share/texlive/texmf-dist/tex/latex/framed/framed.sty)
(/usr/share/texlive/texmf-dist/tex/latex/float/float.sty))
(/usr/share/texlive/texmf-dist/tex/latex/fontspec/fontspec.sty
(/usr/share/texlive/texmf-dist/tex/latex/l3packages/xparse/xparse.sty
(/usr/share/texlive/texmf-dist/tex/latex/l3kernel/expl3.sty
(/usr/share/texlive/texmf-dist/tex/latex/l3backend/l3backend-luatex.def)))
(/usr/share/texlive/texmf-dist/tex/latex/fontspec/fontspec-luatex.sty
(/usr/share/texlive/texmf-dist/tex/latex/base/fontenc.sty)
(/usr/share/texlive/texmf-dist/tex/latex/fontspec/fontspec.cfg)))
(/usr/share/texlive/texmf-dist/tex/latex/xcolor/xcolor.sty
(/usr/share/texlive/texmf-dist/tex/latex/graphics-cfg/color.cfg)
(/usr/share/texlive/texmf-dist/tex/latex/graphics-def/luatex.def))/home/tapyu/.local/bin/pygmentize
 (./main.aux)
(/usr/share/texlive/texmf-dist/tex/latex/base/ts1cmr.fd)
(/usr/share/texlive/texmf-dist/tex/context/base/mkii/supp-pdf.mkii
[Loading MPS to PDF converter (version 2006.09.02).]
) (./_minted-main/default.pygstyle)
(./_minted-main/B5ABD6D09156175CB66A1CF9F2C69EB82AE44091634ECC1F29D496B7DD014B1
8.pygtex

LaTeX Font Warning: Font shape `TU/stm/m/n' undefined
(Font)              using `TU/lmr/m/n' instead on input line 1.


LaTeX Font Warning: Font shape `TU/stm/b/n' undefined
(Font)              using `TU/stm/m/n' instead on input line 2.


LaTeX Font Warning: Font shape `TU/stm/m/it' undefined
(Font)              using `TU/stm/m/n' instead on input line 4.

) [1{/var/lib/texmf/fonts/map/pdftex/updmap/pdftex.map}
Missing character: There is no 𝐱 (U+1D431) in font [lmroman9-regular]:+tlig;
!
Missing character: There is no 𝐀 (U+1D400) in font [lmroman9-regular]:+tlig;
!
Missing character: There is no 𝐛 (U+1D41B) in font [lmroman9-regular]:+tlig;
!
Missing character: There is no 𝐗 (U+1D417) in font [lmroman9-regular]:+tlig;
!
Missing character: There is no 𝐱 (U+1D431) in font [lmroman9-regular]:+tlig;
!
Missing character: There is no 𝐱 (U+1D431) in font [lmroman9-regular]:+tlig;
!
Missing character: There is no 𝐱 (U+1D431) in font [lmroman9-regular]:+tlig;
!
Missing character: There is no 𝐮 (U+1D42E) in font [lmroman9-regular]:+tlig;
!
Missing character: There is no 𝐮 (U+1D42E) in font [lmroman9-regular]:+tlig;
!
Missing character: There is no 𝐮 (U+1D42E) in font [lmroman9-regular]:+tlig;
!
Missing character: There is no 𝐗 (U+1D417) in font [lmroman9-regular]:+tlig;
!
Missing character: There is no 𝐀 (U+1D400) in font [lmroman9-regular]:+tlig;
!
Missing character: There is no 𝐗 (U+1D417) in font [lmroman9-regular]:+tlig;
!
Missing character: There is no 𝐛 (U+1D41B) in font [lmroman9-regular]:+tlig;
!
Missing character: There is no 𝐮 (U+1D42E) in font [lmroman9-regular]:+tlig;
!
Missing character: There is no 𝐗 (U+1D417) in font [lmroman9-regular]:+tlig;
!
Missing character: There is no 𝐗 (U+1D417) in font [lmroman9-regular]:+tlig;
!
Missing character: There is no 𝐮 (U+1D42E) in font [lmroman9-regular]:+tlig;
!
] (./main.aux)

LaTeX Font Warning: Some font shapes were not available, defaults substituted.

)
 416 words of node memory still in use:
   3 hlist, 1 vlist, 1 rule, 2 glue, 3 kern, 1 glyph, 4 attribute, 50 glue_spec
, 4 attribute_list, 1 write nodes
   avail lists: 1:1,2:1405,3:96,4:686,5:228,6:46,7:2026,9:342,11:84
</usr/share/texmf/fonts/opentype/public/lm/lmroman9-regular.otf></usr/share/tex
mf/fonts/opentype/public/lm/lmroman5-regular.otf></usr/share/texmf/fonts/openty
pe/public/lm/lmroman10-regular.otf>
Output written on main.pdf (1 page, 15399 bytes).
Transcript written on main.log.

Well, thanks to a wise man on stack exchange, I could find a font what fits on my purposes :slight_smile:

\documentclass{article}

\usepackage{fontspec}
\usepackage{unicode-math}
\newfontfamily\stm{StixTwoMath}[NFSSFamily=stm]
\usepackage{minted}

\begin{document}
\begin{minted}[breaklines,escapeinside=||,mathescape=true, linenos, numbersep=3pt, gobble=2, frame=lines, fontsize=\small, fontfamily=stm, framesep=2mm]{julia}
    using Convex, SCS, Plots, LaTeXStrings

    N = 30 # N in the set {0, 1, ..., N}
    n = 3 # order of the linear dynamical system
    x_des = [7, 2, -6] # constraint -> 𝐱(N) == x_des
    # model parameters
    𝐀 = [-1 .4 .8; 1 0 0; 0 1 0]
    𝐛 = [1, 0, 0.3]

    𝐗 = Variable(n, N+1) # [𝐱(0) 𝐱(1) ... 𝐱(N)]
    𝐮 = Variable(1, N) # [u(0) u(1) ... u(N-1)]
    f0 = sum(max(abs(𝐮), 2abs(𝐮)-1)) # objective function
    constraints = [
        𝐗[:,2:N+1] == 𝐀*𝐗[:,1:N]+𝐛*𝐮, # recursive equation
        𝐗[:,1] == zeros(n), # initial condition
        𝐗[:,N+1] == x_des, # final condition
    ]
    problem = minimize(f0, constraints)
    solve!(problem, SCS.Optimizer; silent_solver = true)

    fig = plot(vec(𝐮.value), xlabel=L"k", title=L"u(k)", line=:steppre)
    savefig(fig, "figs/4.17.png")
\end{minted}
\end{document}

Neat!

1 Like

I’m glad you got it working.

After my previous encounters with \LaTeX I wouldn’t have expected this to work anyway:

\setmonofont{JuliaMono} 

That’s too simple! :rofl: Yes, it ought to be as simple as that to define fonts, but…:man_shrugging:t2:
I would expect to have to define the font in advance:

\documentclass{article}
\usepackage{fontspec}
\usepackage{unicode-math}
\usepackage[utf8]{inputenc}
\usepackage{minted}

\setmonofont{JuliaMono-Regular.ttf}[
    Path = /Users/me/Library/Fonts/,
    Contextuals = Alternate,
    Scale = MatchLowercase,
	BoldFont = JuliaMono-Bold.ttf,
	%Numbers = OldStyle
]

And now minted will just find and use the monofont:

\begin{minted}[breaklines,escapeinside=||,mathescape=true, linenos, numbersep=3pt, gobble=2, frame=lines, framesep=2mm]{julia}
...

12 Likes

That is sick! So can I define any font from your reference in the way?

I browsed through the fontspec manual (https://mirror.ox.ac.uk/sites/ctan.org/macros/unicodetex/latex/fontspec/fontspec.pdf) and there are many things you can do, if you find the right magic incantation. :slight_smile:

2 Likes