or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

Files

docs

arguments.mdcolored-text.mdenglish.mdindex.mdprogress.mdprompts.mdresources.mdtext-output.mdutilities.mdvalidation.md

colored-text.mddocs/

0

# Colored Text

1

2

Rich colored text output with automatic TTY detection and cross-platform terminal color support. Provides color functions and ColoredString class that maintains color information while supporting standard string operations and intelligent color output based on terminal capabilities.

3

4

## Capabilities

5

6

### Color Functions

7

8

Create colored text with support for different colors, bold styling, and forced color output.

9

10

```python { .api }

11

def black(string, always=False, bold=False):

12

"""

13

Returns black ColoredString.

14

15

Parameters:

16

- string: str, text to color

17

- always: bool, force color even when not TTY (default: False)

18

- bold: bool, make text bold (default: False)

19

20

Returns:

21

ColoredString: colored string object

22

"""

23

24

def red(string, always=False, bold=False):

25

"""

26

Returns red ColoredString.

27

28

Parameters:

29

- string: str, text to color

30

- always: bool, force color even when not TTY (default: False)

31

- bold: bool, make text bold (default: False)

32

33

Returns:

34

ColoredString: colored string object

35

"""

36

37

def green(string, always=False, bold=False):

38

"""

39

Returns green ColoredString.

40

41

Parameters:

42

- string: str, text to color

43

- always: bool, force color even when not TTY (default: False)

44

- bold: bool, make text bold (default: False)

45

46

Returns:

47

ColoredString: colored string object

48

"""

49

50

def yellow(string, always=False, bold=False):

51

"""

52

Returns yellow ColoredString.

53

54

Parameters:

55

- string: str, text to color

56

- always: bool, force color even when not TTY (default: False)

57

- bold: bool, make text bold (default: False)

58

59

Returns:

60

ColoredString: colored string object

61

"""

62

63

def blue(string, always=False, bold=False):

64

"""

65

Returns blue ColoredString.

66

67

Parameters:

68

- string: str, text to color

69

- always: bool, force color even when not TTY (default: False)

70

- bold: bool, make text bold (default: False)

71

72

Returns:

73

ColoredString: colored string object

74

"""

75

76

def magenta(string, always=False, bold=False):

77

"""

78

Returns magenta ColoredString.

79

80

Parameters:

81

- string: str, text to color

82

- always: bool, force color even when not TTY (default: False)

83

- bold: bool, make text bold (default: False)

84

85

Returns:

86

ColoredString: colored string object

87

"""

88

89

def cyan(string, always=False, bold=False):

90

"""

91

Returns cyan ColoredString.

92

93

Parameters:

94

- string: str, text to color

95

- always: bool, force color even when not TTY (default: False)

96

- bold: bool, make text bold (default: False)

97

98

Returns:

99

ColoredString: colored string object

100

"""

101

102

def white(string, always=False, bold=False):

103

"""

104

Returns white ColoredString.

105

106

Parameters:

107

- string: str, text to color

108

- always: bool, force color even when not TTY (default: False)

109

- bold: bool, make text bold (default: False)

110

111

Returns:

112

ColoredString: colored string object

113

"""

114

```

115

116

### ColoredString Class

117

118

Enhanced string class that maintains color information while supporting all standard string operations.

119

120

```python { .api }

121

class ColoredString:

122

def __init__(self, color, s, always_color=False, bold=False):

123

"""

124

Enhanced string for colored output with string operation compatibility.

125

126

Parameters:

127

- color: str, color name (e.g., 'RED', 'GREEN', 'BLUE')

128

- s: str, the actual string content

129

- always_color: bool, force color output regardless of TTY (default: False)

130

- bold: bool, make text bold (default: False)

131

"""

132

133

def __len__(self):

134

"""Return length of the underlying string (ignoring color codes)."""

135

136

def __str__(self):

137

"""Return colored string or plain string based on terminal capabilities."""

138

139

def __add__(self, other):

140

"""Concatenate with another string, preserving color."""

141

142

def __mul__(self, other):

143

"""Multiply string content, preserving color."""

144

145

def __repr__(self):

146

"""Return string representation for debugging."""

147

148

def __unicode__(self):

149

"""Return unicode string representation (Python 2/3 compatibility)."""

150

151

def __iter__(self):

152

"""Enable iteration over the underlying string."""

153

154

def __radd__(self, other):

155

"""Support right-hand addition with other strings."""

156

157

def __getattr__(self, att):

158

"""

159

Proxy all string methods to the underlying string while preserving color.

160

161

This enables ColoredString to support all string methods like .upper(),

162

.lower(), .split(), etc. while maintaining color information.

163

164

Parameters:

165

- att: str, attribute/method name to proxy

166

167

Returns:

168

ColoredString or result of string method

169

"""

170

171

@property

172

def color_str(self):

173

"""

174

Returns the actual colored string with ANSI escape codes.

175

176

Returns:

177

str: string with ANSI color codes applied

178

"""

179

```

180

181

### Utility Functions

182

183

Functions for color management and string cleaning.

184

185

```python { .api }

186

def clean(s):

187

"""

188

Strips ANSI color codes and special characters from string.

189

190

Parameters:

191

- s: str or ColoredString, string to clean

192

193

Returns:

194

str: cleaned string without color codes

195

"""

196

197

def disable():

198

"""

199

Disables colors globally.

200

Sets global DISABLE_COLOR flag to prevent color output.

201

"""

202

```

203

204

## Advanced Features

205

206

### Automatic Environment Detection

207

208

- **TTY Detection**: Colors are automatically disabled when output is not a TTY (e.g., when piping to files)

209

- **iPython Detection**: Colors are automatically disabled when running in iPython environments

210

- **CLINT_FORCE_COLOR**: Set environment variable `CLINT_FORCE_COLOR=1` to force colors even in non-TTY environments

211

212

### String Method Proxying

213

214

ColoredString objects support all standard string methods through the `__getattr__` method:

215

216

```python

217

colored_text = red("Hello World")

218

print(colored_text.upper()) # Returns RED "HELLO WORLD"

219

print(colored_text.split()) # Returns list with RED "Hello" and RED "World"

220

print(len(colored_text)) # Returns 11 (ignoring ANSI codes)

221

```

222

223

### Public API Status

224

225

Note: `ColoredString` is not included in the module's `__all__` declaration but is used throughout the codebase and should be considered part of the public API for type annotations and advanced usage.

226

227

## Usage Examples

228

229

```python

230

from clint.textui import puts

231

from clint.textui.colored import red, green, blue, yellow, clean

232

233

# Basic colored output

234

puts(red('This is red text'))

235

puts(green('This is green text'))

236

puts(blue('This is blue text', bold=True))

237

238

# Force color output (useful for logging/piping)

239

puts(red('Always red', always=True))

240

241

# String operations work with colored strings

242

colored_text = red('Hello')

243

result = colored_text + ' ' + blue('World')

244

puts(result) # "Hello World" with colors preserved

245

246

# Multiplication

247

puts(red('-') * 20) # Red dashes

248

249

# Length operations (ignores color codes)

250

text = red('Hello')

251

print(len(text)) # 5, not including ANSI codes

252

253

# Clean color codes from strings

254

dirty_text = red('Colored text')

255

clean_text = clean(dirty_text)

256

print(clean_text) # "Colored text" without color codes

257

258

# Mix with indentation and other formatting

259

from clint.textui import indent

260

261

puts("Status messages:")

262

with indent(2):

263

puts(green('✓ Success: Operation completed'))

264

puts(yellow('⚠ Warning: Minor issue detected'))

265

puts(red('✗ Error: Operation failed'))

266

```

267

268

## Advanced Usage

269

270

```python

271

from clint.textui.colored import ColoredString, disable

272

import os

273

274

# Direct ColoredString usage

275

custom_colored = ColoredString('CYAN', 'Custom colored text', bold=True)

276

puts(custom_colored)

277

278

# Environment variable control

279

# Set CLINT_FORCE_COLOR=1 to force colors in non-TTY environments

280

os.environ['CLINT_FORCE_COLOR'] = '1'

281

puts(red('This will be colored even when piped'))

282

283

# Disable colors globally

284

disable()

285

puts(red('This will not be colored'))

286

287

# Complex formatting with colors

288

def status_report(items):

289

puts(blue('Status Report', bold=True))

290

puts(blue('=' * 20))

291

292

for item, status in items:

293

if status == 'success':

294

puts(f" {green('✓')} {item}")

295

elif status == 'warning':

296

puts(f" {yellow('⚠')} {item}")

297

else:

298

puts(f" {red('✗')} {item}")

299

300

# Usage

301

items = [

302

('Database connection', 'success'),

303

('Cache system', 'warning'),

304

('External API', 'error')

305

]

306

status_report(items)

307

```

308

309

## TTY Detection and Color Control

310

311

Clint automatically detects terminal capabilities:

312

313

- **TTY Detection**: Colors are automatically disabled when output is piped or redirected

314

- **Environment Control**: Set `CLINT_FORCE_COLOR=1` to force colors in non-TTY environments

315

- **Global Disable**: Use `disable()` function to turn off colors entirely

316

- **iPython Detection**: Colors are automatically disabled in iPython environments

317

318

```python

319

import sys

320

from clint.textui.colored import red

321

322

# This will be colored in terminal, plain when piped

323

puts(red('Status message'))

324

325

# This will always be colored

326

puts(red('Status message', always=True))

327

328

# Check if output is going to terminal

329

if sys.stdout.isatty():

330

puts("Output is going to terminal")

331

else:

332

puts("Output is being piped or redirected")

333

```