Module

_escape

HTML escaping utilities for Rosettes.

Thread-safe string escaping for HTML output.

Design Philosophy:

This module usesstr.translate()with a pre-computed table for maximum performance. This is faster than regex or multiplestr.replace()calls:

  • str.translate(): ~0.2µs per call (C-level implementation)
  • regex sub(): ~1.5µs per call
  • chainedreplace(): ~0.8µs per call

For syntax highlighting,escape_html()is called once per token, so performance here directly impacts overall throughput.

Security:

Escapes the standard five HTML special characters:

  • &&(must be first to avoid double-escaping)
  • <&lt;(prevents tag injection)
  • >&gt;(prevents tag injection)
  • "&quot;(prevents attribute injection)
  • '&#x27;(prevents attribute injection in single quotes)

This provides protection against XSS when embedding code in HTML.

Thread-Safety:

The escape table is immutable (dict with int keys). The function uses only the input string and the table — no shared mutable state.

See Also:

  • rosettes.formatters.html: Usesescape_htmlfor all token values

Functions

escape_html 1 str
Escape HTML special characters. Escapes: & " ' Uses str.translate() with a p…
def escape_html(text: str) -> str

Escape HTML special characters.

Escapes: & < > " '

Uses str.translate() with a pre-computed table for maximum performance. This is the hot path for HTML formatting — called once per token.

Performance: ~0.2µs per call for typical token lengths (5-20 chars).

Parameters
Name Type Description
text str

The text to escape.

Returns
str