gilt 1.10.0

Fast, beautiful terminal formatting for Rust — styles, tables, trees, syntax highlighting, progress bars, markdown.
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
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
//! Live render module -- a renderable that can be updated and tracks its dimensions.
//!
//! that can be refreshed in-place by emitting cursor movement control codes.

use std::cell::Cell;
use std::sync::Arc;

use crate::console::{Console, ConsoleOptions, Renderable};
use crate::segment::{ControlCode, ControlType, Segment};
use crate::style::Style;
use crate::text::{JustifyMethod, OverflowMethod, Text};

/// How to handle content that exceeds the available vertical space.
#[derive(Debug, Clone, Copy, PartialEq)]
pub enum VerticalOverflowMethod {
    /// Crop excess lines (discard lines beyond the height).
    Crop,
    /// Show an ellipsis ("...") line in place of the last visible line.
    Ellipsis,
    /// Show all lines regardless of the height constraint.
    Visible,
}

/// A renderable wrapper that tracks the dimensions of its last render,
/// enabling cursor-based in-place updates for live terminal displays.
pub struct LiveRender {
    /// The content to render — stored as a type-erased `Arc` so any
    /// `Renderable + Send + Sync` can be held without boxing or flattening.
    pub renderable: Arc<dyn Renderable + Send + Sync>,
    /// An optional style overlay applied when rendering.
    pub style: Style,
    /// How to handle vertical overflow.
    pub vertical_overflow: VerticalOverflowMethod,
    /// The (width, height) of the last render, or `None` if never rendered.
    /// Uses `Cell` for interior mutability so the `Renderable` trait method
    /// (which takes `&self`) can cache the computed shape without unsafe code.
    shape: Cell<Option<(usize, usize)>>,
}

impl LiveRender {
    /// Create a new `LiveRender` with the given renderable content.
    ///
    /// Accepts any `Renderable + Send + Sync + 'static`.
    /// Defaults to a null style and `VerticalOverflowMethod::Ellipsis`.
    pub fn new(renderable: impl Renderable + Send + Sync + 'static) -> Self {
        LiveRender {
            renderable: Arc::new(renderable),
            style: Style::null(),
            vertical_overflow: VerticalOverflowMethod::Ellipsis,
            shape: Cell::new(None),
        }
    }

    /// Create a `LiveRender` from an already-`Arc`-wrapped renderable.
    ///
    /// Used internally by [`Live`] to avoid double-boxing when it already
    /// holds an `Arc<dyn Renderable + Send + Sync>`.
    pub fn new_arc(renderable: Arc<dyn Renderable + Send + Sync>) -> Self {
        LiveRender {
            renderable,
            style: Style::null(),
            vertical_overflow: VerticalOverflowMethod::Ellipsis,
            shape: Cell::new(None),
        }
    }

    /// Set the style overlay (builder pattern).
    #[must_use]
    pub fn with_style(mut self, style: Style) -> Self {
        self.style = style;
        self
    }

    /// Set the vertical overflow method (builder pattern).
    #[must_use]
    pub fn with_vertical_overflow(mut self, overflow: VerticalOverflowMethod) -> Self {
        self.vertical_overflow = overflow;
        self
    }

    /// Return the height (in lines) of the last render.
    ///
    /// Returns `0` if nothing has been rendered yet.
    pub fn last_render_height(&self) -> usize {
        match self.shape.get() {
            Some((_, height)) => height,
            None => 0,
        }
    }

    /// Replace the renderable content.
    pub fn set_renderable(&mut self, renderable: Arc<dyn Renderable + Send + Sync>) {
        self.renderable = renderable;
    }

    /// Return control segments that move the cursor back to the start of the
    /// last render output so that it can be overwritten.
    ///
    /// Produces: CR, ERASE_IN_LINE(2), then (height-1) repetitions of
    /// CURSOR_UP(1) + ERASE_IN_LINE(2).
    pub fn position_cursor(&self) -> Vec<Segment> {
        let Some((_, height)) = self.shape.get() else {
            return Vec::new();
        };
        if height == 0 {
            return Vec::new();
        }

        let mut codes: Vec<ControlCode> = Vec::new();
        codes.push(ControlCode::Simple(ControlType::CarriageReturn));
        codes.push(ControlCode::WithParam(ControlType::EraseInLine, 2));
        for _ in 0..height.saturating_sub(1) {
            codes.push(ControlCode::WithParam(ControlType::CursorUp, 1));
            codes.push(ControlCode::WithParam(ControlType::EraseInLine, 2));
        }

        vec![Segment::new("", None, Some(codes))]
    }

    /// Return control segments that erase the last render output and move the
    /// cursor back to its position before the render.
    ///
    /// Produces: CR, then `height` repetitions of CURSOR_UP(1) + ERASE_IN_LINE(2).
    pub fn restore_cursor(&self) -> Vec<Segment> {
        let Some((_, height)) = self.shape.get() else {
            return Vec::new();
        };
        if height == 0 {
            return Vec::new();
        }

        let mut codes: Vec<ControlCode> = Vec::new();
        codes.push(ControlCode::Simple(ControlType::CarriageReturn));
        for _ in 0..height {
            codes.push(ControlCode::WithParam(ControlType::CursorUp, 1));
            codes.push(ControlCode::WithParam(ControlType::EraseInLine, 2));
        }

        vec![Segment::new("", None, Some(codes))]
    }
}

impl LiveRender {
    /// Render the content and return both the per-line segments (for diff)
    /// and the flat segment list (for the `Renderable` trait).
    ///
    /// This is the shared implementation used by both `gilt_console` and
    /// `gilt_console_lines`, keeping the logic in one place.
    fn render_to_lines(&self, console: &Console, options: &ConsoleOptions) -> Vec<Vec<Segment>> {
        let style_ref = if self.style.is_null() {
            None
        } else {
            Some(&self.style)
        };
        let mut lines = console.render_lines(
            self.renderable.as_ref(),
            Some(options),
            style_ref,
            false,
            false,
        );

        // Check the shape and apply vertical overflow if needed.
        let (_, height) = Segment::get_shape(&lines);
        let max_height = options.height.unwrap_or(options.size.height);

        if height > max_height {
            match self.vertical_overflow {
                VerticalOverflowMethod::Crop => {
                    lines.truncate(max_height);
                }
                VerticalOverflowMethod::Ellipsis => {
                    let ellipsis_lines = if max_height > 0 { max_height - 1 } else { 0 };
                    lines.truncate(ellipsis_lines);
                    let ellipsis_style = console
                        .get_style("live.ellipsis")
                        .unwrap_or_else(|_| Style::null());
                    let mut overflow_text = Text::new("...", ellipsis_style);
                    overflow_text.overflow = Some(OverflowMethod::Crop);
                    overflow_text.justify = Some(JustifyMethod::Center);
                    overflow_text.end = String::new();
                    let ellipsis_segments = console.render(&overflow_text, Some(options));
                    lines.push(ellipsis_segments);
                }
                VerticalOverflowMethod::Visible => {
                    // Keep all lines; do not truncate.
                }
            }
        }

        // Trim trailing empty lines caused by Text's trailing newline (Text::end="\n")
        while let Some(last) = lines.last() {
            if last.is_empty() || last.iter().all(|s| s.text.trim().is_empty()) {
                lines.pop();
            } else {
                break;
            }
        }

        // Compute and store the final shape.
        let final_shape = Segment::get_shape(&lines);
        self.shape.set(Some(final_shape));

        lines
    }

    /// Render the content and return per-line segments for line-diff use.
    pub(crate) fn gilt_console_lines(
        &self,
        console: &Console,
        options: &ConsoleOptions,
    ) -> Vec<Vec<Segment>> {
        self.render_to_lines(console, options)
    }
}

impl Renderable for LiveRender {
    fn gilt_console(&self, console: &Console, options: &ConsoleOptions) -> Vec<Segment> {
        let lines = self.render_to_lines(console, options);

        // Flatten lines into a single segment list, inserting newlines between
        // lines (but not after the last line).
        let mut segments = Vec::new();
        let line_count = lines.len();
        for (i, line) in lines.into_iter().enumerate() {
            segments.extend(line);
            if i + 1 < line_count {
                segments.push(Segment::line());
            }
        }

        segments
    }
}

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

    // -- Construction -------------------------------------------------------

    #[test]
    fn test_default_construction() {
        let lr = LiveRender::new(Text::new("hello", Style::null()));
        // Check pre-render invariants first (before shape is set).
        assert!(lr.style.is_null());
        assert_eq!(lr.vertical_overflow, VerticalOverflowMethod::Ellipsis);
        assert!(lr.shape.get().is_none());
        // Now verify by rendering.
        let console = Console::builder().width(80).markup(false).build();
        let opts = console.options();
        let segments = lr.gilt_console(&console, &opts);
        let combined: String = segments.iter().map(|s| s.text.as_str()).collect();
        assert!(combined.contains("hello"));
    }

    // -- Builder methods ----------------------------------------------------

    #[test]
    fn test_with_style() {
        let style = Style::parse("bold");
        let lr = LiveRender::new(Text::new("x", Style::null())).with_style(style.clone());
        assert_eq!(lr.style, style);
    }

    #[test]
    fn test_with_vertical_overflow() {
        let lr = LiveRender::new(Text::new("x", Style::null()))
            .with_vertical_overflow(VerticalOverflowMethod::Crop);
        assert_eq!(lr.vertical_overflow, VerticalOverflowMethod::Crop);
    }

    // -- last_render_height -------------------------------------------------

    #[test]
    fn test_last_render_height_before_render() {
        let lr = LiveRender::new(Text::new("hello", Style::null()));
        assert_eq!(lr.last_render_height(), 0);
    }

    #[test]
    fn test_last_render_height_after_render() {
        let console = Console::builder().width(80).build();
        let lr = LiveRender::new(Text::new("line1\nline2\nline3", Style::null()));
        let opts = console.options();
        let _ = lr.gilt_console(&console, &opts);
        assert_eq!(lr.last_render_height(), 3);
    }

    // -- set_renderable -----------------------------------------------------

    #[test]
    fn test_set_renderable() {
        let mut lr = LiveRender::new(Text::new("old", Style::null()));
        lr.set_renderable(Arc::new(Text::new("new", Style::null())));
        // Verify by rendering
        let console = Console::builder().width(80).markup(false).build();
        let opts = console.options();
        let segments = lr.gilt_console(&console, &opts);
        let combined: String = segments.iter().map(|s| s.text.as_str()).collect();
        assert!(combined.contains("new"));
        assert!(!combined.contains("old"));
    }

    // -- Renderable trait ---------------------------------------------------

    #[test]
    fn test_renderable_basic() {
        let console = Console::builder().width(80).markup(false).build();
        let lr = LiveRender::new(Text::new("Hello, World!", Style::null()));
        let opts = console.options();
        let segments = lr.gilt_console(&console, &opts);
        let combined: String = segments.iter().map(|s| s.text.as_str()).collect();
        assert!(combined.contains("Hello, World!"));
    }

    #[test]
    fn test_renderable_multiline() {
        let console = Console::builder().width(80).markup(false).build();
        let lr = LiveRender::new(Text::new("Line1\nLine2", Style::null()));
        let opts = console.options();
        let segments = lr.gilt_console(&console, &opts);

        // There should be a newline segment between lines.
        let has_newline = segments.iter().any(|s| s.text == "\n");
        assert!(has_newline);

        let combined: String = segments.iter().map(|s| s.text.as_str()).collect();
        assert!(combined.contains("Line1"));
        assert!(combined.contains("Line2"));
    }

    // -- Vertical overflow: crop --------------------------------------------

    #[test]
    fn test_vertical_overflow_crop() {
        let console = Console::builder().width(80).height(3).build();
        // Create content with 5 lines.
        let lr = LiveRender::new(Text::new("L1\nL2\nL3\nL4\nL5", Style::null()))
            .with_vertical_overflow(VerticalOverflowMethod::Crop);
        let opts = console.options();
        let segments = lr.gilt_console(&console, &opts);

        let combined: String = segments.iter().map(|s| s.text.as_str()).collect();
        assert!(combined.contains("L1"));
        assert!(combined.contains("L2"));
        assert!(combined.contains("L3"));
        assert!(!combined.contains("L4"));
        assert!(!combined.contains("L5"));

        assert_eq!(lr.last_render_height(), 3);
    }

    // -- Vertical overflow: ellipsis ----------------------------------------

    #[test]
    fn test_vertical_overflow_ellipsis() {
        let console = Console::builder().width(80).height(3).build();
        let lr = LiveRender::new(Text::new("L1\nL2\nL3\nL4\nL5", Style::null()))
            .with_vertical_overflow(VerticalOverflowMethod::Ellipsis);
        let opts = console.options();
        let segments = lr.gilt_console(&console, &opts);

        let combined: String = segments.iter().map(|s| s.text.as_str()).collect();
        assert!(combined.contains("L1"));
        assert!(combined.contains("L2"));
        assert!(combined.contains("..."));
        assert!(!combined.contains("L3\n"));

        assert_eq!(lr.last_render_height(), 3);
    }

    // -- Vertical overflow: visible -----------------------------------------

    #[test]
    fn test_vertical_overflow_visible() {
        let console = Console::builder().width(80).height(3).build();
        let lr = LiveRender::new(Text::new("L1\nL2\nL3\nL4\nL5", Style::null()))
            .with_vertical_overflow(VerticalOverflowMethod::Visible);
        let opts = console.options();
        let segments = lr.gilt_console(&console, &opts);

        let combined: String = segments.iter().map(|s| s.text.as_str()).collect();
        assert!(combined.contains("L1"));
        assert!(combined.contains("L5"));

        assert_eq!(lr.last_render_height(), 5);
    }

    // -- position_cursor ----------------------------------------------------

    #[test]
    fn test_position_cursor_no_render() {
        let lr = LiveRender::new(Text::new("hello", Style::null()));
        let segments = lr.position_cursor();
        assert!(segments.is_empty());
    }

    #[test]
    fn test_position_cursor_after_render() {
        let console = Console::builder().width(80).build();
        let lr = LiveRender::new(Text::new("L1\nL2\nL3", Style::null()));
        let opts = console.options();
        let _ = lr.gilt_console(&console, &opts);

        let segments = lr.position_cursor();
        assert_eq!(segments.len(), 1);
        let ctrl = segments[0].control.as_ref().unwrap();

        // First code: CarriageReturn
        assert_eq!(ctrl[0], ControlCode::Simple(ControlType::CarriageReturn));
        // Second code: EraseInLine(2)
        assert_eq!(ctrl[1], ControlCode::WithParam(ControlType::EraseInLine, 2));

        // Then (height-1) = 2 pairs of CursorUp(1), EraseInLine(2)
        // Total codes: 1 + 1 + 2*2 = 6
        assert_eq!(ctrl.len(), 6);
        assert_eq!(ctrl[2], ControlCode::WithParam(ControlType::CursorUp, 1));
        assert_eq!(ctrl[3], ControlCode::WithParam(ControlType::EraseInLine, 2));
        assert_eq!(ctrl[4], ControlCode::WithParam(ControlType::CursorUp, 1));
        assert_eq!(ctrl[5], ControlCode::WithParam(ControlType::EraseInLine, 2));
    }

    // -- restore_cursor -----------------------------------------------------

    #[test]
    fn test_restore_cursor_no_render() {
        let lr = LiveRender::new(Text::new("hello", Style::null()));
        let segments = lr.restore_cursor();
        assert!(segments.is_empty());
    }

    #[test]
    fn test_restore_cursor_after_render() {
        let console = Console::builder().width(80).build();
        let lr = LiveRender::new(Text::new("L1\nL2\nL3", Style::null()));
        let opts = console.options();
        let _ = lr.gilt_console(&console, &opts);

        let segments = lr.restore_cursor();
        assert_eq!(segments.len(), 1);
        let ctrl = segments[0].control.as_ref().unwrap();

        // First code: CarriageReturn
        assert_eq!(ctrl[0], ControlCode::Simple(ControlType::CarriageReturn));

        // Then height = 3 pairs of CursorUp(1), EraseInLine(2)
        // Total codes: 1 + 3*2 = 7
        assert_eq!(ctrl.len(), 7);
        for i in 0..3 {
            assert_eq!(
                ctrl[1 + i * 2],
                ControlCode::WithParam(ControlType::CursorUp, 1)
            );
            assert_eq!(
                ctrl[2 + i * 2],
                ControlCode::WithParam(ControlType::EraseInLine, 2)
            );
        }
    }

    // -- Shape tracking after render ----------------------------------------

    #[test]
    fn test_shape_tracking() {
        let console = Console::builder().width(40).build();
        let lr = LiveRender::new(Text::new("Hello", Style::null()));
        let opts = console.options();

        assert!(lr.shape.get().is_none());
        let _ = lr.gilt_console(&console, &opts);
        assert!(lr.shape.get().is_some());
        let (w, h) = lr.shape.get().unwrap();
        assert!(w > 0);
        assert_eq!(h, 1);
    }

    // -- Single-line position_cursor ----------------------------------------

    #[test]
    fn test_position_cursor_single_line() {
        let console = Console::builder().width(80).build();
        let lr = LiveRender::new(Text::new("Hello", Style::null()));
        let opts = console.options();
        let _ = lr.gilt_console(&console, &opts);

        let segments = lr.position_cursor();
        assert_eq!(segments.len(), 1);
        let ctrl = segments[0].control.as_ref().unwrap();
        // height=1, so: CR, EraseInLine(2), no CursorUp pairs
        assert_eq!(ctrl.len(), 2);
        assert_eq!(ctrl[0], ControlCode::Simple(ControlType::CarriageReturn));
        assert_eq!(ctrl[1], ControlCode::WithParam(ControlType::EraseInLine, 2));
    }

    // -- Single-line restore_cursor -----------------------------------------

    #[test]
    fn test_restore_cursor_single_line() {
        let console = Console::builder().width(80).build();
        let lr = LiveRender::new(Text::new("Hello", Style::null()));
        let opts = console.options();
        let _ = lr.gilt_console(&console, &opts);

        let segments = lr.restore_cursor();
        assert_eq!(segments.len(), 1);
        let ctrl = segments[0].control.as_ref().unwrap();
        // height=1: CR, CursorUp(1), EraseInLine(2)
        assert_eq!(ctrl.len(), 3);
        assert_eq!(ctrl[0], ControlCode::Simple(ControlType::CarriageReturn));
        assert_eq!(ctrl[1], ControlCode::WithParam(ControlType::CursorUp, 1));
        assert_eq!(ctrl[2], ControlCode::WithParam(ControlType::EraseInLine, 2));
    }

    // -- Vertical overflow enum variants ------------------------------------

    #[test]
    fn test_vertical_overflow_method_variants() {
        assert_ne!(
            VerticalOverflowMethod::Crop,
            VerticalOverflowMethod::Ellipsis
        );
        assert_ne!(
            VerticalOverflowMethod::Ellipsis,
            VerticalOverflowMethod::Visible
        );
        assert_ne!(
            VerticalOverflowMethod::Crop,
            VerticalOverflowMethod::Visible
        );
    }

    // -- Render with style --------------------------------------------------

    #[test]
    fn test_render_with_style() {
        let console = Console::builder().width(80).markup(false).build();
        let style = Style::parse("bold");
        let lr = LiveRender::new(Text::new("styled", Style::null())).with_style(style);
        let opts = console.options();
        let segments = lr.gilt_console(&console, &opts);
        let combined: String = segments.iter().map(|s| s.text.as_str()).collect();
        assert!(combined.contains("styled"));
    }

    // -- Content fits within height (no overflow) ---------------------------

    #[test]
    fn test_no_overflow_when_fits() {
        let console = Console::builder().width(80).height(10).build();
        let lr = LiveRender::new(Text::new("L1\nL2\nL3", Style::null()))
            .with_vertical_overflow(VerticalOverflowMethod::Ellipsis);
        let opts = console.options();
        let segments = lr.gilt_console(&console, &opts);

        let combined: String = segments.iter().map(|s| s.text.as_str()).collect();
        assert!(combined.contains("L1"));
        assert!(combined.contains("L2"));
        assert!(combined.contains("L3"));
        assert!(!combined.contains("..."));
    }

    // -- new_arc constructor ------------------------------------------------

    #[test]
    fn test_new_arc_constructor() {
        let arc: Arc<dyn Renderable + Send + Sync> = Arc::new(Text::new("via arc", Style::null()));
        let lr = LiveRender::new_arc(arc);
        let console = Console::builder().width(80).markup(false).build();
        let opts = console.options();
        let segments = lr.gilt_console(&console, &opts);
        let combined: String = segments.iter().map(|s| s.text.as_str()).collect();
        assert!(combined.contains("via arc"));
    }
}