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

colors-markup.mddocs/

0

# Colors and Markup

1

2

PyTermGUI provides comprehensive color management and a powerful markup language (TIM - Terminal Inline Markup) for rich text formatting. The system supports RGB, HEX, indexed terminal colors, and palette generation.

3

4

## Capabilities

5

6

### Color System

7

8

PyTermGUI's color system provides full support for terminal colors including RGB, HEX, indexed colors, and automatic terminal compatibility.

9

10

```python { .api }

11

class Color:

12

"""Base color class with terminal conversion."""

13

14

def __init__(self, value: str | int | tuple):

15

"""

16

Create color from various formats.

17

18

Parameters:

19

- value: Color specification (hex string, RGB tuple, color name, etc.)

20

"""

21

22

@property

23

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

24

"""Get RGB values as (r, g, b) tuple."""

25

26

def hex(self) -> str:

27

"""Get hexadecimal color representation."""

28

29

def __str__(self) -> str:

30

"""Get ANSI escape sequence for foreground."""

31

32

def as_background(self) -> str:

33

"""Get ANSI escape sequence for background."""

34

35

class RGBColor(Color):

36

"""True RGB color support."""

37

38

def __init__(self, red: int, green: int, blue: int):

39

"""

40

Create RGB color.

41

42

Parameters:

43

- red (int): Red component (0-255)

44

- green (int): Green component (0-255)

45

- blue (int): Blue component (0-255)

46

"""

47

48

class HEXColor(RGBColor):

49

"""Hexadecimal color support."""

50

51

def __init__(self, hex_value: str):

52

"""

53

Create color from hex string.

54

55

Parameters:

56

- hex_value (str): Hex color code ('#FF0000' or 'FF0000')

57

"""

58

59

class IndexedColor(Color):

60

"""256-color indexed terminal colors."""

61

62

def __init__(self, index: int):

63

"""

64

Create indexed color.

65

66

Parameters:

67

- index (int): Color index (0-255)

68

"""

69

70

class StandardColor(IndexedColor):

71

"""Standard 16-color terminal colors."""

72

73

class GreyscaleRampColor(IndexedColor):

74

"""Greyscale color ramp."""

75

```

76

77

### Color Utilities

78

79

Helper functions for color parsing and text formatting.

80

81

```python { .api }

82

def str_to_color(color_str: str) -> Color:

83

"""

84

Parse color string into Color object.

85

86

Parameters:

87

- color_str (str): Color specification (name, hex, rgb, etc.)

88

89

Returns:

90

Color object

91

92

Supports formats:

93

- Named colors: 'red', 'blue', 'green'

94

- Hex colors: '#FF0000', 'ff0000'

95

- RGB tuples: '(255, 0, 0)'

96

- Indexed colors: '196', '@196'

97

"""

98

99

def foreground(text: str, color: str | Color, reset: bool = True) -> str:

100

"""

101

Apply foreground color to text.

102

103

Parameters:

104

- text (str): Text to colorize

105

- color: Color specification

106

- reset (bool): Whether to add reset sequence

107

108

Returns:

109

Colored text with ANSI sequences

110

"""

111

112

def background(text: str, color: str | Color, reset: bool = True) -> str:

113

"""

114

Apply background color to text.

115

116

Parameters:

117

- text (str): Text to colorize

118

- color: Color specification

119

- reset (bool): Whether to add reset sequence

120

121

Returns:

122

Text with background color ANSI sequences

123

"""

124

125

def clear_color_cache() -> None:

126

"""Clear color conversion cache."""

127

```

128

129

### Color Palettes

130

131

Color palette generation and management for cohesive color schemes.

132

133

```python { .api }

134

class Palette:

135

"""Color palette management."""

136

137

def __init__(self, **colors):

138

"""

139

Create color palette.

140

141

Parameters:

142

- colors: Named color mappings

143

"""

144

145

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

146

"""Get color by name."""

147

148

def set(self, key: str, color: Color):

149

"""Set named color."""

150

151

def triadic(base: Color) -> tuple[Color, Color, Color, Color]:

152

"""

153

Generate triadic color scheme.

154

155

Parameters:

156

- base (Color): Base color for scheme

157

158

Returns:

159

Tuple of (base, complement1, complement2, accent)

160

"""

161

162

def analogous(base: Color) -> tuple[Color, Color, Color, Color]:

163

"""

164

Generate analogous color scheme.

165

166

Parameters:

167

- base (Color): Base color for scheme

168

169

Returns:

170

Tuple of related colors

171

"""

172

173

# Global palette instance

174

palette: Palette

175

```

176

177

### TIM Markup Language

178

179

Terminal Inline Markup (TIM) provides rich text formatting with colors, styles, and layout control.

180

181

```python { .api }

182

class MarkupLanguage:

183

"""TIM markup parser and processor."""

184

185

def __init__(self):

186

"""Initialize markup language processor."""

187

188

def parse(self, text: str) -> list[Token]:

189

"""

190

Parse markup text into tokens.

191

192

Parameters:

193

- text (str): Text with TIM markup

194

195

Returns:

196

List of parsed tokens

197

"""

198

199

def apply(self, text: str, **context) -> str:

200

"""

201

Apply markup formatting to text.

202

203

Parameters:

204

- text (str): Text with markup

205

- context: Markup context variables

206

207

Returns:

208

Formatted text with ANSI sequences

209

"""

210

211

class StyledText:

212

"""Styled text representation."""

213

214

def __init__(self, text: str):

215

"""

216

Create styled text.

217

218

Parameters:

219

- text (str): Text with markup

220

"""

221

222

def __str__(self) -> str:

223

"""Get formatted text output."""

224

225

@property

226

def plain(self) -> str:

227

"""Get plain text without formatting."""

228

229

def escape(text: str) -> str:

230

"""

231

Escape TIM markup characters in text.

232

233

Parameters:

234

- text (str): Text to escape

235

236

Returns:

237

Text with escaped markup characters

238

"""

239

240

# Global TIM instance

241

tim: MarkupLanguage

242

```

243

244

### Markup Tokens

245

246

Token classes representing different markup elements.

247

248

```python { .api }

249

class Token:

250

"""Base markup token."""

251

252

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

253

"""Apply token formatting."""

254

255

class PlainToken(Token):

256

"""Plain text token."""

257

258

class StyleToken(Token):

259

"""Style application token (bold, italic, etc.)."""

260

261

class ColorToken(Token):

262

"""Color application token."""

263

264

class ResetToken(Token):

265

"""Style reset token."""

266

267

class ClearScreenToken(Token):

268

"""Screen clear token."""

269

```

270

271

### Markup Parsing

272

273

Low-level markup parsing utilities.

274

275

```python { .api }

276

def tokenize_markup(text: str) -> list[Token]:

277

"""

278

Tokenize markup text.

279

280

Parameters:

281

- text (str): Text with TIM markup

282

283

Returns:

284

List of markup tokens

285

"""

286

287

def tokenize_ansi(text: str) -> list[Token]:

288

"""

289

Tokenize ANSI escape sequences.

290

291

Parameters:

292

- text (str): Text with ANSI sequences

293

294

Returns:

295

List of ANSI tokens

296

"""

297

298

def consume_tag(text: str, pos: int) -> tuple[Token, int]:

299

"""

300

Parse single markup tag.

301

302

Parameters:

303

- text (str): Source text

304

- pos (int): Current position

305

306

Returns:

307

Tuple of (token, new_position)

308

"""

309

310

def create_context_dict(**kwargs) -> dict:

311

"""Create markup context dictionary."""

312

313

type ContextDict = dict[str, Any]

314

```

315

316

## Color Constants

317

318

```python { .api }

319

# Pre-defined color lookup tables

320

COLOR_TABLE: dict[int, tuple[int, int, int]]

321

XTERM_NAMED_COLORS: dict[str, int]

322

NAMED_COLORS: dict[str, str]

323

```

324

325

## Usage Examples

326

327

### Basic Color Usage

328

329

```python

330

import pytermgui as ptg

331

332

# Create colors different ways

333

red = ptg.Color('red')

334

blue = ptg.HEXColor('#0066CC')

335

green = ptg.RGBColor(0, 255, 0)

336

337

# Apply colors to text

338

colored_text = ptg.foreground("Hello", red)

339

bg_text = ptg.background("World", blue)

340

341

print(colored_text, bg_text)

342

```

343

344

### TIM Markup Examples

345

346

```python

347

import pytermgui as ptg

348

349

# Basic markup formatting

350

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

351

formatted = ptg.tim.parse(markup_text)

352

353

# Widget with markup

354

label = ptg.Label("[210 bold]Welcome to [/bold][157]PyTermGUI[/157]")

355

356

# Complex markup with colors and styles

357

title = ptg.Label("""

358

[bold 210]╔══════════════════╗

359

[bold 210]║ [/210][bold 157]Application Title[/157][bold 210] ║

360

[bold 210]╚══════════════════╝[/210 bold]

361

""")

362

```

363

364

### Color Palette Usage

365

366

```python

367

import pytermgui as ptg

368

369

# Generate color schemes

370

base_color = ptg.Color('#3366CC')

371

triadic_colors = ptg.triadic(base_color)

372

analogous_colors = ptg.analogous(base_color)

373

374

# Create custom palette

375

my_palette = ptg.Palette(

376

primary='#3366CC',

377

secondary='#66CC33',

378

accent='#CC3366',

379

background='#2D2D2D',

380

text='#FFFFFF'

381

)

382

383

# Use palette colors

384

button = ptg.Button(

385

f"[{my_palette['primary']}]Click Me[/]",

386

onclick=my_handler

387

)

388

```

389

390

### Text Processing

391

392

```python

393

import pytermgui as ptg

394

395

# Strip formatting

396

plain_text = ptg.strip_markup("[bold red]Hello[/red bold]")

397

no_ansi = ptg.strip_ansi("\033[1;31mHello\033[0m")

398

399

# Measure display width

400

display_width = ptg.real_length("[bold]Hello World[/bold]")

401

402

# Escape markup characters

403

safe_text = ptg.escape("Text with [brackets] and /slashes/")

404

```