mdv-minus 5.7.2

mdv-maintained fork of the asynchronous minus terminal paging library
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
use crate::{LineNumbers, PagerState};
use crossterm::style::{Attribute, Color, ContentStyle};
use std::{fmt::Write, sync::Arc};
use unicode_segmentation::UnicodeSegmentation;
use unicode_width::UnicodeWidthStr;

const RESET_STYLE: &str = "\x1b[0m";

/// Runs synchronously while pager state is locked.
pub type PromptRenderer = Arc<
    dyn for<'a> Fn(&PromptContext<'a>) -> Result<PromptLine, PromptError> + Send + Sync + 'static,
>;

#[derive(Clone, Debug, Eq, PartialEq, thiserror::Error)]
pub enum PromptError {
    #[error("prompt content must fit on one line")]
    MultilineText,
    #[error("prompt content contains unsupported control character {0:?}")]
    ControlCharacter(char),
}

pub struct PromptContext<'a> {
    state: &'a PagerState,
}

impl<'a> PromptContext<'a> {
    pub(crate) const fn new(state: &'a PagerState) -> Self {
        Self { state }
    }

    #[must_use]
    pub fn prompt(&self) -> &'a str {
        &self.state.prompt
    }

    #[must_use]
    pub fn message(&self) -> Option<&'a str> {
        self.state.message.as_deref()
    }

    #[must_use]
    pub fn display_text(&self) -> &'a str {
        self.message().unwrap_or_else(|| self.prompt())
    }

    #[must_use]
    pub const fn columns(&self) -> usize {
        self.state.cols
    }

    #[must_use]
    pub const fn rows(&self) -> usize {
        self.state.rows
    }

    #[must_use]
    pub const fn content_rows(&self) -> usize {
        self.state.content_rows()
    }

    #[must_use]
    pub const fn panel_rows(&self) -> usize {
        self.state.prompt_panel_rows()
    }

    #[must_use]
    pub const fn upper_mark(&self) -> usize {
        self.state.upper_mark
    }

    #[must_use]
    pub const fn left_mark(&self) -> usize {
        self.state.left_mark
    }

    #[must_use]
    pub const fn formatted_lines(&self) -> usize {
        self.state.screen.formatted_lines_count()
    }

    #[must_use]
    pub const fn logical_lines(&self) -> usize {
        self.state.screen.line_count()
    }

    #[must_use]
    pub const fn max_scroll_offset(&self) -> usize {
        self.state.max_upper_mark()
    }

    #[must_use]
    pub fn scroll_percentage(&self) -> u8 {
        let max_offset = self.max_scroll_offset();
        if max_offset == 0 {
            return 100;
        }

        let offset = self.upper_mark().min(max_offset) as u128;
        let percentage = (offset * 100 + max_offset as u128 / 2) / max_offset as u128;
        #[allow(clippy::cast_possible_truncation)]
        let percentage = percentage as u8;
        percentage
    }

    #[must_use]
    pub fn numeric_prefix(&self) -> &'a str {
        &self.state.prefix_num
    }

    #[must_use]
    pub const fn line_numbers(&self) -> LineNumbers {
        self.state.line_numbers
    }

    #[must_use]
    pub const fn line_wrapping(&self) -> bool {
        self.state.screen.line_wrapping
    }

    #[must_use]
    pub const fn follow_output(&self) -> bool {
        self.state.follow_output
    }

    #[must_use]
    #[cfg(feature = "search")]
    pub fn search_position(&self) -> Option<(usize, usize)> {
        let total = self.state.search_state.search_idx.len();
        (total > 0).then_some((self.state.search_state.search_mark + 1, total))
    }
}

#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub enum PromptColor {
    Black,
    DarkGrey,
    Red,
    DarkRed,
    Green,
    DarkGreen,
    Yellow,
    DarkYellow,
    Blue,
    DarkBlue,
    Magenta,
    DarkMagenta,
    Cyan,
    DarkCyan,
    White,
    Grey,
    Rgb { r: u8, g: u8, b: u8 },
    AnsiValue(u8),
}

impl From<PromptColor> for Color {
    fn from(color: PromptColor) -> Self {
        match color {
            PromptColor::Black => Self::Black,
            PromptColor::DarkGrey => Self::DarkGrey,
            PromptColor::Red => Self::Red,
            PromptColor::DarkRed => Self::DarkRed,
            PromptColor::Green => Self::Green,
            PromptColor::DarkGreen => Self::DarkGreen,
            PromptColor::Yellow => Self::Yellow,
            PromptColor::DarkYellow => Self::DarkYellow,
            PromptColor::Blue => Self::Blue,
            PromptColor::DarkBlue => Self::DarkBlue,
            PromptColor::Magenta => Self::Magenta,
            PromptColor::DarkMagenta => Self::DarkMagenta,
            PromptColor::Cyan => Self::Cyan,
            PromptColor::DarkCyan => Self::DarkCyan,
            PromptColor::White => Self::White,
            PromptColor::Grey => Self::Grey,
            PromptColor::Rgb { r, g, b } => Self::Rgb { r, g, b },
            PromptColor::AnsiValue(value) => Self::AnsiValue(value),
        }
    }
}

#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub enum PromptAttribute {
    Bold,
    Dim,
    Italic,
    Underlined,
    Reverse,
    Hidden,
    CrossedOut,
}

impl PromptAttribute {
    const ALL: [Self; 7] = [
        Self::Bold,
        Self::Dim,
        Self::Italic,
        Self::Underlined,
        Self::Reverse,
        Self::Hidden,
        Self::CrossedOut,
    ];

    const fn bit(self) -> u8 {
        1 << self as u8
    }
}

impl From<PromptAttribute> for Attribute {
    fn from(attribute: PromptAttribute) -> Self {
        match attribute {
            PromptAttribute::Bold => Self::Bold,
            PromptAttribute::Dim => Self::Dim,
            PromptAttribute::Italic => Self::Italic,
            PromptAttribute::Underlined => Self::Underlined,
            PromptAttribute::Reverse => Self::Reverse,
            PromptAttribute::Hidden => Self::Hidden,
            PromptAttribute::CrossedOut => Self::CrossedOut,
        }
    }
}

#[derive(Clone, Copy, Debug, Default, Eq, PartialEq)]
pub struct PromptStyle {
    foreground: Option<PromptColor>,
    background: Option<PromptColor>,
    attributes: u8,
}

impl PromptStyle {
    #[must_use]
    pub const fn foreground(mut self, color: PromptColor) -> Self {
        self.foreground = Some(color);
        self
    }

    #[must_use]
    pub const fn background(mut self, color: PromptColor) -> Self {
        self.background = Some(color);
        self
    }

    #[must_use]
    pub const fn attribute(mut self, attribute: PromptAttribute) -> Self {
        self.attributes |= attribute.bit();
        self
    }

    fn content_style(self) -> ContentStyle {
        let mut style = ContentStyle {
            foreground_color: self.foreground.map(Into::into),
            background_color: self.background.map(Into::into),
            ..ContentStyle::default()
        };
        for attribute in PromptAttribute::ALL {
            if self.attributes & attribute.bit() != 0 {
                style.attributes.set(attribute.into());
            }
        }
        style
    }
}

#[derive(Clone, Debug, Eq, PartialEq)]
pub struct PromptSpan {
    text: String,
    style: PromptStyle,
}

#[allow(clippy::missing_errors_doc)]
impl PromptSpan {
    /// Rejects line breaks and terminal control characters.
    pub fn new(text: impl Into<String>, style: PromptStyle) -> Result<Self, PromptError> {
        let text = text.into();
        validate_single_line(&text)?;
        if let Some(character) = text.chars().find(|character| character.is_control()) {
            return Err(PromptError::ControlCharacter(character));
        }
        Ok(Self { text, style })
    }

    fn width(&self) -> usize {
        UnicodeWidthStr::width(self.text.as_str())
    }
}

#[derive(Clone, Debug, Default, Eq, PartialEq)]
pub struct PromptLine {
    left: Vec<PromptSpan>,
    right: Vec<PromptSpan>,
    fill_style: PromptStyle,
    truncation_indicator: Option<PromptSpan>,
}

#[allow(clippy::missing_errors_doc)]
impl PromptLine {
    #[must_use]
    pub const fn new() -> Self {
        Self {
            left: Vec::new(),
            right: Vec::new(),
            fill_style: PromptStyle {
                foreground: None,
                background: None,
                attributes: 0,
            },
            truncation_indicator: None,
        }
    }

    pub fn plain(text: impl Into<String>) -> Result<Self, PromptError> {
        Ok(Self::new().left(PromptSpan::new(text, PromptStyle::default())?))
    }

    #[must_use]
    pub fn left(mut self, span: PromptSpan) -> Self {
        self.left.push(span);
        self
    }

    #[must_use]
    pub fn right(mut self, span: PromptSpan) -> Self {
        self.right.push(span);
        self
    }

    #[must_use]
    pub const fn fill_style(mut self, style: PromptStyle) -> Self {
        self.fill_style = style;
        self
    }

    #[must_use]
    pub fn truncation_indicator(mut self, span: PromptSpan) -> Self {
        self.truncation_indicator = Some(span);
        self
    }

    #[must_use]
    pub fn render(&self, columns: usize) -> String {
        let spans = self.layout(columns);
        let mut output = String::with_capacity(columns.saturating_add(spans.len() * 16));
        for span in spans {
            let _ = write!(output, "{}", span.style.content_style().apply(span.text));
        }
        output.push_str(RESET_STYLE);
        output
    }

    #[must_use]
    pub fn render_plain(&self, columns: usize) -> String {
        self.layout(columns)
            .into_iter()
            .map(|span| span.text)
            .collect()
    }

    fn layout(&self, columns: usize) -> Vec<PromptSpan> {
        if columns == 0 {
            return Vec::new();
        }

        let right_width = spans_width(&self.right);
        if right_width >= columns {
            let right = take_suffix(&self.right, columns);
            let filler_width = columns.saturating_sub(spans_width(&right));
            if filler_width == 0 {
                return right;
            }

            let mut output = vec![PromptSpan {
                text: " ".repeat(filler_width),
                style: self.fill_style,
            }];
            output.extend(right);
            return output;
        }

        let left_limit = columns - right_width;
        let mut output = if spans_width(&self.left) > left_limit {
            self.truncated_left(left_limit)
        } else {
            self.left.clone()
        };
        let filler_width = columns
            .saturating_sub(spans_width(&output))
            .saturating_sub(right_width);
        if filler_width > 0 {
            output.push(PromptSpan {
                text: " ".repeat(filler_width),
                style: self.fill_style,
            });
        }
        output.extend(self.right.clone());
        output
    }

    fn truncated_left(&self, width: usize) -> Vec<PromptSpan> {
        let indicator = self
            .truncation_indicator
            .as_ref()
            .map_or_else(Vec::new, |span| {
                take_prefix(std::slice::from_ref(span), width)
            });
        let content_width = width.saturating_sub(spans_width(&indicator));
        let mut left = take_prefix(&self.left, content_width);
        left.extend(indicator);
        left
    }
}

pub fn validate_single_line(text: &str) -> Result<(), PromptError> {
    if text.contains(['\n', '\r']) {
        Err(PromptError::MultilineText)
    } else {
        Ok(())
    }
}

fn spans_width(spans: &[PromptSpan]) -> usize {
    spans.iter().map(PromptSpan::width).sum()
}

fn take_prefix(spans: &[PromptSpan], width: usize) -> Vec<PromptSpan> {
    let mut remaining = width;
    let mut output = Vec::new();
    for span in spans {
        if remaining == 0 {
            break;
        }
        let text = take_text_prefix(&span.text, remaining);
        let used = UnicodeWidthStr::width(text.as_str());
        if !text.is_empty() {
            output.push(PromptSpan {
                text,
                style: span.style,
            });
        }
        remaining = remaining.saturating_sub(used);
        if used < span.width() {
            break;
        }
    }
    output
}

fn take_suffix(spans: &[PromptSpan], width: usize) -> Vec<PromptSpan> {
    let mut remaining = width;
    let mut reversed = Vec::new();
    for span in spans.iter().rev() {
        if remaining == 0 {
            break;
        }
        let text = take_text_suffix(&span.text, remaining);
        let used = UnicodeWidthStr::width(text.as_str());
        if !text.is_empty() {
            reversed.push(PromptSpan {
                text,
                style: span.style,
            });
        }
        remaining = remaining.saturating_sub(used);
        if used < span.width() {
            break;
        }
    }
    reversed.reverse();
    reversed
}

fn take_text_prefix(text: &str, width: usize) -> String {
    let mut used = 0;
    text.graphemes(true)
        .take_while(|grapheme| {
            let next = used + UnicodeWidthStr::width(*grapheme);
            if next > width {
                return false;
            }
            used = next;
            true
        })
        .collect()
}

fn take_text_suffix(text: &str, width: usize) -> String {
    let mut used = 0;
    let mut graphemes = text
        .graphemes(true)
        .rev()
        .take_while(|grapheme| {
            let next = used + UnicodeWidthStr::width(*grapheme);
            if next > width {
                return false;
            }
            used = next;
            true
        })
        .collect::<Vec<_>>();
    graphemes.reverse();
    graphemes.concat()
}

#[cfg(test)]
mod tests {
    use super::{PromptAttribute, PromptColor, PromptError, PromptLine, PromptSpan, PromptStyle};

    #[test]
    fn prompt_span_rejects_multiline_and_control_text() {
        let style = PromptStyle::default();

        assert_eq!(
            PromptSpan::new("first\nsecond", style),
            Err(PromptError::MultilineText)
        );
        assert_eq!(
            PromptSpan::new("unsafe\x1b[31m", style),
            Err(PromptError::ControlCharacter('\x1b'))
        );
    }

    #[test]
    fn prompt_line_handles_unicode_width_and_right_alignment() {
        let line = PromptLine::new()
            .left(PromptSpan::new("界界界", PromptStyle::default()).unwrap())
            .right(PromptSpan::new("XY", PromptStyle::default()).unwrap())
            .truncation_indicator(PromptSpan::new("…", PromptStyle::default()).unwrap());

        assert_eq!(line.render_plain(5), "界…XY");

        let narrow =
            PromptLine::new().right(PromptSpan::new("界", PromptStyle::default()).unwrap());
        assert_eq!(narrow.render_plain(1), " ");
    }

    #[test]
    fn prompt_line_pads_to_width_and_resets_styles() {
        let fill = PromptStyle::default().background(PromptColor::Rgb {
            r: 36,
            g: 36,
            b: 36,
        });
        let brand = PromptStyle::default()
            .foreground(PromptColor::AnsiValue(154))
            .attribute(PromptAttribute::Bold);
        let line = PromptLine::new()
            .left(PromptSpan::new("MDV", brand).unwrap())
            .right(PromptSpan::new("HELP", fill).unwrap())
            .fill_style(fill);

        assert_eq!(line.render_plain(10), "MDV   HELP");
        let rendered = line.render(10);
        assert!(rendered.contains("\x1b["));
        assert!(rendered.ends_with("\x1b[0m"));
    }
}