Metadata-Version: 2.4
Name: codechu-term
Version: 0.1.0
Summary: Stdlib-only terminal capability detection and low-level terminal control.
Author: Codechu
License: MIT License
        
        Copyright (c) 2026 Codechu
        
        Permission is hereby granted, free of charge, to any person obtaining a copy
        of this software and associated documentation files (the "Software"), to deal
        in the Software without restriction, including without limitation the rights
        to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
        copies of the Software, and to permit persons to whom the Software is
        furnished to do so, subject to the following conditions:
        
        The above copyright notice and this permission notice shall be included in all
        copies or substantial portions of the Software.
        
        THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
        IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
        FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
        AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
        LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
        OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
        SOFTWARE.
        
Project-URL: Homepage, https://github.com/codechu/term-py
Project-URL: Source, https://github.com/codechu/term-py
Project-URL: Issues, https://github.com/codechu/term-py/issues
Keywords: terminal,tty,ansi,capabilities,alt-buffer,raw-mode,stdlib
Classifier: Development Status :: 4 - Beta
Classifier: Intended Audience :: Developers
Classifier: License :: OSI Approved :: MIT License
Classifier: Operating System :: POSIX
Classifier: Operating System :: POSIX :: Linux
Classifier: Operating System :: MacOS
Classifier: Programming Language :: Python :: 3
Classifier: Programming Language :: Python :: 3.10
Classifier: Programming Language :: Python :: 3.11
Classifier: Programming Language :: Python :: 3.12
Classifier: Topic :: Software Development :: Libraries
Classifier: Topic :: Terminals
Requires-Python: >=3.10
Description-Content-Type: text/markdown
License-File: LICENSE
Provides-Extra: dev
Requires-Dist: pytest>=7.0; extra == "dev"
Requires-Dist: pytest-cov>=4.1; extra == "dev"
Requires-Dist: ruff>=0.4; extra == "dev"
Dynamic: license-file

```text
   ┌──────────────────────────────────────────────────┐
   │  c o d e c h u — t e r m                         │
   │  $ _                                             │
   │  ····TTY detection · alt buffer · raw mode······ │
   └──────────────────────────────────────────────────┘
```

> *Terminal capability detection and low-level control, stdlib-only.*

# codechu-term

Stdlib-only terminal-capability detection and low-level terminal
control — extracted from the [codechu/cli-py](https://github.com/codechu/cli-py)
private `_term` module and expanded with the bits Codechu CLIs
actually use. No external dependencies. Python 3.10+, POSIX-first.

## Install

```bash
pip install codechu-term
```

## API

```python
import os, sys
from codechu_term import (
    is_tty, terminal_size, capabilities,
    with_alt_buffer, with_raw_mode, on_resize,
    hide_cursor, show_cursor, clear_line, clear_screen,
)

is_tty(sys.stderr)                          # → True / False

terminal_size()                             # → (cols, rows), e.g. (120, 40)
terminal_size(env={"COLUMNS": "100", "LINES": "30"})  # explicit env

capabilities(sys.stdout, env=os.environ)
# → {'color': True, 'truecolor': True, 'unicode': True,
#    'emoji': True, 'mouse': True, 'alt_buffer': True}

with with_alt_buffer() as out:              # full-screen mode
    out.write("hello, alt buffer\n"); out.flush()

with with_raw_mode() as fd:                 # char-by-char input
    ch = os.read(fd, 1)

remove = on_resize(lambda: print("resized!"))
# ... later
remove()

hide_cursor(); show_cursor()
clear_line(); clear_screen()
```

### `is_tty(stream)`

Defensive `isatty()` — accepts `None` and any object, swallows
exceptions, returns `False` for anything that isn't a confirmed TTY.

### `terminal_size(stream=sys.stderr, *, env=None)`

Resolution ladder:

1. `os.get_terminal_size(stream.fileno())` when available.
2. `COLUMNS` / `LINES` from `env` (defaults to `os.environ`).
3. `(80, 24)` as a final fallback.

Never raises.

### `capabilities(stream, env=None)`

Returns six boolean flags:

| Key          | True when                                                     |
| ------------ | ------------------------------------------------------------- |
| `color`      | `stream` is a TTY, `TERM != "dumb"`, and `NO_COLOR` is unset  |
| `truecolor`  | `color` and `COLORTERM` in `{"truecolor", "24bit"}`           |
| `unicode`    | `LC_ALL` / `LC_CTYPE` / `LANG` advertises UTF-8               |
| `emoji`      | `unicode` and (`TERM_PROGRAM` is a known emoji emulator or xterm-family) |
| `mouse`      | TTY and xterm-family `TERM`                                   |
| `alt_buffer` | xterm-family `TERM`                                           |

`env` is taken explicitly — pass `env=os.environ` for the live
process environment.

### `with_alt_buffer(stream=sys.stdout)`

Context manager that switches to the alt screen buffer
(`\x1b[?1049h`) on entry and restores the main buffer
(`\x1b[?1049l`) on exit — even when the block raises.

### `with_raw_mode(fd=sys.stdin.fileno())`

`termios`/`tty` raw mode for char-by-char input. Restores the
original terminal attributes in a `finally` block, so the terminal
never gets stuck. POSIX only.

### `on_resize(callback)`

Installs `callback` as a `SIGWINCH` handler and returns a remover
function that restores the previous handler. The callback is invoked
with no arguments. POSIX only.

### `hide_cursor() / show_cursor() / clear_line() / clear_screen()`

Best-effort emitters for the corresponding ANSI sequences
(`\x1b[?25l`, `\x1b[?25h`, `\x1b[2K\r`, `\x1b[2J\x1b[H`). They never
raise — a closed stream is silently ignored.

## Design

- **Pure stdlib.** Zero third-party dependencies.
- **Explicit env.** Capability detection never reads `os.environ`
  implicitly — the caller passes the dict. Makes testing trivial and
  avoids surprises in nested processes.
- **Defensive.** Helpers tolerate `None` streams, closed streams,
  and missing methods. They never raise from a "best-effort" path.
- **POSIX-first.** `with_raw_mode` and `on_resize` are POSIX-only
  (termios / SIGWINCH); they raise `OSError` on Windows rather than
  silently no-op.

## Tests

```bash
pip install -e ".[dev]"
pytest -q
```

Tests that require a real TTY (raw mode, SIGWINCH propagation) skip
themselves when running headless.

## License

MIT — see [LICENSE](LICENSE).
