gilt 0.5.0

A fast, rich terminal formatting library — Rust port of Python's rich
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
//! Rust-idiomatic style extension trait for string types.
//!
//! This module provides a `Stylize` extension trait that enables method chaining
//! on `&str`, `String`, and `StyledStr` to build styled text, similar to the
//! `colored` crate's API. This is a distinctly Rusty API that Python's rich
//! cannot offer.
//!
//! # Examples
//!
//! ```
//! use gilt::styled_str::Stylize;
//!
//! let styled = "Hello".bold().red().on_blue();
//! assert_eq!(styled.text, "Hello");
//! ```

use crate::color::Color;
use crate::console::{Console, ConsoleOptions, Renderable};
use crate::segment::Segment;
use crate::style::Style;
use crate::text::Text;

use std::fmt;

/// A string with an associated style, created via the [`Stylize`] extension trait.
///
/// `StyledStr` implements [`Renderable`], so it can be passed directly to
/// [`Console::print`] and friends.
///
/// # Examples
///
/// ```
/// use gilt::styled_str::Stylize;
///
/// let greeting = "Hello, world!".bold().green();
/// assert_eq!(greeting.text, "Hello, world!");
/// ```
#[derive(Clone, Debug)]
pub struct StyledStr {
    /// The plain text content.
    pub text: String,
    /// The accumulated style.
    pub style: Style,
}

impl StyledStr {
    /// Create a new `StyledStr` with the given text and style.
    pub fn new(text: impl Into<String>, style: Style) -> Self {
        StyledStr {
            text: text.into(),
            style,
        }
    }

    /// Convert this `StyledStr` into a [`Text`] with the style applied as a span.
    pub fn to_text(&self) -> Text {
        Text::styled(&self.text, self.style.clone())
    }
}

impl fmt::Display for StyledStr {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        // Display shows the plain text without ANSI codes.
        write!(f, "{}", self.text)
    }
}

impl Renderable for StyledStr {
    fn rich_console(&self, console: &Console, options: &ConsoleOptions) -> Vec<Segment> {
        self.to_text().rich_console(console, options)
    }
}

// ---------------------------------------------------------------------------
// Helper: construct a Style with a single attribute set
// ---------------------------------------------------------------------------

/// Build an attribute-only style. Uses `Style::parse` for known-valid attribute
/// names, which will never fail for the strings we pass.
fn attr_style(name: &str) -> Style {
    Style::parse(name).expect("internal: known-valid attribute name")
}

/// Build a foreground-color style.
fn fg_style(name: &str) -> Style {
    let color = Color::parse(name).expect("internal: known-valid color name");
    Style::from_color(Some(color), None)
}

/// Build a background-color style.
fn bg_style(name: &str) -> Style {
    let color = Color::parse(name).expect("internal: known-valid color name");
    Style::from_color(None, Some(color))
}

// ---------------------------------------------------------------------------
// Stylize trait
// ---------------------------------------------------------------------------

/// Extension trait for adding rich-style formatting to strings via method chaining.
///
/// Implemented for `&str`, `String`, and `StyledStr`. When called on a plain
/// string type, the first method creates a [`StyledStr`]. Subsequent chained
/// calls merge additional style attributes using the `Style` `+` operator.
///
/// # Examples
///
/// ```
/// use gilt::styled_str::Stylize;
///
/// // Single attribute
/// let bold = "hello".bold();
/// assert_eq!(bold.text, "hello");
///
/// // Chained attributes + foreground + background
/// let fancy = "world".bold().italic().red().on_blue();
/// assert_eq!(fancy.text, "world");
/// ```
pub trait Stylize: Sized {
    /// Apply an arbitrary [`Style`] to produce a [`StyledStr`].
    fn styled(self, style: Style) -> StyledStr;

    // -- Attribute methods --------------------------------------------------

    /// Make the text bold.
    fn bold(self) -> StyledStr {
        self.styled(attr_style("bold"))
    }
    /// Make the text dim / faint.
    fn dim(self) -> StyledStr {
        self.styled(attr_style("dim"))
    }
    /// Make the text italic.
    fn italic(self) -> StyledStr {
        self.styled(attr_style("italic"))
    }
    /// Underline the text.
    fn underline(self) -> StyledStr {
        self.styled(attr_style("underline"))
    }
    /// Apply strikethrough to the text.
    fn strikethrough(self) -> StyledStr {
        self.styled(attr_style("strike"))
    }
    /// Make the text blink.
    fn blink(self) -> StyledStr {
        self.styled(attr_style("blink"))
    }
    /// Reverse foreground and background colors.
    fn reverse(self) -> StyledStr {
        self.styled(attr_style("reverse"))
    }
    /// Hide / conceal the text.
    fn conceal(self) -> StyledStr {
        self.styled(attr_style("conceal"))
    }
    /// Apply double underline.
    fn underline2(self) -> StyledStr {
        self.styled(attr_style("underline2"))
    }
    /// Apply overline.
    fn overline(self) -> StyledStr {
        self.styled(attr_style("overline"))
    }

    // -- Foreground color methods -------------------------------------------

    /// Set foreground to red.
    fn red(self) -> StyledStr {
        self.styled(fg_style("red"))
    }
    /// Set foreground to green.
    fn green(self) -> StyledStr {
        self.styled(fg_style("green"))
    }
    /// Set foreground to blue.
    fn blue(self) -> StyledStr {
        self.styled(fg_style("blue"))
    }
    /// Set foreground to yellow.
    fn yellow(self) -> StyledStr {
        self.styled(fg_style("yellow"))
    }
    /// Set foreground to magenta.
    fn magenta(self) -> StyledStr {
        self.styled(fg_style("magenta"))
    }
    /// Set foreground to cyan.
    fn cyan(self) -> StyledStr {
        self.styled(fg_style("cyan"))
    }
    /// Set foreground to white.
    fn white(self) -> StyledStr {
        self.styled(fg_style("white"))
    }
    /// Set foreground to black.
    fn black(self) -> StyledStr {
        self.styled(fg_style("black"))
    }
    /// Set foreground to bright red.
    fn bright_red(self) -> StyledStr {
        self.styled(fg_style("bright_red"))
    }
    /// Set foreground to bright green.
    fn bright_green(self) -> StyledStr {
        self.styled(fg_style("bright_green"))
    }
    /// Set foreground to bright blue.
    fn bright_blue(self) -> StyledStr {
        self.styled(fg_style("bright_blue"))
    }
    /// Set foreground to bright yellow.
    fn bright_yellow(self) -> StyledStr {
        self.styled(fg_style("bright_yellow"))
    }
    /// Set foreground to bright magenta.
    fn bright_magenta(self) -> StyledStr {
        self.styled(fg_style("bright_magenta"))
    }
    /// Set foreground to bright cyan.
    fn bright_cyan(self) -> StyledStr {
        self.styled(fg_style("bright_cyan"))
    }
    /// Set foreground to bright white.
    fn bright_white(self) -> StyledStr {
        self.styled(fg_style("bright_white"))
    }

    // -- Background color methods -------------------------------------------

    /// Set background to red.
    fn on_red(self) -> StyledStr {
        self.styled(bg_style("red"))
    }
    /// Set background to green.
    fn on_green(self) -> StyledStr {
        self.styled(bg_style("green"))
    }
    /// Set background to blue.
    fn on_blue(self) -> StyledStr {
        self.styled(bg_style("blue"))
    }
    /// Set background to yellow.
    fn on_yellow(self) -> StyledStr {
        self.styled(bg_style("yellow"))
    }
    /// Set background to magenta.
    fn on_magenta(self) -> StyledStr {
        self.styled(bg_style("magenta"))
    }
    /// Set background to cyan.
    fn on_cyan(self) -> StyledStr {
        self.styled(bg_style("cyan"))
    }
    /// Set background to white.
    fn on_white(self) -> StyledStr {
        self.styled(bg_style("white"))
    }
    /// Set background to black.
    fn on_black(self) -> StyledStr {
        self.styled(bg_style("black"))
    }

    // -- Arbitrary color methods --------------------------------------------

    /// Set the foreground to an arbitrary color by name or hex string.
    ///
    /// # Panics
    /// Panics if `color` is not a valid color string.
    fn fg(self, color: &str) -> StyledStr {
        self.styled(fg_style(color))
    }

    /// Set the background to an arbitrary color by name or hex string.
    ///
    /// # Panics
    /// Panics if `color` is not a valid color string.
    fn bg(self, color: &str) -> StyledStr {
        self.styled(bg_style(color))
    }

    /// Apply a hyperlink.
    fn link(self, url: &str) -> StyledStr {
        self.styled(Style::with_link(url))
    }
}

// ---------------------------------------------------------------------------
// Implementations
// ---------------------------------------------------------------------------

impl Stylize for &str {
    fn styled(self, style: Style) -> StyledStr {
        StyledStr {
            text: self.to_string(),
            style,
        }
    }
}

impl Stylize for String {
    fn styled(self, style: Style) -> StyledStr {
        StyledStr { text: self, style }
    }
}

impl Stylize for StyledStr {
    fn styled(self, style: Style) -> StyledStr {
        StyledStr {
            text: self.text,
            style: self.style + style,
        }
    }
}

// ---------------------------------------------------------------------------
// Tests
// ---------------------------------------------------------------------------

#[cfg(test)]
mod tests {
    use super::*;
    use crate::console::ConsoleBuilder;

    #[test]
    fn test_bold_str() {
        let s = "hello".bold();
        assert_eq!(s.text, "hello");
        assert_eq!(s.style.bold(), Some(true));
    }

    #[test]
    fn test_chain_bold_red() {
        let s = "hello".bold().red();
        assert_eq!(s.text, "hello");
        assert_eq!(s.style.bold(), Some(true));
        let color = s.style.color().expect("should have foreground color");
        assert_eq!(color.name, "red");
    }

    #[test]
    fn test_chain_on_color() {
        let s = "hello".red().on_blue();
        assert_eq!(s.text, "hello");
        let fg = s.style.color().expect("should have fg");
        assert_eq!(fg.name, "red");
        let bg = s.style.bgcolor().expect("should have bg");
        assert_eq!(bg.name, "blue");
    }

    #[test]
    fn test_styled_str_renderable() {
        let styled = "Hello".bold().green();
        let console = ConsoleBuilder::new().force_terminal(true).width(80).build();
        let options = console.options();
        let segments = styled.rich_console(&console, &options);
        // Should produce at least one segment containing "Hello"
        let text: String = segments.iter().map(|seg| seg.text.as_str()).collect();
        assert!(text.contains("Hello"));
    }

    #[test]
    fn test_stylize_string() {
        let owned = String::from("world");
        let s = owned.italic().cyan();
        assert_eq!(s.text, "world");
        assert_eq!(s.style.italic(), Some(true));
        let color = s.style.color().expect("should have foreground color");
        assert_eq!(color.name, "cyan");
    }

    #[test]
    fn test_display() {
        let s = "plain text".bold().red();
        // Display should show the plain text, not ANSI codes.
        assert_eq!(format!("{}", s), "plain text");
    }

    #[test]
    fn test_styled_str_text_conversion() {
        let s = "convert me".underline().magenta();
        let text = s.to_text();
        assert_eq!(text.plain(), "convert me");
        // The text should have a span with the style applied.
        assert!(!text.spans().is_empty());
    }

    #[test]
    fn test_all_colors() {
        let colors = vec![
            ("red", "hello".red()),
            ("green", "hello".green()),
            ("blue", "hello".blue()),
            ("yellow", "hello".yellow()),
            ("magenta", "hello".magenta()),
            ("cyan", "hello".cyan()),
            ("white", "hello".white()),
            ("black", "hello".black()),
            ("bright_red", "hello".bright_red()),
            ("bright_green", "hello".bright_green()),
            ("bright_blue", "hello".bright_blue()),
            ("bright_yellow", "hello".bright_yellow()),
            ("bright_magenta", "hello".bright_magenta()),
            ("bright_cyan", "hello".bright_cyan()),
            ("bright_white", "hello".bright_white()),
        ];

        for (name, styled) in colors {
            let color = styled
                .style
                .color()
                .unwrap_or_else(|| panic!("color method '{}' should set fg color", name));
            assert_eq!(
                color.name, name,
                "expected color name '{}', got '{}'",
                name, color.name
            );
        }
    }

    #[test]
    fn test_all_bg_colors() {
        let colors = vec![
            ("red", "hello".on_red()),
            ("green", "hello".on_green()),
            ("blue", "hello".on_blue()),
            ("yellow", "hello".on_yellow()),
            ("magenta", "hello".on_magenta()),
            ("cyan", "hello".on_cyan()),
            ("white", "hello".on_white()),
            ("black", "hello".on_black()),
        ];

        for (name, styled) in colors {
            let bg = styled
                .style
                .bgcolor()
                .unwrap_or_else(|| panic!("on_{} should set bg color", name));
            assert_eq!(
                bg.name, name,
                "expected bg color '{}', got '{}'",
                name, bg.name
            );
        }
    }

    #[test]
    fn test_all_attributes() {
        assert_eq!("x".bold().style.bold(), Some(true));
        assert_eq!("x".dim().style.dim(), Some(true));
        assert_eq!("x".italic().style.italic(), Some(true));
        assert_eq!("x".underline().style.underline(), Some(true));
        assert_eq!("x".strikethrough().style.strike(), Some(true));
        assert_eq!("x".blink().style.blink(), Some(true));
        assert_eq!("x".reverse().style.reverse(), Some(true));
        assert_eq!("x".conceal().style.conceal(), Some(true));
        assert_eq!("x".overline().style.overline(), Some(true));
    }

    #[test]
    fn test_complex_chain() {
        let s = "fancy"
            .bold()
            .italic()
            .underline()
            .bright_yellow()
            .on_blue();
        assert_eq!(s.text, "fancy");
        assert_eq!(s.style.bold(), Some(true));
        assert_eq!(s.style.italic(), Some(true));
        assert_eq!(s.style.underline(), Some(true));
        assert_eq!(s.style.color().unwrap().name, "bright_yellow");
        assert_eq!(s.style.bgcolor().unwrap().name, "blue");
    }

    #[test]
    fn test_fg_and_bg_arbitrary() {
        let s = "hex".fg("#ff0000").bg("#00ff00");
        assert!(s.style.color().is_some());
        assert!(s.style.bgcolor().is_some());
    }

    #[test]
    fn test_link() {
        let s = "click me".blue().underline().link("https://example.com");
        assert_eq!(s.style.link(), Some("https://example.com"));
        assert_eq!(s.style.color().unwrap().name, "blue");
    }

    #[test]
    fn test_styled_method_with_parsed_style() {
        let style = Style::parse("bold italic red on white").unwrap();
        let s = "custom".styled(style);
        assert_eq!(s.style.bold(), Some(true));
        assert_eq!(s.style.italic(), Some(true));
        assert_eq!(s.style.color().unwrap().name, "red");
        assert_eq!(s.style.bgcolor().unwrap().name, "white");
    }
}