Metadata-Version: 2.3
Name: escape-colors
Version: 0.3.0
Summary: ANSI colors, nested text styles, and portable terminal printing
Author: ellainng
Author-email: ellainng <299958882+ellainng@users.noreply.github.com>
Requires-Dist: astree>=0.1.0,<0.2 ; extra == 'markdown'
Requires-Dist: parse-md>=0.1.0,<0.2 ; extra == 'markdown'
Requires-Dist: astree ; extra == 'syntax'
Requires-Python: >=3.14
Project-URL: Repository, https://github.com/wispsy/escape_colors
Project-URL: Issues, https://github.com/wispsy/escape_colors/issues
Provides-Extra: markdown
Provides-Extra: syntax
Description-Content-Type: text/markdown

# Escape Colors

Readable ANSI colors and nested text styles for Python 3.14+, with no runtime
dependencies.

```python
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:

```sh
python -m pip install escape-colors
```

From this checkout:

```sh
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.

```python
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.

```python
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:

```python
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"`.

```python
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**:

```sh
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.

```python
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`.

```python
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 unless `NO_COLOR` is nonempty or `TERM=dumb`.
  Streams without a working `isatty()` 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.

```python
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:

```python
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)`:

```python
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:

```sh
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
`SyntaxWarning`s, 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](https://docs.python.org/3.14/reference/lexical_analysis.html#escape-sequences)
- [ANSI escape code overview](https://en.wikipedia.org/wiki/ANSI_escape_code)
- [Xterm control sequences](https://invisible-island.net/xterm/ctlseqs/ctlseqs.html)
- [Windows VT sequences](https://learn.microsoft.com/en-us/windows/console/console-virtual-terminal-sequences)
- [SetConsoleMode](https://learn.microsoft.com/en-us/windows/console/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.

```python
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](https://iterm2.com/documentation-escape-codes.html).

`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.
