What do you use to embed Julia code in LaTeX?

I wonder if anyone here has interesting tips or tricks for embedding Julia code in LaTeX, e.g. fancy color schemes, running code inline for presentations, automatic display of figures with captions, etc.

4 Likes

For julia in latex I use minted.
To run julia in presentations I use the “export to reveal.js slides” option in Jupyter

Here is a short wiki I created for my coworkers to include julia in latex

Minted

It is possible to include julia code using the package minted https://github.com/gpoore/minted

Prerequisites

pygmentize is required, if it is not installed, try running sudo pip install pygments

Get latest version of minted.sty from the github repo above. Put it in you texlive package folder or in the current working directory. Minted has other prerequisites, but those should be installed already.

A small example

  • \begin{minted}[breaklines,escapeinside=||,mathescape=true, linenos, numbersep=3pt, gobble=2, frame=lines, fontsize=\small, framesep=2mm]{julia}
    • Your awesome julia code here\end{minted}

minted.tex minted.pdf

Inclusion of unicode characters

With julia, one has the option of including most unicode characters in the code. For a copy-paste-kind of strategy to work, I have found the following two packages useful

\usepackage[mathletters]{ucs} \usepackage[utf8x]{inputenc}

With these packages, unicode characters in the input are handled quite well. At least if one builds with latexmk and pdflatex.

With luatex, use the following instead \usepackage[T1]{fontenc} \usepackage{unicode-math}

See https://tex.stackexchange.com/questions/251446/problem-with-math-symbols-unicode-math for info regarding setting a math font. The following selects the font that is default in Atom

\usepackage{fontspec}\setmonofont{DejaVu Sans Mono}[Scale=0.8]

Note, there might be some conflicts between unicode-math and the department fonts. If you get errors, try removing all other font choices, such as schoolbook, newtxtext, newtxmath,inconsolata,fourier, and see if the erros go away.

Issues

Beamer

Frames must be declared fragile for minted to work

\begin{frame}[fragile]

Other issues

Minted has issues if the build output is stored in a subdirectory and not in the working directory, use \usepackage[outputdir=build]{minted}

If pygments is installed but pygmentize can not be found, reinstall pygments .

25 Likes

I also created a minted style to resemble atomone syntax highlighting in atom

# -*- coding: utf-8 -*-
"""
Command to clear build directory, copy this file to the correct folder and then build a test document
rm /tmp/test.pdf; rm -rf /tmp/build/*; sudo cp ~/atomone.py /usr/lib/python3.6/site-packages/pygments/styles/.;lualatex --shell-escape --output-directory=build test.tex; okular build/test.pdf
"""

from pygments.style import Style
from pygments.token import Keyword, Name, Comment, String, Error, \
     Number, Operator, Generic, Whitespace


class AtomoneStyle(Style):
    """
    Bagge's style
    """

    background_color = '#f0f3f3'

    styles = {
        Whitespace:         '#bbbbbb',
        Comment:            'italic #A2A2A2',
        Comment.Preproc:    'noitalic #A2A2A2',
        Comment.Special:    'bold',

        Keyword:            'bold #AD00AC', # function, for, if
        Keyword.Pseudo:     'nobold',
        Keyword.Type:       '#008491',

        Operator:           '#555555',
        Operator.Word:      'bold #FF0000',# Does not seem to be used

        Name.Builtin:       '#008491', # Both these should be set to same
        Name.Function:      '#008491', # Both these should be set to same
        Name.Class:         'bold #000000',
        Name.Namespace:     'bold #FF0000',# Does not seem to be used
        Name.Exception:     'bold #CC0000',
        Name.Variable:      '#000000',
        Name.Constant:      '#000000',
        Name.Label:         '#FF0000',
        Name.Entity:        'bold #999999',
        Name.Attribute:     '#330000',
        Name.Tag:           'bold #FF0000',
        Name.Decorator:     '#9999FF',

        String:             '#97C417', # This is used for strings
        String.Doc:         'italic',
        String.Interpol:    '#AA0000', # Used for itnerpolations
        String.Escape:      'bold #CC3300',
        String.Regex:       '#33AAAA',
        String.Symbol:      '#FFCC33',
        String.Other:       '#CC3300',

        Number:             '#FF6600',

        Generic.Heading:    'bold #1A3300',
        Generic.Subheading: 'bold #003300',
        Generic.Deleted:    'border:#CC0000 bg:#FFCCCC',
        Generic.Inserted:   'border:#00CC00 bg:#CCFFCC',
        Generic.Error:      '#D60000',
        Generic.Emph:       'italic',
        Generic.Strong:     'bold',
        Generic.Prompt:     'bold #078600',
        Generic.Output:     '#787878',
        Generic.Traceback:  '#787878',

        Error:              'bg:#FFAAAA #AA0000'
    }
5 Likes

Very cool! Thank your for response. I will play around with minted some more and try your syntax highlighting.

Also see

3 Likes

@baggepinnen in your atomone style, what would be the way to make = and function names at call site differently colored from black?

Edit: that’s probably a language support issue?

1 Like

I have honestly no idea, it was very much a trial and error endeavor for me. I know I managed to install another julia syntax ruleset that works better, I’ll look around and see if I can remember where I got that from.

You need to find a new lexer
ref: http://pygments.org/docs/lexers/#lexers-for-the-julia-language
This is the one I use
https://github.com/sisl/pygments-julia
After that, use julia1 as language for the minted environment

5 Likes

Awesome, works like a charm! Thank you.

1 Like

You can also use jlcon1 as language for code copy-pasted from the REPL, to make output render nicely etc.

4 Likes

Pygments version 2.6.1 calls this language jlcon .

So does older versions, but with the custom lexer I linked in the post above, you need to append the 1 on the end to make user of the new lexer.

Reference

1 Like

I’m having good luck with this

8 Likes

I too use the jlcode package, and I have added some newcommands. Works like this:

\begin{code}
using DelimitedFiles
data = readdlm("file.dat")
x = data[:,1]
y = data[:,2]
\end{code}

which displays something like:

image

or

\codelink{./julia/kineticmodel.jl}

to display:

where “[Clique aqui para baixar o código]” means “[Click here to download the code]”.

Examples files are available at: https://github.com/m3g/jlcode_example

12 Likes

Nice work! Thanks @lmiq

If I want to use \begin{code} … without the colors (print book where colors are expensive) can I just delete

keywordstyle=\color{blue},
commentstyle=\color{gray},
identifierstyle=\color[RGB]{0,102,0}\textbf,

or do I need to changed the colors? Right now I use

\usepackage[nocolors]{jlcode}

Would that do the job?

You have to both add the [nocolors] option and comment those lines to get a completely grayscale output.

I have added a minimal working example (with some fixes to the code above), here:

2 Likes

You sir, just saved me some trouble over the next six months. Thanks again.

2 Likes

All the merits go to the wg030 github user, what I provide there is just a very simple example of what is in the user manual.

Wonderful stuff. I checked in the jlcode.sty file if there was an easy way to increase the size of the fonts. In some circumstances, we may need larger fonts for slides. But I did not figure out how to do it. Do you have a clue? Help would be very appreciated.

Not really, I tried I few things but I can only change the size with proper results if changing the size of the fonts of the complete document in \documentclass[12pt]{article}, for example.