[Tex/LaTex] Configure minted style in LaTeX for code highlighting

codeminted

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}

Best Answer

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.