Escape Colors
Readable ANSI colors and nested text styles for Python 3.14+, with no runtime dependencies.
from escape_colors import ansi_print, blue, escape, escape_ansi, init_windows
ansi_print("blue(hello world)")
ansi_print("bold(blue(hello red(world) again))")
# For direct print/f-string output on Windows:
init_windows()
print(escape_ansi("blue(hello red(world))"))
print(f"{blue}hello world{escape}")
escape_ansi returns a string containing real ANSI SGR codes. ansi_print renders
markup and chooses whether to use color for the destination stream. Redirected
output is plain by default; use color=True to force ANSI sequences.
Install and develop
Install from PyPI with Python 3.14 or later:
python -m pip install escape-colors
From this checkout:
uv sync --locked
uv run python examples/basic.py
python tools/review_source.py
uv run python -m unittest discover -s tests -v
uv build
uv run python tools/verify_distribution.py
Install a built wheel into another Python environment with
uv pip install /path/to/escape_colors-0.3.0-py3-none-any.whl.
Releases
Publish a GitHub release with a tag matching the package version, such as
v0.3.0. .github/workflows/release.yaml tests and verifies the distributions
before publishing to PyPI through the pypi environment using Trusted Publishing.
The workflow can also be run manually against an existing release tag.
Colors and styles
The 16 named foreground colors are black, red, green, yellow, blue,
magenta, cyan, and white, plus bright_black, bright_red, bright_green,
bright_yellow, bright_blue, bright_magenta, bright_cyan, and bright_white.
Add bg_ for a background: bg_blue, bg_bright_white, and so on. Each name is
both a markup expression and an importable ANSI string constant.
from escape_colors import background, color, escape, escape_ansi
text = escape_ansi("bright_blue(hello bg_white(world))")
indexed = escape_ansi("15(white) 196(red) bg_232(dark background)")
direct = f"{color(196)}red {background(232)}on dark{escape}"
Numeric markup selects a 256-color palette index, not an SGR parameter:
15(text) means ESC[38;5;15m, and bg_15(text) means ESC[48;5;15m.
Indices 0–15 address the base palette, 16–231 the color cube, and 232–255 the
grayscale ramp. The terminal controls the actual palette and appearance.
color(index) and background(index) accept integers 0–255; booleans, floats,
strings, and values outside that range are rejected.
| Expression / constant | SGR | Effect |
|---|---|---|
bold |
1 | Bold/increased intensity |
faint, dim |
2 | Decreased intensity |
italic, italics |
3 | Italic |
underline |
4 | Underline |
double_underline |
21 | Double underline |
blink |
5 | Slow blink |
reverse |
7 | Swap foreground/background |
conceal |
8 | Conceal text |
strike, strikethrough |
9 | Strike through |
overline |
53 | Overline |
font0 … font9 |
10 … 19 | Default/alternative terminal font |
escape, reset |
0 | Reset constant for direct output |
Use bold(text), underline(text), italics(text), or combine them by nesting.
When an inner expression closes, its enclosing styles are restored. A top-level
expression ends with a reset. Font selection, italics, blink, and other attributes
depend on terminal support. SGR does not select arbitrary installed typefaces or
font sizes; older terminals may treat SGR 21 as an intensity change.
escape and reset are constants, rather than markup expressions.
Grammar and literal text
Markup is case-sensitive. A standalone ASCII name or decimal index immediately
followed by ( opens an expression. Whitespace between a name and ( makes it
ordinary text. Unknown names and ordinary parentheses remain in the output;
recognized expressions inside unknown parentheses still work.
from escape_colors import escape_ansi, strip_ansi
assert strip_ansi(escape_ansi("blue(hello (world))")) == "hello (world)"
assert escape_ansi("unknown(hello)") == "unknown(hello)"
assert escape_ansi(r"blue\(literal\)") == "blue(literal)"
assert strip_ansi(escape_ansi(r"blue(a\) b\( c\\d)")) == "a) b( c\\d"
\( and \) quote parentheses; \\ quotes a backslash. Other backslashes,
Unicode characters, line breaks, and tabs are preserved. Recognized unclosed
expressions and invalid numeric color indices raise ValueError with a
zero-based character position. Unmatched ordinary parentheses remain literal.
The parser is iterative and does not evaluate Python or depend on its recursion
limit. Existing raw SGR codes pass through; scope restoration tracks markup
styles, rather than arbitrary control sequences embedded in the input.
Unicode, hex, and octal notation
These three Python literals hold exactly the same one-character string:
assert "\u001b" == "\x1b" == "\033" == chr(27)
The spelling is consumed by Python when it creates the string. No format warning
is emitted, and normal terminal output is identical for all three choices.
ESCAPE_COLOR_FORMAT controls the visible representation produced by
literal=True or format_ansi, and defaults to "unicode".
import escape_colors
escape_colors.ESCAPE_COLOR_FORMAT = "octal"
assert escape_colors.escape_ansi("blue(hello)", literal=True) == r"\033[34mhello\033[0m"
assert escape_colors.escape_ansi("blue(hello)", literal=True, format="hex") == r"\x1b[34mhello\x1b[0m"
# The live runtime string always contains actual ESC characters.
assert escape_colors.escape_ansi("blue(hello)") == "\u001b[34mhello\u001b[0m"
escape_colors.ESCAPE_COLOR_FORMAT = "unicode"
Alternatively set the environment variable before importing:
ESCAPE_COLOR_FORMAT=octal uv run python examples/basic.py
On PowerShell, use $env:ESCAPE_COLOR_FORMAT = 'octal' before starting Python.
Accepted values are exactly unicode, hex, and octal. A per-call format
overrides the package setting. Assign escape_colors.ESCAPE_COLOR_FORMAT on the
module; assigning a separately imported local name does not update the module.
Invalid settings raise an error when rendering or serializing.
from escape_colors import blue, escape, escape_ansi, format_ansi, normalize_ansi
assert format_ansi(f"{blue}café{escape}", format="unicode") == r"\u001b[34mcafé\u001b[0m"
assert normalize_ansi(r"\x1b[34mcafé\033[0m") == f"{blue}café{escape}"
assert escape_ansi(r"\u001b[34mcafé\033[0m", decode=True) == f"{blue}café{escape}"
Textual notation decoding is opt-in. normalize_ansi and decode=True recognize
only \u001b, \x1b (also with uppercase B), and \033 followed by complete
numeric SGR sequences. They do not decode general Python escapes, change Unicode,
or decode a backslash-prefixed spelling. Literal output replaces ESC only: it is
readable escape notation, not a complete quoted/escaped Python string literal.
Printing and Windows
ansi_print(*objects, sep=" ", end="\n", file=None, flush=False, color=None)
renders each object's string representation and supports the usual print
arguments, including sep=None and end=None. It returns None.
import io
from escape_colors import ansi_print
capture = io.StringIO()
ansi_print("blue(hello)", "bold(world)", sep=" / ", end="!", file=capture)
assert capture.getvalue() == "hello / world!"
ansi_print("196(forced ANSI)", color=True)
ansi_print("blue(plain text)", color=False)
color=None: use color for a TTY unlessNO_COLORis nonempty orTERM=dumb. Streams without a workingisatty()get plain text. Windows also needs successful VT initialization.color=True: attempt Windows initialization and emit ANSI, even on redirection or if initialization fails. This overrides environment color preferences.color=False: remove rendered SGR codes, including existing SGR in objects, separators, and endings.
ansi_print initializes Windows automatically for the destination stream.
init_windows(file=None) is available for direct print/f-string output and can
also initialize stderr or another console stream. It preserves existing console
mode bits and enables processed output and virtual-terminal processing. Repeated
calls are safe. It returns True on Windows success and False on other systems,
unsupported consoles, or redirected/invalid handles. Importing the module does
not change console state. Obsolete Windows consoles without VT support are not
emulated; automatic printing uses plain text there.
strip_ansi removes numeric SGR sequences only. These APIs format text and do not
sanitize arbitrary terminal control commands in untrusted input.
Syntax highlighting
The escape_colors.syntax subsystem provides semantic token classification, color themes, and styled ANSI rendering for source code and token streams.
from escape_colors.syntax import highlight
python_code = "def greet(name: str) -> None:\n print(f'Hello {name}')"
print(highlight(python_code, language="python", theme="monokai"))
json_data = '{"name": "escape-colors", "version": "0.2.0"}'
print(highlight(json_data, language="json", theme="solarized-dark"))
Pre-tokenized inputs and token pipeline
Tokenization is separated from styling and ANSI rendering. Applications that already produce tokens or use parsing engines can highlight pre-tokenized streams directly without redundant tokenization:
from escape_colors.syntax import (
Token,
TokenType,
highlight,
render_ansi,
style_tokens,
)
tokens = [
Token(TokenType.KEYWORD, "import"),
Token(TokenType.TEXT, " "),
Token(TokenType.NAME, "sys"),
]
styled_ansi = highlight(tokens, theme="default")
styled_spans = style_tokens(tokens, theme="monokai")
output = render_ansi(styled_spans)
Themes and custom styles
Built-in themes include default, monokai, solarized-dark, and solarized-light. Themes can be retrieved with get_theme(name) or registered with register_theme(name, styles):
from escape_colors.syntax import TokenType, highlight, register_theme
custom = register_theme(
"forest",
{
TokenType.KEYWORD: "bold green",
TokenType.FUNCTION: "bright_yellow",
TokenType.STRING: "yellow",
TokenType.COMMENT: "dim",
},
)
print(highlight("def hello(): pass", language="python", theme="forest"))
Style specifications accept named ANSI colors and styles ("bold cyan"), 256-color palette indices ("color_208", "bg_232"), tuples (("bold", "green")), or direct escape sequences.
Optional astree integration
For structured HTML parsing or integration with astree, install with the syntax extra:
python -m pip install "escape-colors[syntax]"
Basic color and ANSI operations remain completely dependency-free; astree is imported lazily only when requested.
Verification and references
python tools/review_source.py performs a static review using only Python's
standard library. It checks first-party Python files for syntax errors and
SyntaxWarnings, checks runtime imports against the standard library and local
modules, and reports missing internal modules. It compiles source for validation
without executing the inspected code. Use --format json for structured results
or --root /path/to/checkout for another source tree. Findings exit with status 1;
invalid invocation exits with status 2. Review covers ordinary import statements,
including conditional imports; dynamic imports and imported attributes are
outside these checks. Runtime behavior is covered by the test suite.
CI tests Python 3.14 on Linux, macOS, and Windows, builds the wheel and source distribution, and runs the suite from freshly installed wheel artifacts outside the checkout. The verification script also rebuilds a wheel from the source archive. Tests cover nested restoration, every indexed color, notation, Unicode, printing, and Windows API behavior. Visual support still depends on the terminal.
- Python string escapes
- ANSI escape code overview
- Xterm control sequences
- Windows VT sequences
- SetConsoleMode
Terminal Markdown (0.3.0)
Install escape-colors[markdown] to select the optional parse-md parser and
Astree HTML tree profile. Core imports retain zero mandatory dependencies. Both
the development lock and published metadata use versioned PyPI requirements;
the qualified parser is parse-md 0.1.0.
from escape_colors.markdown import markdown_print, render_html, render_markdown
markdown_print('# Notes\n\nA **bold** paragraph.\n\n```python\nprint(1)\n```')
plain = render_markdown('| A | B |\n| --- | --- |\n| one | two |\n', width=60)
assert 'one' in plain
assert render_html('<p>red(literal)</p>') == 'red(literal)'
Astree supplies the bounded HTML tree; Escape Colors owns terminal presentation.
The default Markdown parser is parse-md's explicit extended document profile.
parser=callable selects a synchronous alternative returning HTML, an Astree
Document/Node, or a result with an html field. HTML/tree inputs can use render_html
directly. No notebook model, publication policy, renderer engine or application
URL handler is inferred. No editor or network request is launched.
Headings, paragraphs, nested lists/quotes, task checkboxes, rules, links/images, code and readable tables have terminal layout. Python/JSON and registered code lexers reuse syntax themes; unknown languages use plain code. If a tree-based lexer would reconstruct different source, code stays plain instead of changing the displayed text. All code is display text; controls are escaped. HTML scripts, styles, templates, hidden elements and SVG decorations are omitted.
render_html / render_markdown return plain text by default; color=True emits
SGR and hyperlinks=True explicitly selects OSC 8 links for allowed absolute
schemes. Default allowed schemes are http, https and mailto. Relative links show
their destination as text; custom schemes need an explicit allowed_schemes
selection. Link targets reject controls, credentials and unsafe schemes.
Terminal styles must be numeric SGR, and source text is never interpreted as
Escape Colors markup. The OSC format follows
the terminal hyperlink contract.
markdown_print chooses color for its destination using the existing TTY,
NO_COLOR, TERM and Windows VT rules. Redirected/NO_COLOR output is plain unless
color=True explicitly overrides it. Links remain off unless explicitly selected
and styling is enabled. Width defaults to terminal columns, clamped to 8–400;
returning functions default to width=80. CJK full-width characters and combining
marks are counted; complex emoji/grapheme appearance remains terminal-dependent.
Tabs expand to four spaces and line endings normalize for display. These are
document layouts, without CSS evaluation or Rich-specific pixel/width parity.
RenderLimits defaults: 2,000,000 input/tree characters, 100,000 nodes or code tokens, depth 64 (at most 128), 20,000 output lines and 8,000,000 encoded output characters. Both Markdown and produced HTML are bounded. Limit failures return no partial string; the print helper buffers rendering before writing. Existing Astree trees are inspected without mutation. Selected parser/lexer callbacks remain caller-owned code and must cooperate with these finite inputs.
Qualify the optional profile with uv sync --locked --extra markdown and the
ordinary test/distribution commands. CI and clean wheel/source installs test
both base and optional profiles.
Metadata
Release files for escape-colors 0.3.0
For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.
Source distribution (sdist)
| File | Size | Uploaded | Provenance | Actions |
|---|---|---|---|---|
| escape_colors-0.3.0.tar.gz | 21.3 kB | With provenance | Details for escape_colors-0.3.0.tar.gz |
Built distribution (wheel)
| File | Interpreter | ABI | Platform | Actions Reset |
|---|---|---|---|---|
| escape_colors-0.3.0-py3-none-any.whl | Python 3 | none | any | Details for escape_colors-0.3.0-py3-none-any.whl |
Total release size: 48.0 kB
Release files / escape_colors-0.3.0.tar.gz
| Download URL | escape_colors-0.3.0.tar.gz |
|---|---|
| Size | 21.3 kB |
| Tags | Source |
|
SHA-256 checksum How to use checksums |
6ed3e7fc6adf924455dfc9ef745e657a95aca04a38ae1d385089887f8dabc256
|
|
BLAKE2b-256 checksum How to use checksums |
14c9b6554549d6c00d8086b371dd540e358437e0b89a75f7f8400342c3eef82a
|
| Upload date | |
|
Uploaded using Trusted Publishing? What is trusted publishing? |
Yes |
| Uploaded via |
twine/7.0.0 CPython/3.13.14
|
Provenance
Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.
PyPI Publish Attestation
PyPI verified that this artifact, at this checksum, originated from the publisher listed below.
Signed by GitHub Actions, verified by PyPI on Nov 17, 2026.
Transparency logRelease files / escape_colors-0.3.0-py3-none-any.whl
| Download URL | escape_colors-0.3.0-py3-none-any.whl |
|---|---|
| Size | 26.6 kB |
| Tags | Python 3 |
|
SHA-256 checksum How to use checksums |
949ce4287e6d5932d8e290cadae53bb249dd5ab60826b6ae1be64704255cde53
|
|
BLAKE2b-256 checksum How to use checksums |
344c9d6c93da2b93d89ba06b7074685f904ba90c09a1e58d725af9c0042a1105
|
| Upload date | |
|
Uploaded using Trusted Publishing? What is trusted publishing? |
Yes |
| Uploaded via |
twine/7.0.0 CPython/3.13.14
|
Provenance
Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.
PyPI Publish Attestation
PyPI verified that this artifact, at this checksum, originated from the publisher listed below.
Signed by GitHub Actions, verified by PyPI on Nov 17, 2026.
Transparency logSecurity for escape-colors 0.3.0
Provenance
Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.
Full provenance
Both files in this release have been uploaded with provenance metadata.
Attestation for escape_colors-0.3.0.tar.gz
PyPI Publish Attestation
PyPI verified that this artifact, at this checksum, originated from the publisher listed below.
Signed by GitHub Actions, verified by PyPI on Nov 17, 2026.
Transparency logA note on package security
PyPI is a repository for distributing packages, not a service for auditing them. While third-party security researchers and our staff do their best to detect and remove malicious packages, PyPI cannot guarantee the quality, security or suitability of any given package.
To learn more about protecting yourself from malicious actors, visit our package security documentation.