Metadata-Version: 2.4
Name: libTerm
Version: 0.2.5
Author-email: Jeroen Hoefkens <hoefkens.j@gmail.com>
Project-URL: Homepage, https://github.com/hoefkensj/libTerm
Project-URL: Issues, https://github.com/hoefkensj/libTerm
Description-Content-Type: text/markdown


# libTerm

## Quick Setup with examples:
```commandline
git clone https://github.com/hoefkensj/libTerm
cd libTerm
python -m venv .venv && source .venv/bin/activate
pip install -e . 
python Examples/ex_manualsnake.py

```
## Quick Setup for use within Your project:
```commandline
pip install libTerm
```




## ⚠️ **WARNING:**
While No code in this project was written by an LLM (not even autocomplete). Everything below this warning was 
generated generated by an LLM. It was Quickly skimmed for errors and or falsehoods, corrected where needed, but I 
would not trust it to much.  





**libTerm** is a lightweight Python library for **low-level terminal control** and **interactive TUI-style programs**.  
It provides a clean abstraction over ANSI escape codes, POSIX terminal modes, cursor movement, input handling, colors, and terminal size — without hiding the power of the terminal.

This library is best suited for:
- Interactive CLI tools
- Terminal games (snake, roguelikes, demos)
- Live terminal dashboards
- Custom key handling (arrows, raw input)


It works primarily on **POSIX systems** (Linux/macOS). An implementation for windows is in progress but not usable 
at the moment (running it in a 3rd party terminal emulator in windows could work).

---

## Features

- 🖥 Terminal mode control (NORMAL / CONTROL)
- 🎯 Cursor positioning, movement, save/restore
- ⌨ Raw keyboard input & event polling
- 🎨 Terminal foreground/background color detection
- 📐 Terminal size tracking
- 🧱 Minimal abstraction — ANSI is still accessible

---

---

## Quick Start

```python
from libTerm import Term,Coord,Mode

term = Term()
print(term.size.xy)       # Terminal size (columns, rows)
print(term.cursor.xy)     # Cursor position
print(term.color.bg)      # Background color
```

---

## Terminal Modes

libTerm exposes terminal modes through `Mode`.

### Modes

* `Mode.NORMAL` – canonical input, echo on, cursor visible
* `Mode.CONTROL` – raw-ish input, no echo, cursor hidden

### Switching Modes

```python
from libTerm import Term, Mode

term = Term()
term.mode(Mode.CONTROL)

print("Press q to quit")
while True:
    if term.stdin.event:
        key = term.stdin.read()
        if key == 'q':
            break

term.mode(Mode.NORMAL)
```

⚠️ **IMPORTANT:** The terminal is automatically restored on exit using `atexit`, but you should still return to `NORMAL` mode explicitly when possible.

---

## Keyboard Input (`term.stdin`)

### Properties & Methods

| Member     | Description                     |
| ---------- | ------------------------------- |
| `event`    | Non-blocking check for input    |
| `read()`   | Read buffered input as a string |
| `buffer()` | Fill internal buffer            |
| `flush()`  | Clear buffer                    |
| `count`    | Number of buffered reads        |

### Example: Arrow Keys

```python
from libTerm import Term, Mode

term = Term()
term.mode(Mode.CONTROL)

while True:
    if term.stdin.event:
        key = term.stdin.read()
        if key == '\x1b[A':
            print("UP")
        elif key == '\x1b[B':
            print("DOWN")
        elif key == '\x1b[C':
            print("RIGHT")
        elif key == '\x1b[D':
            print("LEFT")
        elif key == 'q':
            break
```

---

## Cursor Control (`term.cursor`)

### Cursor Properties

| Property  | Description                       |
| --------- | --------------------------------- |
| `xy`      | Get/set cursor position (`Coord`) |
| `x`, `y`  | Individual coordinates            |
| `visible` | Cursor visibility state           |
| `hidden`  | Cursor hidden state               |

### Cursor Movement

```python
from libTerm import Term, Coord

term = Term()

term.cursor.xy = Coord(10, 5)
print("#")

term.cursor.move.down()
print("#")

term.cursor.move.right(5)
print("#")

term.cursor.move.abs(X=2, Y=12)
print("#")
```

### Show / Hide Cursor

```python
term.cursor.hide()
term.cursor.show()
```

---

## Cursor Save / Restore (Store)

The cursor maintains a **position stack**.

### Methods

| Method    | Description                   |
| --------- | ----------------------------- |
| `save()`  | Save current position         |
| `undo()`  | Restore previous position     |
| `load(n)` | Load specific stored position |

### Example

```python
term.cursor.save()
print("Hello")
term.cursor.undo()
print("World")
```

---

## Coordinates (`Coord`)

`Coord` is an immutable `(x, y)` structure.

```python
from libTerm import Coord

c = Coord(5, 10)

print(c.x, c.y)
print(c.xy)
print(c + Coord(2, 3))
```

It supports:

* Indexing (`c[0]`, `c['x']`)
* Addition
* Iteration

---

## Terminal Size (`term.size`)

### Properties

| Property   | Description           |
| ---------- | --------------------- |
| `xy`       | `(columns, rows)`     |
| `width`    | Columns               |
| `height`   | Rows                  |
| `changed`  | Size changed recently |
| `changing` | Resize in progress    |

```python
term = Term()
print(term.size.xy)

if term.size.changed:
    print("Terminal resized!")
```

---

## Colors (`term.color`)

Reads current terminal colors.

```python
print(term.color.fg)
print(term.color.bg)
print(term.color.bg.RGB)
```

`Color` supports:

* `R`, `G`, `B`
* `BIT` depth
* `.RGB` tuple

---

## ANSI Access (Advanced)

libTerm does **not** hide ANSI escape sequences.
You can freely mix raw ANSI with the API.

```python
print("\x1b[31mRED\x1b[m")
```

Cursor movement enums are exposed:

```python
term.cursor.move.up(2)
term.cursor.move.left(5)
```

---

## Example Use Cases

### 1. Interactive Input

* Custom keybinds
* Vim-like controls
* Raw arrow-key navigation

### 2. Terminal Games

* Snake (see `Examples/`)
* Roguelikes
* ASCII animations

### 3. Live Dashboards

* Terminal resizing detection
* Cursor-based rendering
* Zero external dependencies

### 4. Learning Tool

* Study ANSI sequences
* Understand terminal modes
* Experiment with POSIX I/O

---

## Examples Included

Located in `Examples/`:

| File                | Description               |
| ------------------- | ------------------------- |
| `example.py`        | Basic usage demo          |
| `ex3.py`            | Raw arrow-key handling    |
| `ex_autosnake.py`   | Automated snake animation |
| `ex_manualsnake.py` | Keyboard-controlled snake |

Run them directly:

```bash
python Examples/example.py
```

---

## Platform Notes

* ✅ Linux / macOS: Fully supported
* ⚠ Windows: Partial support (limited cursor/input features)

---

## Philosophy

libTerm is intentionally **low-level**.

It aims to:

* Stay close to ANSI & POSIX
* Avoid heavy abstractions
* Let you *see* and *control* the terminal

If you want a framework — use something else.
If you want **control** — use libTerm.

---

## License

MIT License (or specify if different)

---

## Contributing

Pull requests welcome.
Bug reports and experimental ideas encouraged.

---

Happy hacking 🐍🖥

```

