or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

Files

docs

console.mdcontainers.mdindex.mdinteractive.mdlayout.mdmarkdown.mdprogress.mdsyntax.mdtables.mdtext-styling.mdutilities.md

text-styling.mddocs/

0

# Text and Styling

1

2

Advanced text objects with precise styling control, markup support, and comprehensive formatting options. Rich provides powerful text handling with styled spans, color support, and flexible rendering capabilities.

3

4

## Capabilities

5

6

### Text Class

7

8

Rich text objects with styling spans and advanced formatting capabilities.

9

10

```python { .api }

11

class Text:

12

"""

13

Styled text with Rich formatting capabilities.

14

15

Args:

16

text: Plain text content

17

style: Default style for the text

18

justify: Text justification method

19

overflow: Overflow handling method

20

no_wrap: Disable text wrapping

21

end: String to append at end

22

tab_size: Size of tab characters

23

spans: List of styled spans

24

"""

25

def __init__(

26

self,

27

text: str = "",

28

style: StyleType = "",

29

*,

30

justify: Optional[JustifyMethod] = None,

31

overflow: OverflowMethod = "fold",

32

no_wrap: Optional[bool] = None,

33

end: str = "\n",

34

tab_size: Optional[int] = 8,

35

spans: Optional[List[Span]] = None,

36

): ...

37

38

def stylize(

39

self,

40

style: StyleType,

41

start: int = 0,

42

end: Optional[int] = None,

43

) -> None:

44

"""

45

Apply style to a range of text.

46

47

Args:

48

style: Style to apply

49

start: Start character index

50

end: End character index or None for end of text

51

"""

52

53

def stylize_range(

54

self,

55

style: StyleType,

56

start: int = 0,

57

end: Optional[int] = None,

58

) -> None:

59

"""

60

Apply style to a range of text (alias for stylize).

61

62

Args:

63

style: Style to apply

64

start: Start character index

65

end: End character index or None for end of text

66

"""

67

68

def stylize_before(

69

self,

70

style: StyleType,

71

start: int = 0,

72

end: Optional[int] = None,

73

) -> "Text":

74

"""

75

Apply style before existing styles in a range.

76

77

Args:

78

style: Style to apply

79

start: Start character index

80

end: End character index or None for end of text

81

82

Returns:

83

New Text instance with applied style

84

"""

85

86

def stylize_after(

87

self,

88

style: StyleType,

89

start: int = 0,

90

end: Optional[int] = None,

91

) -> "Text":

92

"""

93

Apply style after existing styles in a range.

94

95

Args:

96

style: Style to apply

97

start: Start character index

98

end: End character index or None for end of text

99

100

Returns:

101

New Text instance with applied style

102

"""

103

104

def highlight_words(

105

self,

106

words: Iterable[str],

107

style: StyleType,

108

*,

109

case_sensitive: bool = True,

110

) -> int:

111

"""

112

Highlight specific words in the text.

113

114

Args:

115

words: Words to highlight

116

style: Style to apply to highlighted words

117

case_sensitive: Enable case-sensitive matching

118

119

Returns:

120

Number of words highlighted

121

"""

122

123

def highlight_regex(

124

self,

125

re_highlight: Union[str, Pattern[str]],

126

style: Optional[StyleType] = None,

127

*,

128

style_prefix: str = "",

129

) -> int:

130

"""

131

Highlight text matching a regular expression.

132

133

Args:

134

re_highlight: Regular expression pattern

135

style: Style to apply or None to use groups

136

style_prefix: Prefix for group-based style names

137

138

Returns:

139

Number of matches highlighted

140

"""

141

142

def append(

143

self,

144

text: Union[str, "Text"],

145

style: Optional[StyleType] = None,

146

) -> "Text":

147

"""

148

Append text with optional styling.

149

150

Args:

151

text: Text to append

152

style: Style to apply to appended text

153

154

Returns:

155

Self for method chaining

156

"""

157

158

def copy(self) -> "Text":

159

"""

160

Create a copy of this text object.

161

162

Returns:

163

New Text instance with same content and styles

164

"""

165

166

def copy_styles(self, text: "Text") -> None:

167

"""

168

Copy styles from another text object.

169

170

Args:

171

text: Text object to copy styles from

172

"""

173

174

def split(

175

self,

176

separator: str = "\n",

177

*,

178

include_separator: bool = False,

179

allow_blank: bool = True,

180

) -> List["Text"]:

181

"""

182

Split text by separator.

183

184

Args:

185

separator: String to split on

186

include_separator: Include separator in results

187

allow_blank: Allow blank strings in results

188

189

Returns:

190

List of Text objects

191

"""

192

193

def divide(

194

self, offsets: Iterable[int]

195

) -> List["Text"]:

196

"""

197

Divide text at specific character offsets.

198

199

Args:

200

offsets: Character positions to split at

201

202

Returns:

203

List of Text objects

204

"""

205

206

def right_crop(self, amount: int = 1) -> "Text":

207

"""

208

Remove characters from the right.

209

210

Args:

211

amount: Number of characters to remove

212

213

Returns:

214

New Text with characters removed

215

"""

216

217

def truncate(

218

self,

219

max_width: int,

220

*,

221

overflow: OverflowMethod = "fold",

222

pad: bool = False,

223

) -> None:

224

"""

225

Truncate text to maximum width.

226

227

Args:

228

max_width: Maximum width in characters

229

overflow: Overflow handling method

230

pad: Pad to exact width with spaces

231

"""

232

233

def pad_left(self, count: int, character: str = " ") -> "Text":

234

"""

235

Add padding to the left.

236

237

Args:

238

count: Number of characters to add

239

character: Character to use for padding

240

241

Returns:

242

New Text with padding

243

"""

244

245

def pad_right(self, count: int, character: str = " ") -> "Text":

246

"""

247

Add padding to the right.

248

249

Args:

250

count: Number of characters to add

251

character: Character to use for padding

252

253

Returns:

254

New Text with padding

255

"""

256

257

def align(self, align: AlignMethod, width: int, character: str = " ") -> "Text":

258

"""

259

Align text within a given width.

260

261

Args:

262

align: Alignment method

263

width: Total width

264

character: Character to use for padding

265

266

Returns:

267

New aligned Text

268

"""

269

270

def strip(self, characters: Optional[str] = None) -> "Text":

271

"""

272

Strip characters from both ends.

273

274

Args:

275

characters: Characters to strip or None for whitespace

276

277

Returns:

278

New Text with characters stripped

279

"""

280

281

def rstrip(self, characters: Optional[str] = None) -> "Text":

282

"""

283

Strip characters from the right end.

284

285

Args:

286

characters: Characters to strip or None for whitespace

287

288

Returns:

289

New Text with characters stripped

290

"""

291

292

def lstrip(self, characters: Optional[str] = None) -> "Text":

293

"""

294

Strip characters from the left end.

295

296

Args:

297

characters: Characters to strip or None for whitespace

298

299

Returns:

300

New Text with characters stripped

301

"""

302

303

def expand_tabs(self, tab_size: Optional[int] = None) -> "Text":

304

"""

305

Expand tab characters to spaces.

306

307

Args:

308

tab_size: Size of tabs or None to use default

309

310

Returns:

311

New Text with tabs expanded

312

"""

313

314

def replace(

315

self,

316

old: str,

317

new: Union[str, "Text"],

318

count: int = -1,

319

) -> "Text":

320

"""

321

Replace occurrences of a substring.

322

323

Args:

324

old: Substring to replace

325

new: Replacement text

326

count: Maximum replacements or -1 for all

327

328

Returns:

329

New Text with replacements

330

"""

331

332

@classmethod

333

def from_markup(

334

cls,

335

text: str,

336

*,

337

style: StyleType = "",

338

emoji: bool = True,

339

emoji_variant: Optional[EmojiVariant] = None,

340

) -> "Text":

341

"""

342

Create Text from Rich markup.

343

344

Args:

345

text: Text with Rich markup tags

346

style: Base style to apply

347

emoji: Enable emoji rendering

348

emoji_variant: Emoji variant preference

349

350

Returns:

351

New Text object with markup applied

352

"""

353

354

@classmethod

355

def from_ansi(

356

cls,

357

text: str,

358

*,

359

style: StyleType = "",

360

no_color: Optional[bool] = None,

361

) -> "Text":

362

"""

363

Create Text from ANSI escaped string.

364

365

Args:

366

text: Text with ANSI escape codes

367

style: Base style to apply

368

no_color: Disable color processing

369

370

Returns:

371

New Text object with ANSI styles converted

372

"""

373

374

@classmethod

375

def styled(

376

cls,

377

text: str,

378

style: StyleType,

379

) -> "Text":

380

"""

381

Create styled Text.

382

383

Args:

384

text: Plain text

385

style: Style to apply

386

387

Returns:

388

New styled Text object

389

"""

390

391

@classmethod

392

def assemble(

393

cls,

394

*parts: Union[str, "Text", Tuple[str, StyleType]],

395

style: StyleType = "",

396

justify: Optional[JustifyMethod] = None,

397

overflow: OverflowMethod = "fold",

398

no_wrap: Optional[bool] = None,

399

end: str = "\n",

400

tab_size: int = 8,

401

meta: Optional[Dict[str, Any]] = None,

402

) -> "Text":

403

"""

404

Assemble Text from multiple parts.

405

406

Args:

407

*parts: Text parts as strings, Text objects, or (text, style) tuples

408

style: Base style

409

justify: Text justification

410

overflow: Overflow handling

411

no_wrap: Disable wrapping

412

end: End string

413

tab_size: Tab size

414

meta: Metadata dictionary

415

416

Returns:

417

New assembled Text object

418

"""

419

420

# Properties

421

@property

422

def plain(self) -> str:

423

"""Get plain text without styling."""

424

425

@property

426

def markup(self) -> str:

427

"""Get text as Rich markup."""

428

429

@property

430

def spans(self) -> List[Span]:

431

"""Get list of styled spans."""

432

433

@property

434

def style(self) -> Style:

435

"""Get base style."""

436

```

437

438

### Span Class

439

440

Represents a styled region within text.

441

442

```python { .api }

443

class Span(NamedTuple):

444

"""

445

A styled span within text.

446

447

Attributes:

448

start: Start character index

449

end: End character index

450

style: Style for this span

451

"""

452

start: int

453

end: int

454

style: Union[str, Style]

455

456

def split(self, offset: int) -> Tuple["Span", Optional["Span"]]:

457

"""

458

Split span at offset.

459

460

Args:

461

offset: Character offset to split at

462

463

Returns:

464

Tuple of (left_span, right_span or None)

465

"""

466

467

def move(self, offset: int) -> "Span":

468

"""

469

Move span by offset.

470

471

Args:

472

offset: Number of characters to move

473

474

Returns:

475

New span with adjusted position

476

"""

477

478

def right_crop(self, offset: int) -> "Span":

479

"""

480

Crop span at offset.

481

482

Args:

483

offset: Offset to crop at

484

485

Returns:

486

New cropped span

487

"""

488

```

489

490

### Style Class

491

492

Comprehensive styling system with support for colors, typography, and effects.

493

494

```python { .api }

495

class Style:

496

"""

497

Immutable style definition for text formatting.

498

499

Args:

500

color: Text color

501

bgcolor: Background color

502

bold: Bold text

503

dim: Dim text

504

italic: Italic text

505

underline: Underlined text

506

blink: Blinking text

507

blink2: Fast blinking text

508

reverse: Reverse video

509

conceal: Concealed text

510

strike: Strikethrough text

511

underline2: Double underline

512

frame: Framed text

513

encircle: Encircled text

514

overline: Overlined text

515

link: Hyperlink URL

516

meta: Metadata dictionary

517

"""

518

def __init__(

519

self,

520

*,

521

color: Optional[ColorType] = None,

522

bgcolor: Optional[ColorType] = None,

523

bold: Optional[bool] = None,

524

dim: Optional[bool] = None,

525

italic: Optional[bool] = None,

526

underline: Optional[bool] = None,

527

blink: Optional[bool] = None,

528

blink2: Optional[bool] = None,

529

reverse: Optional[bool] = None,

530

conceal: Optional[bool] = None,

531

strike: Optional[bool] = None,

532

underline2: Optional[bool] = None,

533

frame: Optional[bool] = None,

534

encircle: Optional[bool] = None,

535

overline: Optional[bool] = None,

536

link: Optional[str] = None,

537

meta: Optional[Dict[str, Any]] = None,

538

): ...

539

540

def copy(self) -> "Style":

541

"""

542

Create a copy of this style.

543

544

Returns:

545

New Style with same properties

546

"""

547

548

def update(self, **kwargs: Any) -> "Style":

549

"""

550

Update style properties.

551

552

Args:

553

**kwargs: Style properties to update

554

555

Returns:

556

New Style with updated properties

557

"""

558

559

def render(

560

self,

561

text: str = "",

562

*,

563

color_system: ColorSystem = ColorSystem.TRUECOLOR,

564

legacy_windows: bool = False,

565

) -> str:

566

"""

567

Render style as ANSI codes.

568

569

Args:

570

text: Text to wrap with codes

571

color_system: Target color system

572

legacy_windows: Enable legacy Windows compatibility

573

574

Returns:

575

Text with ANSI escape codes

576

"""

577

578

def test(self, text: Optional[str] = None) -> "Text":

579

"""

580

Create test text with this style applied.

581

582

Args:

583

text: Test text or None for default

584

585

Returns:

586

Styled Text object for testing

587

"""

588

589

def without_color(self) -> "Style":

590

"""

591

Create style without color information.

592

593

Returns:

594

New Style with colors removed

595

"""

596

597

@classmethod

598

def parse(cls, style: Union[str, "Style"]) -> "Style":

599

"""

600

Parse style from string or return existing Style.

601

602

Args:

603

style: Style string or Style object

604

605

Returns:

606

Parsed Style object

607

"""

608

609

@classmethod

610

def combine(cls, styles: Iterable["Style"]) -> "Style":

611

"""

612

Combine multiple styles.

613

614

Args:

615

styles: Iterable of styles to combine

616

617

Returns:

618

New combined Style

619

"""

620

621

@classmethod

622

def chain(cls, *styles: "Style") -> "Style":

623

"""

624

Chain multiple styles together.

625

626

Args:

627

*styles: Styles to chain

628

629

Returns:

630

New chained Style

631

"""

632

633

@classmethod

634

def null(cls) -> "Style":

635

"""

636

Create a null style with no formatting.

637

638

Returns:

639

Empty Style object

640

"""

641

642

# Properties

643

@property

644

def color(self) -> Optional[Color]:

645

"""Text color."""

646

647

@property

648

def bgcolor(self) -> Optional[Color]:

649

"""Background color."""

650

651

@property

652

def bold(self) -> Optional[bool]:

653

"""Bold flag."""

654

655

@property

656

def dim(self) -> Optional[bool]:

657

"""Dim flag."""

658

659

@property

660

def italic(self) -> Optional[bool]:

661

"""Italic flag."""

662

663

@property

664

def underline(self) -> Optional[bool]:

665

"""Underline flag."""

666

667

@property

668

def strike(self) -> Optional[bool]:

669

"""Strikethrough flag."""

670

671

@property

672

def link(self) -> Optional[str]:

673

"""Hyperlink URL."""

674

675

@property

676

def transparent_background(self) -> bool:

677

"""Check if background is transparent."""

678

```

679

680

**Usage Examples:**

681

682

```python

683

from rich.text import Text, Span

684

from rich.style import Style

685

from rich.console import Console

686

687

console = Console()

688

689

# Basic text creation

690

text = Text("Hello World!")

691

text.stylize("bold red", 0, 5) # Style "Hello"

692

text.stylize("italic blue", 6, 12) # Style "World!"

693

console.print(text)

694

695

# Text from markup

696

markup_text = Text.from_markup("[bold red]Error:[/bold red] Something went wrong")

697

console.print(markup_text)

698

699

# Text assembly

700

assembled = Text.assemble(

701

"Status: ",

702

("OK", "bold green"),

703

" - ",

704

("Ready", "italic blue")

705

)

706

console.print(assembled)

707

708

# Text with highlighting

709

code_text = Text("def hello_world():")

710

code_text.highlight_words(["def", "hello_world"], "bold blue")

711

console.print(code_text)

712

713

# Advanced styling

714

style = Style(

715

color="red",

716

bgcolor="yellow",

717

bold=True,

718

italic=True,

719

underline=True

720

)

721

styled_text = Text("Important Notice", style=style)

722

console.print(styled_text)

723

724

# Text manipulation

725

long_text = Text("This is a very long line of text that needs to be processed")

726

long_text.truncate(20, overflow="ellipsis")

727

console.print(long_text)

728

729

# Working with spans

730

text = Text("Hello World")

731

spans = [

732

Span(0, 5, "bold red"),

733

Span(6, 11, "italic blue")

734

]

735

for span in spans:

736

text.stylize(span.style, span.start, span.end)

737

console.print(text)

738

```