Skip to content

[Python] Using Python package “Pygments” to highlight your code

Last Updated on 2021-06-08 by Clay

If we using IDE to develop the program, maybe you have noticed: the code we wrote is highlighted! This is because of there is a backend program to highlight our code automatically.

Like this.

So, if we want to highlight our code by ourself, how do we do? We can use a useful Python package “Pygments”!

The following quote from the official website:

This is the home of Pygments. It is a generic syntax highlighter suitable for use in code hosting, forums, wikis or other applications that need to prettify source code. Highlights are:
– a wide range of over 500 languages and other text formats is supported
– special attention is paid to details that increase highlighting quality
– support for new languages and formats are added easily;
most languages use a simple regex-based lexing mechanism
– a number of output formats is available, among them HTML, RTF, LaTeX and ANSI sequences
– it is usable as a command-line tool and as a library

https://pygments.org/

So how do we use the Pygments? In the following article I will simply record the usage.


Installation

If you never install the Pygments in your computer, you need the following command:

sudo pip3 install Pygments

Instructions

To use Pygments you need to decide three parameters:

  • Lexer: Decide what language you want to highlight
  • Style: Decide what styles you want to use
  • Formatter: output foramt

Lexer

First, we need to decide what programming language. But before we decide, we can take a look for the languages which are support.

from pygments import lexers

for lexer in lexers.get_all_lexers():
    print(lexer)



Output:

('ABAP', ('abap',), ('<em>.abap', '</em>.ABAP'), ('text/x-abap',)) ('APL', ('apl',), ('<em>.apl',), ()) ('ABNF', ('abnf',), ('</em>.abnf',), ('text/x-abnf',)) . . . ('Zeek', ('zeek', 'bro'), ('<em>.zeek', '</em>.bro'), ()) ('Zephir', ('zephir',), ('<em>.zep',), ()) </em> ('Zig', ('zig',), ('*.zig',), ('text/zig',))

Style

Just like the narrative above, we need to decide what style we want to use. By the way, I always use “native”.

from pygments.styles import get_all_styles

# Style
for s in get_all_styles():
    print(s)



Output:

 default
 emacs
 friendly
 colorful
 autumn
 murphy
 manni
 monokai
 perldoc
 pastie
 borland
 trac
 native
 fruity
 bw
 vim
 vs
 tango
 rrt
 xcode
 igor
 paraiso-light
 paraiso-dark
 lovelace
 algol
 algol_nu
 arduino
 rainbow_dash
 abap
 solarized-dark
 solarized-light
 sas
 stata
 stata-light
 stata-dark
 inkpot

That’s all styles we can choose.


Formatter

The output formats of Pygments have many types you can choose. For example: “HTML” and “Image”.

First is “HTML”:

from pygments import highlight
from pygments import lexers
from pygments.formatters.html import HtmlFormatter
from pygments.styles import get_style_by_name

# Settings
code = "print('Hello World!')"
lexer = lexers.get_lexer_by_name('python')
style = get_style_by_name('native')
formatter = HtmlFormatter(full=True, style=style)

# Highlight
with open('test.html', 'w') as f:
    highlight(code, lexer, formatter, outfile=f)



Output:

You will see this screen.

And we can open the browser and see the result:

Image output format is the same usage. The obvious difference is that the writing of the picture is binary, so we need to use “wb” mode.

from pygments import highlight
from pygments import lexers
from pygments.formatters.img import ImageFormatter
from pygments.styles import get_style_by_name

# Settings
code = "print('Hello World!')"
lexer = lexers.get_lexer_by_name('python')
style = get_style_by_name('native')
formatter = ImageFormatter(full=True, style=style)

# Highlight
with open('test.png', 'wb') as f:
    f.write(highlight(code, lexer, formatter))



Output:

If the following error occurs:

pygments.formatters.img.PilNotAvailable: Python Imaging Library is required for this formatter

Then install Pillow using the following instructions:

sudo pip3 install Pillow

References

Leave a ReplyCancel reply

Exit mobile version