Introduction to Pygments
Pygments is a powerful syntax highlighting library written in Python, widely used to add colorized, easily readable code snippets to various applications such as web pages, CLI tools, and documentation. It supports a vast range of programming languages and markup formats, making it a go-to solution for developers and technical writers.
In this guide, we will dive deep into the core features of Pygments
and demonstrate its APIs through practical examples. By the end of this article, you’ll also see how to build a mini application utilizing these features.
Key Features of Pygments
- Support for over 300 programming languages and file types.
- Rich styles and themes for syntax highlighting.
- Customizable lexers, formatters, and styles for endless flexibility.
- Seamless integration into CLI and Python scripts.
Pygments API Examples
1. Highlighting Source Code
The core function of Pygments is code highlighting. You can use the highlight
method with a lexer and a formatter to get the desired output.
from pygments import highlight
from pygments.lexers import PythonLexer
from pygments.formatters import HtmlFormatter
code = "def hello_world():\n print('Hello, world!')"
highlighted_code = highlight(code, PythonLexer(), HtmlFormatter())
print(highlighted_code)
2. Listing Available Lexers
You can retrieve a list of all supported lexers using the get_all_lexers
method.
from pygments.lexers import get_all_lexers
for lexer in get_all_lexers():
print(lexer)
3. Using Formatters
Pygments offers several formatters such as HTML, LaTeX, and IRC. For example, creating a LaTeX-styled output:
from pygments import highlight
from pygments.lexers import JavaLexer
from pygments.formatters import LatexFormatter
code = "public class HelloWorld { public static void main(String[] args) { System.out.println('Hello, World!'); }}"
latex_output = highlight(code, JavaLexer(), LatexFormatter())
print(latex_output)
4. Line Numbering
Pygments makes it easy to add line numbers to your highlighted code with the HtmlFormatter
.
from pygments import highlight
from pygments.lexers import BashLexer
from pygments.formatters import HtmlFormatter
code = "echo 'Hello, Bash!'"
formatter = HtmlFormatter(linenos=True)
highlighted_code = highlight(code, BashLexer(), formatter)
print(highlighted_code)
5. Custom Themes
You can customize existing styles or create new ones using Style
class.
from pygments.style import Style
from pygments.token import Keyword, Name, Comment
class CustomStyle(Style):
default_style = ""
styles = {
Keyword: 'bold #FF00FF',
Name: 'italic #00FF00',
Comment: 'underline #0000FF',
}
6. Creating Custom Lexers
Sometimes, you may want to create your own lexer for an unsupported language.
from pygments.lexer import RegexLexer
from pygments.token import Text, Number
class SimpleLexer(RegexLexer):
tokens = {
'root': [
(r'\d+', Number),
(r'\s+', Text),
],
}
Building a Simple Highlighted Code Web App
Here’s a simple example of a web application using Pygments for syntax highlighting, built with Flask:
from flask import Flask, request, render_template_string
from pygments import highlight
from pygments.lexers import get_lexer_by_name
from pygments.formatters import HtmlFormatter
app = Flask(__name__)
@app.route('/', methods=['GET', 'POST'])
def index():
if request.method == 'POST':
code = request.form['code']
language = request.form['language']
lexer = get_lexer_by_name(language)
formatter = HtmlFormatter(linenos=True, full=True, style='colorful')
result = highlight(code, lexer, formatter)
return result
return '''
'''
if __name__ == '__main__':
app.run(debug=True)
Conclusion
Pygments is a versatile library with a broad set of features suited for highlighting code in a wide range of scenarios. With its extensive support for languages, customizable APIs, and integration options, Pygments remains a favorite tool for developers who want to create visually attractive, easy-to-read code presentations. Start using Pygments today to take your projects to the next level!