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

utilities.mddocs/

0

# Utilities and Helpers

1

2

PyTermGUI provides a comprehensive set of utility functions for text processing, debugging, prettification, syntax highlighting, and development tools that enhance the framework's capabilities and developer experience.

3

4

## Capabilities

5

6

### Text Processing

7

8

Text manipulation utilities for handling markup, ANSI sequences, and display calculations.

9

10

```python { .api }

11

def strip_ansi(text: str) -> str:

12

"""

13

Remove ANSI escape sequences from text.

14

15

Parameters:

16

- text (str): Text containing ANSI sequences

17

18

Returns:

19

Plain text with ANSI sequences removed

20

"""

21

22

def strip_markup(text: str) -> str:

23

"""

24

Remove TIM markup tags from text.

25

26

Parameters:

27

- text (str): Text containing TIM markup

28

29

Returns:

30

Plain text with markup removed

31

"""

32

33

def escape_markup(text: str) -> str:

34

"""

35

Escape TIM markup characters in text.

36

37

Parameters:

38

- text (str): Text to escape

39

40

Returns:

41

Text with markup characters escaped

42

"""

43

44

def real_length(text: str) -> int:

45

"""

46

Get display length of text excluding formatting.

47

48

Parameters:

49

- text (str): Text with possible markup/ANSI

50

51

Returns:

52

Actual display width of text

53

"""

54

55

def break_line(text: str, width: int, **kwargs) -> list[str]:

56

"""

57

Break text into lines fitting specified width.

58

59

Parameters:

60

- text (str): Text to break

61

- width (int): Maximum line width

62

- **kwargs: Additional breaking options

63

64

Returns:

65

List of text lines

66

"""

67

```

68

69

### Pretty Printing

70

71

Enhanced object display and prettification tools for development and debugging.

72

73

```python { .api }

74

def pprint(*items, indent: int = 2, **kwargs):

75

"""

76

Pretty print objects with PyTermGUI formatting.

77

78

Parameters:

79

- items: Objects to print

80

- indent (int): Indentation level

81

- **kwargs: Additional formatting options

82

"""

83

84

def install():

85

"""Install pprint as default print function."""

86

87

def prettify(obj) -> str:

88

"""

89

Prettify object for display.

90

91

Parameters:

92

- obj: Object to prettify

93

94

Returns:

95

Formatted string representation

96

"""

97

```

98

99

### Syntax Highlighting

100

101

Code syntax highlighting with customizable highlighters and built-in language support.

102

103

```python { .api }

104

class Highlighter:

105

"""Base syntax highlighter."""

106

107

def __init__(self):

108

"""Initialize highlighter."""

109

110

def highlight(self, text: str) -> str:

111

"""

112

Apply syntax highlighting to text.

113

114

Parameters:

115

- text (str): Source code to highlight

116

117

Returns:

118

Text with TIM markup for syntax colors

119

"""

120

121

class RegexHighlighter(Highlighter):

122

"""Regex-based syntax highlighter."""

123

124

def __init__(self, patterns: dict[str, str]):

125

"""

126

Create regex highlighter.

127

128

Parameters:

129

- patterns (dict): Mapping of regex patterns to TIM styles

130

"""

131

132

def add_pattern(self, name: str, pattern: str, style: str):

133

"""Add highlighting pattern."""

134

135

def highlight_python(text: str) -> str:

136

"""

137

Highlight Python code syntax.

138

139

Parameters:

140

- text (str): Python source code

141

142

Returns:

143

Code with syntax highlighting markup

144

"""

145

146

def highlight_tim(text: str) -> str:

147

"""

148

Highlight TIM markup syntax.

149

150

Parameters:

151

- text (str): TIM markup text

152

153

Returns:

154

Markup with syntax highlighting

155

"""

156

```

157

158

### Inspector

159

160

Interactive object inspection tool for debugging and exploration.

161

162

```python { .api }

163

class Inspector(Container):

164

"""Interactive object inspection widget for any Python object."""

165

166

def __init__(self, target: object = None, show_private: bool = False,

167

show_dunder: bool = False, show_methods: bool = False,

168

show_full_doc: bool = False, show_qualname: bool = True,

169

show_header: bool = True, **attrs):

170

"""

171

Initialize inspector widget.

172

173

Parameters:

174

- target: Object to inspect

175

- show_private (bool): Whether _private attributes should be shown

176

- show_dunder (bool): Whether __dunder__ attributes should be shown

177

- show_methods (bool): Whether methods should be shown for classes

178

- show_full_doc (bool): Show full docstrings vs first line only

179

- show_qualname (bool): Show fully-qualified names

180

- show_header (bool): Show header with path and qualname

181

"""

182

183

def inspect(self, target: object) -> "Inspector":

184

"""

185

Inspect new target object.

186

187

Parameters:

188

- target: Object to inspect

189

190

Returns:

191

Updated Inspector instance

192

"""

193

194

def inspect(target: object, **inspector_args) -> Inspector:

195

"""

196

Create inspector widget for object with smart defaults.

197

198

Parameters:

199

- target: Object to inspect

200

- **inspector_args: Arguments passed to Inspector constructor

201

202

Returns:

203

Inspector widget configured for the target type

204

205

Automatically sets appropriate defaults based on target type:

206

- Modules: Hide dunder/private, show methods

207

- Classes: Hide dunder/private, show full docs and methods

208

- Functions: Show full docs and qualname

209

"""

210

```

211

212

### Export System

213

214

Export terminal content to various formats for documentation and sharing.

215

216

```python { .api }

217

def to_html(content: str, title: str = "Terminal Output") -> str:

218

"""

219

Export terminal content to HTML.

220

221

Parameters:

222

- content (str): Terminal content with ANSI/markup

223

- title (str): HTML document title

224

225

Returns:

226

Complete HTML document with styled content

227

"""

228

229

def token_to_css(token) -> str:

230

"""

231

Convert markup token to CSS styles.

232

233

Parameters:

234

- token: Markup token to convert

235

236

Returns:

237

CSS style string

238

"""

239

```

240

241

### Exception Types

242

243

Framework-specific exception classes for error handling.

244

245

```python { .api }

246

class TimeoutException(Exception):

247

"""Raised when an action has timed out."""

248

249

class WidthExceededError(Exception):

250

"""Raised when an element's width is larger than the screen."""

251

252

class LineLengthError(Exception):

253

"""Raised when a widget line is not the expected length."""

254

255

class ColorSyntaxError(Exception):

256

"""Raised when a color string could not be parsed into a Color."""

257

258

class ParserSyntaxError(Exception):

259

"""Parent exception for unparsable strings."""

260

261

def __init__(self, tag: str, cause: str, context: str):

262

"""

263

Create parser syntax error.

264

265

Parameters:

266

- tag (str): The problematic tag

267

- cause (str): Description of the error

268

- context (str): Context string where error occurred

269

"""

270

271

@property

272

def message(self) -> str:

273

"""Create formatted error message from tag, context and cause."""

274

275

def escape_message(self) -> str:

276

"""Return message with markup tags escaped."""

277

278

class MarkupSyntaxError(ParserSyntaxError):

279

"""Raised when parsed markup text contains an error."""

280

281

class AnsiSyntaxError(ParserSyntaxError):

282

"""Raised when parsed ANSI text contains an error."""

283

```

284

285

### Fancy Repr System

286

287

Protocol for enhanced object representation with TIM formatting.

288

289

```python { .api }

290

class SupportsFancyRepr:

291

"""Protocol for objects supporting fancy representation."""

292

293

def __fancy_repr__(self) -> str:

294

"""Return fancy representation with TIM markup."""

295

296

def supports_fancy_repr(obj) -> bool:

297

"""

298

Check if object supports fancy repr protocol.

299

300

Parameters:

301

- obj: Object to check

302

303

Returns:

304

True if object has __fancy_repr__ method

305

"""

306

307

def build_fancy_repr(obj) -> str:

308

"""

309

Build fancy representation for object.

310

311

Parameters:

312

- obj: Object to represent

313

314

Returns:

315

Formatted representation with TIM markup

316

"""

317

```

318

319

### Context Managers

320

321

Utility context managers for common terminal operations.

322

323

```python { .api }

324

def timeout(duration: float):

325

"""

326

Context manager for operations with timeout.

327

328

Parameters:

329

- duration (float): Timeout in seconds

330

"""

331

332

def alt_buffer():

333

"""Context manager for alternate screen buffer."""

334

335

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

336

"""

337

Context manager for cursor positioning.

338

339

Parameters:

340

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

341

"""

342

343

def mouse_handler():

344

"""Context manager for mouse event handling."""

345

```

346

347

## Usage Examples

348

349

### Text Processing

350

351

```python

352

import pytermgui as ptg

353

354

# Process text with markup and ANSI

355

marked_text = "[bold red]Error:[/red bold] Something went wrong"

356

ansi_text = "\033[1;31mError:\033[0m Something went wrong"

357

358

# Remove formatting

359

plain1 = ptg.strip_markup(marked_text)

360

plain2 = ptg.strip_ansi(ansi_text)

361

362

# Get display width

363

width = ptg.real_length(marked_text)

364

print(f"Display width: {width}")

365

366

# Break long text into lines

367

long_text = "This is a very long line that needs to be broken"

368

lines = ptg.break_line(long_text, width=20)

369

for line in lines:

370

print(f"'{line}'")

371

372

# Escape markup characters

373

user_input = "User said: [hello] and /goodbye/"

374

safe_text = ptg.escape_markup(user_input)

375

```

376

377

### Pretty Printing

378

379

```python

380

import pytermgui as ptg

381

382

# Pretty print complex objects

383

data = {

384

"users": [

385

{"name": "Alice", "age": 30},

386

{"name": "Bob", "age": 25}

387

],

388

"settings": {

389

"theme": "dark",

390

"notifications": True

391

}

392

}

393

394

# Enhanced pretty printing

395

ptg.pprint(data, indent=4)

396

397

# Prettify for string representation

398

formatted = ptg.prettify(data)

399

print(formatted)

400

401

# Install as default print function

402

ptg.install() # Now print() uses ptg.pprint

403

```

404

405

### Syntax Highlighting

406

407

```python

408

import pytermgui as ptg

409

410

# Highlight Python code

411

python_code = """

412

def hello_world():

413

print("Hello, PyTermGUI!")

414

return True

415

"""

416

417

highlighted = ptg.highlight_python(python_code)

418

print(highlighted)

419

420

# Highlight TIM markup

421

markup_example = "[bold red]Error:[/red] [italic]Something happened[/italic]"

422

highlighted_markup = ptg.highlight_tim(markup_example)

423

print(highlighted_markup)

424

425

# Create custom highlighter

426

patterns = {

427

"keywords": (r"\b(if|else|for|while)\b", "[bold blue]"),

428

"strings": (r'"[^"]*"', "[green]"),

429

"numbers": (r'\b\d+\b', "[yellow]")

430

}

431

432

highlighter = ptg.RegexHighlighter(patterns)

433

code = 'if x == 42: print("Found answer")'

434

highlighted_code = highlighter.highlight(code)

435

```

436

437

### Object Inspector

438

439

```python

440

import pytermgui as ptg

441

442

# Create widget to inspect

443

button = ptg.Button("Test Button", lambda: print("Clicked"))

444

445

# Launch interactive inspector

446

ptg.inspect(button)

447

448

# Get inspection info programmatically

449

inspector = ptg.Inspector()

450

info = inspector.get_info(button)

451

print(info)

452

453

# Create inspection widget

454

inspection_widget = inspector.inspect(button)

455

```

456

457

### HTML Export

458

459

```python

460

import pytermgui as ptg

461

462

# Create some terminal content

463

content = ptg.Container(

464

"[bold 210]Terminal Application",

465

"",

466

ptg.Label("[green]Status: [/green][bold]Running"),

467

ptg.Button("Stop", lambda: None),

468

width=40

469

)

470

471

# Export to HTML

472

terminal_output = str(content)

473

html_doc = ptg.to_html(terminal_output, title="App Screenshot")

474

475

# Save to file

476

with open("terminal_output.html", "w") as f:

477

f.write(html_doc)

478

```

479

480

### Error Handling

481

482

```python

483

import pytermgui as ptg

484

485

try:

486

# Create widget with invalid width

487

container = ptg.Container(width=1000) # May exceed terminal

488

container.add(ptg.Label("Very long text that exceeds width"))

489

490

except ptg.WidthExceededError as e:

491

print(f"Width error: {e}")

492

493

try:

494

# Invalid markup

495

label = ptg.Label("[invalid markup")

496

497

except ptg.MarkupSyntaxError as e:

498

print(f"Markup error: {e}")

499

```

500

501

### Fancy Repr Protocol

502

503

```python

504

import pytermgui as ptg

505

506

class CustomWidget(ptg.Widget):

507

"""Widget with fancy representation."""

508

509

def __init__(self, name):

510

super().__init__()

511

self.name = name

512

513

def __fancy_repr__(self) -> str:

514

return f"[bold blue]CustomWidget[/blue]([yellow]{self.name}[/yellow])"

515

516

# Usage

517

widget = CustomWidget("MyWidget")

518

519

# Check if supports fancy repr

520

if ptg.supports_fancy_repr(widget):

521

fancy_str = ptg.build_fancy_repr(widget)

522

print(fancy_str)

523

```

524

525

### Development Utilities

526

527

```python

528

import pytermgui as ptg

529

530

# Debug widget hierarchy

531

def debug_widget_tree(widget, indent=0):

532

"""Print widget hierarchy."""

533

spacing = " " * indent

534

widget_type = type(widget).__name__

535

widget_id = getattr(widget, 'id', 'no-id')

536

537

print(f"{spacing}{widget_type} (id: {widget_id})")

538

539

if hasattr(widget, 'widgets'):

540

for child in widget.widgets:

541

debug_widget_tree(child, indent + 1)

542

543

# Usage

544

container = ptg.Container(

545

ptg.Label("Title", id="title"),

546

ptg.Button("Click", id="button"),

547

id="main-container"

548

)

549

550

debug_widget_tree(container)

551

```