1

I need to configure the minted code highlighting in LaTex.

This is what I want to get: enter image description here

Until now, this is what I get: enter image description here

What is remaining is the "import" and "as" keywords to be in bold and change the color and font of the comments and instructions. Also the '\t' to be in bold.

Here is the LaTeX script the reproduce my attempt.

\documentclass{article}
\usepackage[utf8]{inputenc}
\usepackage[english]{babel}

\usepackage{minted}
\usemintedstyle{manni}%{vs}%{pastie}%{autumn}%{emacs}%{tango}%{rrt}%{manni}
\usepackage[a4paper,margin=1in,footskip=0.40in]{geometry}
\usepackage{url}
\begin{document}


\begin{minted}{python}
    import matplotlib
    import matplotlib.pyplot as plt
    import numpy as np
    import pandas as pd
    import sklearn
    # Load the data
    oecd_bli = pd.read_csv("oecd_bli_2015.csv", thousands=',')
    gdp_per_capita = pd.read_csv("gdp_per_capita.csv",thousands=',',delimiter='\t',
     encoding='latin1', na_values="n/a")

\end{minted}
    
\end{document}
2
  • Just curious, why do you want the formatting to be exactly the same as the example in the first screenshot?
    – Marijn
    Feb 19, 2021 at 15:07
  • @Marjin: I just find it better to write my reports.
    – maths soso
    Feb 19, 2021 at 15:50

1 Answer 1

3

Customizing the colors and other font attributes used in minted styles can be done by writing a style definition file (or editing an existing style). This process is not really transferable, you need to place the style file directly into the directory where Pygments (the formatting engine used by minted) is installed. This directory is different for each Python version (3.6, 3.7, 3.8 etc) and will change when you update Python. If you want to compile your LaTeX document on a different system or make the LaTeX source available for other people then you/they need to install the style file as well (and have administrator/sudo privileges for doing so). This also means that you cannot use a cloud based compiler (Overleaf, VerbTeX etc.) because it is not allowed to change system directories in those systems - so it only works if you have a local installation.

Another customization that is much easier is to set the font used by minted. This is the easiest with XeLaTeX or LuaLaTeX where you can set the monospaced font (i.e., the font used for minted, and also for \texttt, \verb etc) with the fontspec package. For pdfLaTeX there are various packages to set the document font (or sometimes only the mono font) but there the choices are much more limited. The choice of font is important because not all monospaced fonts support boldface, for example the default font for minted does not have bold so the normal thickness will be displayed even if the style file specifies bold.

The style files are located in a folder called pygments/styles, and are called [stylename].py, for example manni.py. These are Python files that use Python syntax to specify the style. If you don't know the exact directory where Pygments is installed then you can do a system-wide search for manni.py for example to find the correct location.

Within a style file there is a class [Stylename]Style, so the name of the style (which is the same as the filename) with a capital letter followed by Style also with a capital letter. For manni.py the class is called ManniStyle. For a custom version of this class you can for example create a file called custommanni.py with a class called CustommanniStyle.

Within the class a list is specified with the color and font properties (bold, italics, underline, boxed etc.) for each category of tokens in the source code that is being highlighted. An overview of the categories is provided at https://pygments.org/docs/tokens/ if you are interested in making further changes.

Note that minted output is cached into a directory called _minted-[yourtexfile]. If you compile your LaTeX file, change the style file, and then compile again, then the cached version is used without taking the style changes into account. So to process further changes to the style you need to remove this directory each time after a style change before running LaTeX again.

The following style file is based on manni.py with two colors changed: the comment color and the color for variables/function names. The bold settings were already present in this style, so when used with a font that supports mono bold no changes are needed to the style file for getting bold in the output.

custommanni.py

# -*- coding: utf-8 -*-
"""
    pygments.styles.custommanni
    ~~~~~~~~~~~~~~~~~~~~~

    A colorful style, inspired by the terminal highlighting style.

    This is a port of the style used in the `php port`_ of pygments
    by Manni. The style is called 'default' there.

    The current file contains adaptations to the manni style.

    :copyright: Copyright 2006-2021 by the Pygments team, see AUTHORS.
    :license: BSD, see LICENSE for details.
"""

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


class CustommanniStyle(Style):
    """
    A colorful style, inspired by the terminal highlighting style.
    """

    background_color = '#f0f3f3'

    styles = {
        Whitespace:         '#bbbbbb',
        Comment:            'italic #003333', # changed color
        Comment.Preproc:    'noitalic #009999',
        Comment.Special:    'bold',

        Keyword:            'bold #006699',
        Keyword.Pseudo:     'nobold',
        Keyword.Type:       '#007788',

        Operator:           '#555555',
        Operator.Word:      'bold #000000',

        Name:               '#060F8C',   # added: blue variables/functions
        Name.Builtin:       '#336666',
        Name.Function:      '#CC00FF',
        Name.Class:         'bold #00AA88',
        Name.Namespace:     'bold #00CCFF',
        Name.Exception:     'bold #CC0000',
        Name.Variable:      '#003333',
        Name.Constant:      '#336600',
        Name.Label:         '#9999FF',
        Name.Entity:        'bold #999999',
        Name.Attribute:     '#330099',
        Name.Tag:           'bold #330099',
        Name.Decorator:     '#9999FF',

        String:             '#CC3300',
        String.Doc:         'italic',
        String.Interpol:    '#AA0000',
        String.Escape:      'bold #CC3300',
        String.Regex:       '#33AAAA',
        String.Symbol:      '#FFCC33',
        String.Other:       '#CC3300',

        Number:             '#FF6600',

        Generic.Heading:    'bold #003300',
        Generic.Subheading: 'bold #003300',
        Generic.Deleted:    'border:#CC0000 bg:#FFCCCC',
        Generic.Inserted:   'border:#00CC00 bg:#CCFFCC',
        Generic.Error:      '#FF0000',
        Generic.Emph:       'italic',
        Generic.Strong:     'bold',
        Generic.Prompt:     'bold #000099',
        Generic.Output:     '#AAAAAA',
        Generic.Traceback:  '#99CC66',

        Error:              'bg:#FFAAAA #AA0000'
    }

The following LaTeX file uses this style and sets the monospaced font to Ubuntu Mono, which supports bold (and looks like the example screenshot). You can change the font to anything else of course. Compile with XeLaTeX or LuaLaTeX.

\documentclass{article}
\usepackage{fontspec}
\setmonofont{Ubuntu Mono}
\usepackage{minted}
\usemintedstyle{custommanni}

\begin{document}
\begin{minted}{python}
    import matplotlib
    import matplotlib.pyplot as plt
    import numpy as np
    import pandas as pd
    import sklearn
    
    # Load the data
    oecd_bli = pd.read_csv("oecd_bli_2015.csv", thousands=',')
    gdp_per_capita = pd.read_csv("gdp_per_capita.csv",thousands=',',delimiter='\t',
     encoding='latin1', na_values="n/a")

\end{minted}
\end{document}

Result:

enter image description here

For setting a suitable font for pdfLaTeX see for example Setting font for a minted environment in a beamer frame.

6
  • Thank you that was of great help. Could you tell me what software are you using for LaTeX compilation? I'm using Overleaf and I don't know how python is involved and where to put the python files since I'm using a cloud based editor Overleaf.
    – maths soso
    Feb 20, 2021 at 14:57
  • @mathssoso in Overleaf you cannot do this, because you are not allowed to change the system directories there (understandably). So you need to install LaTeX on your local computer and change the style in your own system folders. The main distributions for local installations are TeX Live (Linux), MacTeX (Mac) and MikTeX (Windows).
    – Marijn
    Feb 20, 2021 at 16:21
  • @mathssoso see also tex.stackexchange.com/questions/548454/… for a similar question.
    – Marijn
    Feb 20, 2021 at 16:55
  • It's almost working, I have an issue with the ubuntu mono and fontspec when compiling with XeLaTeX, and undefined control sequence \setmonofont
    – maths soso
    Feb 21, 2021 at 2:02
  • Fonts that are used with fontspec must be installed on your system before you can use them. The Ubuntu Mono Font is installed by default on Ubuntu (unsurprisingly) but not on other operating systems - so if you have Windows or Mac or another Linux flavor then you need to download and install the font first. It is a free font, you can get it from fonts.google.com/specimen/Ubuntu+Mono for example. Copy the .ttf files to the same folder as your .tex file, or install them system-wide (open in font preview and click 'install' or something similar) to be able to [...]
    – Marijn
    Feb 21, 2021 at 7:27

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.