or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

Files

docs

animations.mdcolors-markup.mdfile-loading.mdindex.mdterminal.mdutilities.mdwidgets.mdwindow-management.md

terminal.mddocs/

0

# Terminal Interface

1

2

PyTermGUI provides comprehensive terminal control including ANSI escape sequences, cursor management, screen control, input handling, and mouse support. The terminal interface handles cross-platform compatibility and terminal capability detection.

3

4

## Capabilities

5

6

### Terminal Management

7

8

Core terminal interface providing screen size detection, output management, and capability detection.

9

10

```python { .api }

11

class Terminal:

12

"""Terminal interface and capabilities manager."""

13

14

def __init__(self):

15

"""Initialize terminal interface."""

16

17

@property

18

def size(self) -> tuple[int, int]:

19

"""Get terminal size as (width, height)."""

20

21

@property

22

def width(self) -> int:

23

"""Get terminal width in columns."""

24

25

@property

26

def height(self) -> int:

27

"""Get terminal height in rows."""

28

29

def print(self, *args, **kwargs):

30

"""Print to terminal with markup support."""

31

32

def write(self, text: str):

33

"""Write text directly to terminal."""

34

35

def flush(self):

36

"""Flush terminal output buffer."""

37

38

def record(self) -> "Recorder":

39

"""Start recording terminal output."""

40

41

class Recorder:

42

"""Terminal output recording for playback."""

43

44

def __init__(self):

45

"""Initialize recorder."""

46

47

def stop(self) -> str:

48

"""Stop recording and return content."""

49

50

def save(self, filename: str):

51

"""Save recording to file."""

52

53

def get_terminal() -> Terminal:

54

"""Get global terminal instance."""

55

56

def set_global_terminal(terminal: Terminal):

57

"""Set global terminal instance."""

58

59

# Global terminal instance

60

terminal: Terminal

61

```

62

63

### Screen Control

64

65

Functions for managing screen buffer, clearing display, and alternate screen buffer.

66

67

```python { .api }

68

def save_screen() -> None:

69

"""Save current screen content."""

70

71

def restore_screen() -> None:

72

"""Restore saved screen content."""

73

74

def set_alt_buffer() -> None:

75

"""Switch to alternate screen buffer."""

76

77

def unset_alt_buffer() -> None:

78

"""Switch back to main screen buffer."""

79

80

def clear(what: str = "screen") -> None:

81

"""

82

Clear screen or line content.

83

84

Parameters:

85

- what (str): What to clear ('screen', 'line', 'line_to_end', 'line_to_start')

86

"""

87

```

88

89

### Cursor Control

90

91

Comprehensive cursor positioning and visibility control.

92

93

```python { .api }

94

def hide_cursor() -> None:

95

"""Hide terminal cursor."""

96

97

def show_cursor() -> None:

98

"""Show terminal cursor."""

99

100

def save_cursor() -> None:

101

"""Save current cursor position."""

102

103

def restore_cursor() -> None:

104

"""Restore saved cursor position."""

105

106

def report_cursor() -> tuple[int, int] | None:

107

"""Get current cursor position as (row, col)."""

108

109

def move_cursor(pos: tuple[int, int]) -> None:

110

"""

111

Move cursor to position.

112

113

Parameters:

114

- pos (tuple): (row, col) position

115

"""

116

117

def cursor_up(num: int = 1) -> None:

118

"""Move cursor up by num rows."""

119

120

def cursor_down(num: int = 1) -> None:

121

"""Move cursor down by num rows."""

122

123

def cursor_right(num: int = 1) -> None:

124

"""Move cursor right by num columns."""

125

126

def cursor_left(num: int = 1) -> None:

127

"""Move cursor left by num columns."""

128

129

def cursor_next_line(num: int = 1) -> None:

130

"""Move cursor to start of next line."""

131

132

def cursor_prev_line(num: int = 1) -> None:

133

"""Move cursor to start of previous line."""

134

135

def cursor_column(num: int = 0) -> None:

136

"""Move cursor to column number."""

137

138

def cursor_home() -> None:

139

"""Move cursor to home position (0, 0)."""

140

```

141

142

### Input System

143

144

Keyboard input handling with timeout support and key code management.

145

146

```python { .api }

147

class Keys:

148

"""Key code constants and utilities for input handling."""

149

150

def __init__(self, platform_keys: dict[str, str], platform: str):

151

"""

152

Initialize Keys object.

153

154

Parameters:

155

- platform_keys (dict): Platform-specific key mappings

156

- platform (str): Platform identifier ("nt" or "posix")

157

"""

158

159

# Special keys

160

UP: str

161

DOWN: str

162

LEFT: str

163

RIGHT: str

164

ENTER: str

165

RETURN: str

166

ESCAPE: str

167

ESC: str

168

BACKSPACE: str

169

DELETE: str

170

TAB: str

171

SPACE: str

172

ALT: str

173

CARRIAGE_RETURN: str

174

175

# Control keys (CTRL_A through CTRL_Z)

176

CTRL_A: str

177

CTRL_B: str

178

CTRL_C: str

179

CTRL_D: str

180

CTRL_E: str

181

CTRL_F: str

182

CTRL_G: str

183

CTRL_H: str

184

CTRL_I: str

185

CTRL_J: str

186

CTRL_K: str

187

CTRL_L: str

188

CTRL_M: str

189

CTRL_N: str

190

CTRL_O: str

191

CTRL_P: str

192

CTRL_Q: str

193

CTRL_R: str

194

CTRL_S: str

195

CTRL_T: str

196

CTRL_U: str

197

CTRL_V: str

198

CTRL_W: str

199

CTRL_X: str

200

CTRL_Y: str

201

CTRL_Z: str

202

CTRL_SPACE: str

203

204

# Function keys

205

F1: str

206

F2: str

207

F3: str

208

F4: str

209

F5: str

210

F6: str

211

F7: str

212

F8: str

213

F9: str

214

F10: str

215

F11: str

216

F12: str

217

218

def normalize(self, key: str) -> str:

219

"""Normalize key representation for consistent handling."""

220

221

def __getitem__(self, key: str) -> str:

222

"""Get key code by name."""

223

224

def __contains__(self, key: str) -> bool:

225

"""Check if key exists in mapping."""

226

227

def getch(timeout: float = None) -> str:

228

"""

229

Get single character input.

230

231

Parameters:

232

- timeout (float, optional): Input timeout in seconds

233

234

Returns:

235

Character or key code string

236

"""

237

238

def getch_timeout(timeout: float, interval: float = 0.01) -> str | None:

239

"""

240

Get character with timeout and polling interval.

241

242

Parameters:

243

- timeout (float): Maximum wait time

244

- interval (float): Polling interval

245

246

Returns:

247

Character or None if timeout

248

"""

249

250

def feed(text: str) -> None:

251

"""

252

Feed text to input system for testing.

253

254

Parameters:

255

- text (str): Text to inject into input stream

256

"""

257

258

# Global keys instance

259

keys: Keys

260

```

261

262

### Mouse Support

263

264

Mouse event handling and parsing for interactive applications.

265

266

```python { .api }

267

class MouseAction(Enum):

268

"""Mouse action types."""

269

LEFT_CLICK: str

270

RIGHT_CLICK: str

271

MIDDLE_CLICK: str

272

SCROLL_UP: str

273

SCROLL_DOWN: str

274

DRAG: str

275

MOVE: str

276

277

class MouseEvent:

278

"""Mouse event data."""

279

280

def __init__(self, action: MouseAction, position: tuple[int, int]):

281

"""

282

Create mouse event.

283

284

Parameters:

285

- action (MouseAction): Type of mouse action

286

- position (tuple): (x, y) mouse position

287

"""

288

289

@property

290

def action(self) -> MouseAction:

291

"""Get mouse action type."""

292

293

@property

294

def position(self) -> tuple[int, int]:

295

"""Get mouse position as (x, y)."""

296

```

297

298

### Terminal Modes

299

300

Terminal mode management for input/output control.

301

302

```python { .api }

303

def set_mode(mode: str | int, write: bool = True) -> str:

304

"""

305

Set terminal mode.

306

307

Parameters:

308

- mode: Mode identifier

309

- write (bool): Whether to write to terminal

310

311

Returns:

312

ANSI escape sequence

313

"""

314

315

def set_echo() -> None:

316

"""Enable input echo."""

317

318

def unset_echo() -> None:

319

"""Disable input echo."""

320

```

321

322

### Context Managers

323

324

Convenient context managers for terminal state management.

325

326

```python { .api }

327

def alt_buffer(echo: bool = False, cursor: bool = True):

328

"""

329

Context manager for alternate screen buffer.

330

331

Parameters:

332

- echo (bool): Whether to disable echo, defaults to False

333

- cursor (bool): Whether to hide cursor, defaults to True

334

335

Usage:

336

with alt_buffer():

337

# Terminal operations in alternate buffer

338

pass

339

"""

340

341

def cursor_at(pos: tuple[int, int]):

342

"""

343

Context manager for cursor positioning with auto-incrementing y.

344

345

Parameters:

346

- pos (tuple): (x, y) starting position

347

348

Returns:

349

Callable printer function that prints at cursor position

350

351

Usage:

352

with cursor_at((10, 5)) as printer:

353

printer("Line 1") # Prints at (10, 5)

354

printer("Line 2") # Prints at (10, 6)

355

"""

356

357

def mouse_handler(events: list[str], method: str = "decimal_xterm"):

358

"""

359

Context manager for mouse input handling.

360

361

Parameters:

362

- events (list): List of mouse events to capture ("press", "hover", etc.)

363

- method (str): Mouse reporting method ("decimal_xterm" or "decimal_urxvt")

364

365

Returns:

366

Mouse translator function that converts key codes to MouseEvent objects

367

368

Usage:

369

with mouse_handler(["press", "hover"]) as mouse:

370

while True:

371

key = getch()

372

event = mouse(key)

373

if event:

374

print(f"Mouse {event.action} at {event.position}")

375

"""

376

```

377

378

### Input Timeout

379

380

Context manager for input timeout operations.

381

382

```python { .api }

383

def timeout(duration: float):

384

"""

385

Context manager for input timeout using SIGALRM.

386

387

Note: Not supported on Windows due to signal limitations.

388

389

Parameters:

390

- duration (float): Timeout duration in seconds

391

392

Raises:

393

- TimeoutException: When the timeout duration is exceeded

394

395

Usage:

396

try:

397

with timeout(5.0):

398

key = getch() # Will timeout after 5 seconds

399

print(f"Key pressed: {key}")

400

except TimeoutException:

401

print("Timed out waiting for input")

402

"""

403

```

404

405

## Usage Examples

406

407

### Basic Terminal Operations

408

409

```python

410

import pytermgui as ptg

411

412

# Get terminal info

413

term = ptg.get_terminal()

414

width, height = term.size

415

print(f"Terminal: {width}x{height}")

416

417

# Clear screen and position cursor

418

ptg.clear()

419

ptg.move_cursor((10, 5))

420

print("Text at position (10, 5)")

421

422

# Hide cursor during updates

423

ptg.hide_cursor()

424

# ... update display

425

ptg.show_cursor()

426

```

427

428

### Input Handling

429

430

```python

431

import pytermgui as ptg

432

433

# Simple input loop

434

while True:

435

key = ptg.getch()

436

437

if key == ptg.keys.ESCAPE:

438

break

439

elif key == ptg.keys.UP:

440

print("Up arrow pressed")

441

elif key == ptg.keys.CTRL_C:

442

break

443

else:

444

print(f"Key pressed: {key}")

445

```

446

447

### Input with Timeout

448

449

```python

450

import pytermgui as ptg

451

452

# Wait for input with timeout

453

try:

454

with ptg.timeout(5.0):

455

key = ptg.getch()

456

print(f"Key pressed: {key}")

457

except TimeoutError:

458

print("No input received within 5 seconds")

459

```

460

461

### Alternate Screen Buffer

462

463

```python

464

import pytermgui as ptg

465

466

# Use alternate screen for full-screen app

467

with ptg.alt_buffer():

468

ptg.clear()

469

print("This is in the alternate buffer")

470

ptg.getch() # Wait for key

471

# Automatically returns to main buffer

472

```

473

474

### Screen Recording

475

476

```python

477

import pytermgui as ptg

478

479

# Record terminal output

480

recorder = ptg.terminal.record()

481

482

print("This output will be recorded")

483

ptg.move_cursor((5, 5))

484

print("More recorded output")

485

486

content = recorder.stop()

487

recorder.save("session.txt")

488

```

489

490

### Mouse Event Handling

491

492

```python

493

import pytermgui as ptg

494

495

with ptg.mouse_handler():

496

while True:

497

key = ptg.getch()

498

499

if isinstance(key, ptg.MouseEvent):

500

action = key.action

501

x, y = key.position

502

print(f"Mouse {action} at ({x}, {y})")

503

elif key == ptg.keys.ESCAPE:

504

break

505

```