Il pacchetto minted
Crea il tuo stile con Pygments
Il pacchetto minted permette di inserire codice sorgente all'interno di un documento \LaTeX{} e di colorarlo automaticamente. Per fare ciò, minted si appoggia a Pygments, un sistema di colorazione di codice sorgente scritto in Python.
Per utilizzare minted è necessario caricare il pacchetto all'interno del preambolo del documento:
\usepackage{minted}Per inserire del codice all'interno del documento, si utilizza l'ambiente minted:
\begin{minted}{python}
def hello_world():
print("Hello, world!")
\end{minted}Se non si è sossisfatti degli stili di colorazione predefiniti, è possibile creare un proprio stile personalizzato.
Per farlo, è necessario creare un file .py contenente il proprio stile. Ad esempio, il seguente file mystyle.py definisce uno stile personalizzato:
from pygments.style import Style
from pygments.token import Keyword, Name, Comment, String, Error, Number, Operator, Generic
class MyStyle(Style):
default_style = ""
styles = {
Comment: 'italic #888',
Keyword: 'bold #00f',
Name: '#f00',
Name.Function: '#0f0',
Name.Class: 'bold #0f0',
String: '#f00',
Number: '#f00',
}Per utilizzare il proprio stile personalizzato, è necessario caricare il pacchetto minted specificando il percorso del file .py contenente lo stile:
\usepackage{minted}
\usemintedstyle{mystyle}0. Create your custom style
Create a Python file that contains your associations of entities and formatting within your imported code using minted. And save it as MyCustomStyle.py.
Choosing the name
- The name of the file should be the same of the class inside.
from pygments.style import Style
from pygments.token import Token, Comment, Keyword, Name, String, Error, Generic, Number, Operator
class MyCustomStyle(Style):
"""My custom style."""
# Define your style rules here
styles = {
# Example:
Token: '', # Default style
Comment: 'italic #888',
Keyword: 'bold #005',
Name: '#f00',
Name.Function: 'bold #0f0',
String: 'bg:#eee #111',
# ... add more rules as needed ...
}Rules to keep in mind
- When you define a style for
Namethe style automatically also affectsName.Functionand so on; For example, If you definedbold(e.g. forName) and you don't want boldface for a subtoken (e.g.Name.Function) usenobold.
Explanation of keywords
Token: is the default style inherited by all token types; You can use this to set default styles;Comment: Style for comments;Keyword: Style for keywords;Name: Style for identifiers (e.g., variables, functions).Name.Function: Style for function names. String: Style for strings.
1. Register it as a plugin
2. Update the pygments.styles subpackage directory
This is only recommended if you're contributing to Pygments itself.
You'd add your style file to the pygments.styles directory and regenerate the mappings file using tox -e mapfiles.
Here are some resources that you may find helpful:
If you'd like to further customize the style, take a look at "Builtin Tokens".